clang 10.0.0git

SemaExpr.cpp
Go to the documentation of this file.
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/Builtins.h"
29 #include "clang/Basic/FixedPoint.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55 // See if this is an auto-typed variable whose initializer we are parsing.
56 if (ParsingInitForAutoVars.count(D))
57 return false;
58
59 // See if this is a deleted function.
60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61 if (FD->isDeleted())
62 return false;
63
64 // If the function has a deduced return type, and we can't deduce it,
65 // then we can't use it either.
66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68 return false;
69
70 // See if this is an aligned allocation/deallocation function that is
71 // unavailable.
72 if (TreatUnavailableAsInvalid &&
73 isUnavailableAlignedAllocationFunction(*FD))
74 return false;
75 }
76
77 // See if this function is unavailable.
78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
80 return false;
81
82 return true;
83 }
84
85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
86 // Warn if this is used but marked unused.
87 if (const auto *A = D->getAttr<UnusedAttr>()) {
88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
89 // should diagnose them.
90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
93 if (DC && !DC->hasAttr<UnusedAttr>())
94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
95 }
96 }
97 }
98
99 /// Emit a note explaining that this function is deleted.
100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
101 assert(Decl && Decl->isDeleted());
102
103 if (Decl->isDefaulted()) {
104 // If the method was explicitly defaulted, point at that declaration.
105 if (!Decl->isImplicit())
106 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
107
108 // Try to diagnose why this special member function was implicitly
109 // deleted. This might fail, if that reason no longer applies.
110 DiagnoseDeletedDefaultedFunction(Decl);
111 return;
112 }
113
114 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
115 if (Ctor && Ctor->isInheritingConstructor())
116 return NoteDeletedInheritingConstructor(Ctor);
117
118 Diag(Decl->getLocation(), diag::note_availability_specified_here)
119 << Decl << 1;
120 }
121
122 /// Determine whether a FunctionDecl was ever declared with an
123 /// explicit storage class.
124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
125 for (auto I : D->redecls()) {
126 if (I->getStorageClass() != SC_None)
127 return true;
128 }
129 return false;
130 }
131
132 /// Check whether we're in an extern inline function and referring to a
133 /// variable or function with internal linkage (C11 6.7.4p3).
134 ///
135 /// This is only a warning because we used to silently accept this code, but
136 /// in many cases it will not behave correctly. This is not enabled in C++ mode
137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
138 /// and so while there may still be user mistakes, most of the time we can't
139 /// prove that there are errors.
140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
141 const NamedDecl *D,
142 SourceLocation Loc) {
143 // This is disabled under C++; there are too many ways for this to fire in
144 // contexts where the warning is a false positive, or where it is technically
145 // correct but benign.
146 if (S.getLangOpts().CPlusPlus)
147 return;
148
149 // Check if this is an inlined function or method.
150 FunctionDecl *Current = S.getCurFunctionDecl();
151 if (!Current)
152 return;
153 if (!Current->isInlined())
154 return;
155 if (!Current->isExternallyVisible())
156 return;
157
158 // Check if the decl has internal linkage.
159 if (D->getFormalLinkage() != InternalLinkage)
160 return;
161
162 // Downgrade from ExtWarn to Extension if
163 // (1) the supposedly external inline function is in the main file,
164 // and probably won't be included anywhere else.
165 // (2) the thing we're referencing is a pure function.
166 // (3) the thing we're referencing is another inline function.
167 // This last can give us false negatives, but it's better than warning on
168 // wrappers for simple C library functions.
169 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
170 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
171 if (!DowngradeWarning && UsedFn)
172 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
173
174 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
175 : diag::ext_internal_in_extern_inline)
176 << /*IsVar=*/!UsedFn << D;
177
178 S.MaybeSuggestAddingStaticToDecl(Current);
179
180 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
181 << D;
182 }
183
184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
185 const FunctionDecl *First = Cur->getFirstDecl();
186
187 // Suggest "static" on the function, if possible.
188 if (!hasAnyExplicitStorageClass(First)) {
189 SourceLocation DeclBegin = First->getSourceRange().getBegin();
190 Diag(DeclBegin, diag::note_convert_inline_to_static)
191 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
192 }
193 }
194
195 /// Determine whether the use of this declaration is valid, and
196 /// emit any corresponding diagnostics.
197 ///
198 /// This routine diagnoses various problems with referencing
199 /// declarations that can occur when using a declaration. For example,
200 /// it might warn if a deprecated or unavailable declaration is being
201 /// used, or produce an error (and return true) if a C++0x deleted
202 /// function is being used.
203 ///
204 /// \returns true if there was an error (this declaration cannot be
205 /// referenced), false otherwise.
206 ///
207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
208 const ObjCInterfaceDecl *UnknownObjCClass,
209 bool ObjCPropertyAccess,
210 bool AvoidPartialAvailabilityChecks,
211 ObjCInterfaceDecl *ClassReceiver) {
212 SourceLocation Loc = Locs.front();
213 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
214 // If there were any diagnostics suppressed by template argument deduction,
215 // emit them now.
216 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
217 if (Pos != SuppressedDiagnostics.end()) {
218 for (const PartialDiagnosticAt &Suppressed : Pos->second)
219 Diag(Suppressed.first, Suppressed.second);
220
221 // Clear out the list of suppressed diagnostics, so that we don't emit
222 // them again for this specialization. However, we don't obsolete this
223 // entry from the table, because we want to avoid ever emitting these
224 // diagnostics again.
225 Pos->second.clear();
226 }
227
228 // C++ [basic.start.main]p3:
229 // The function 'main' shall not be used within a program.
230 if (cast<FunctionDecl>(D)->isMain())
231 Diag(Loc, diag::ext_main_used);
232
233 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
234 }
235
236 // See if this is an auto-typed variable whose initializer we are parsing.
237 if (ParsingInitForAutoVars.count(D)) {
238 if (isa<BindingDecl>(D)) {
239 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
240 << D->getDeclName();
241 } else {
242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
243 << D->getDeclName() << cast<VarDecl>(D)->getType();
244 }
245 return true;
246 }
247
248 // See if this is a deleted function.
249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
250 if (FD->isDeleted()) {
251 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
252 if (Ctor && Ctor->isInheritingConstructor())
253 Diag(Loc, diag::err_deleted_inherited_ctor_use)
254 << Ctor->getParent()
255 << Ctor->getInheritedConstructor().getConstructor()->getParent();
256 else
257 Diag(Loc, diag::err_deleted_function_use);
258 NoteDeletedFunction(FD);
259 return true;
260 }
261
262 // If the function has a deduced return type, and we can't deduce it,
263 // then we can't use it either.
264 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
265 DeduceReturnType(FD, Loc))
266 return true;
267
268 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
269 return true;
270 }
271
272 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
273 // Lambdas are only default-constructible or assignable in C++2a onwards.
274 if (MD->getParent()->isLambda() &&
275 ((isa<CXXConstructorDecl>(MD) &&
276 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
277 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
278 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
279 << !isa<CXXConstructorDecl>(MD);
280 }
281 }
282
283 auto getReferencedObjCProp = [](const NamedDecl *D) ->
284 const ObjCPropertyDecl * {
285 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
286 return MD->findPropertyDecl();
287 return nullptr;
288 };
289 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
290 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
291 return true;
292 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
293 return true;
294 }
295
296 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
297 // Only the variables omp_in and omp_out are allowed in the combiner.
298 // Only the variables omp_priv and omp_orig are allowed in the
299 // initializer-clause.
300 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
301 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
302 isa<VarDecl>(D)) {
303 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
304 << getCurFunction()->HasOMPDeclareReductionCombiner;
305 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
306 return true;
307 }
308
309 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
310 // List-items in map clauses on this construct may only refer to the declared
311 // variable var and entities that could be referenced by a procedure defined
312 // at the same location
313 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
314 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
315 isa<VarDecl>(D)) {
316 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
317 << DMD->getVarName().getAsString();
318 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
319 return true;
320 }
321
322 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
323 AvoidPartialAvailabilityChecks, ClassReceiver);
324
325 DiagnoseUnusedOfDecl(*this, D, Loc);
326
327 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
328
329 // [expr.prim.id]p4
330 // A program that refers explicitly or implicitly to a function with a
331 // trailing requires-clause whose constraint-expression is not satisfied,
332 // other than to declare it, is ill-formed. [...]
333 //
334 // See if this is a function with constraints that need to be satisfied.
335 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
336 if (Expr *RC = FD->getTrailingRequiresClause()) {
337 ConstraintSatisfaction Satisfaction;
338 bool Failed = CheckConstraintSatisfaction(FD, {RC}, /*TemplateArgs=*/{},
339 SourceRange(Loc), Satisfaction);
340 if (Failed)
341 // A diagnostic will have already been generated (non-constant
342 // constraint expression, for example)
343 return true;
344 if (!Satisfaction.IsSatisfied) {
345 Diag(Loc,
346 diag::err_reference_to_function_with_unsatisfied_constraints)
347 << D;
348 DiagnoseUnsatisfiedConstraint(Satisfaction);
349 return true;
350 }
351 }
352 }
353
354 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
355 !isUnevaluatedContext()) {
356 // C++ [expr.prim.req.nested] p3
357 // A local parameter shall only appear as an unevaluated operand
358 // (Clause 8) within the constraint-expression.
359 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
360 << D;
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 return false;
366 }
367
368 /// DiagnoseSentinelCalls - This routine checks whether a call or
369 /// message-send is to a declaration with the sentinel attribute, and
370 /// if so, it checks that the requirements of the sentinel are
371 /// satisfied.
372 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
373 ArrayRef<Expr *> Args) {
374 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
375 if (!attr)
376 return;
377
378 // The number of formal parameters of the declaration.
379 unsigned numFormalParams;
380
381 // The kind of declaration. This is also an index into a %select in
382 // the diagnostic.
383 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
384
385 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
386 numFormalParams = MD->param_size();
387 calleeType = CT_Method;
388 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
389 numFormalParams = FD->param_size();
390 calleeType = CT_Function;
391 } else if (isa<VarDecl>(D)) {
392 QualType type = cast<ValueDecl>(D)->getType();
393 const FunctionType *fn = nullptr;
394 if (const PointerType *ptr = type->getAs<PointerType>()) {
395 fn = ptr->getPointeeType()->getAs<FunctionType>();
396 if (!fn) return;
397 calleeType = CT_Function;
398 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
399 fn = ptr->getPointeeType()->castAs<FunctionType>();
400 calleeType = CT_Block;
401 } else {
402 return;
403 }
404
405 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
406 numFormalParams = proto->getNumParams();
407 } else {
408 numFormalParams = 0;
409 }
410 } else {
411 return;
412 }
413
414 // "nullPos" is the number of formal parameters at the end which
415 // effectively count as part of the variadic arguments. This is
416 // useful if you would prefer to not have *any* formal parameters,
417 // but the language forces you to have at least one.
418 unsigned nullPos = attr->getNullPos();
419 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
420 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
421
422 // The number of arguments which should follow the sentinel.
423 unsigned numArgsAfterSentinel = attr->getSentinel();
424
425 // If there aren't enough arguments for all the formal parameters,
426 // the sentinel, and the args after the sentinel, complain.
427 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
428 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
429 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
430 return;
431 }
432
433 // Otherwise, find the sentinel expression.
434 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
435 if (!sentinelExpr) return;
436 if (sentinelExpr->isValueDependent()) return;
437 if (Context.isSentinelNullExpr(sentinelExpr)) return;
438
439 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
440 // or 'NULL' if those are actually defined in the context. Only use
441 // 'nil' for ObjC methods, where it's much more likely that the
442 // variadic arguments form a list of object pointers.
443 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
444 std::string NullValue;
445 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
446 NullValue = "nil";
447 else if (getLangOpts().CPlusPlus11)
448 NullValue = "nullptr";
449 else if (PP.isMacroDefined("NULL"))
450 NullValue = "NULL";
451 else
452 NullValue = "(void*) 0";
453
454 if (MissingNilLoc.isInvalid())
455 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
456 else
457 Diag(MissingNilLoc, diag::warn_missing_sentinel)
458 << int(calleeType)
459 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461 }
462
463 SourceRange Sema::getExprRange(Expr *E) const {
464 return E ? E->getSourceRange() : SourceRange();
465 }
466
467 //===----------------------------------------------------------------------===//
468 // Standard Promotions and Conversions
469 //===----------------------------------------------------------------------===//
470
471 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
472 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
473 // Handle any placeholder expressions which made it here.
474 if (E->getType()->isPlaceholderType()) {
475 ExprResult result = CheckPlaceholderExpr(E);
476 if (result.isInvalid()) return ExprError();
477 E = result.get();
478 }
479
480 QualType Ty = E->getType();
481 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
482
483 if (Ty->isFunctionType()) {
484 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
485 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
486 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
487 return ExprError();
488
489 E = ImpCastExprToType(E, Context.getPointerType(Ty),
490 CK_FunctionToPointerDecay).get();
491 } else if (Ty->isArrayType()) {
492 // In C90 mode, arrays only promote to pointers if the array expression is
493 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
494 // type 'array of type' is converted to an expression that has type 'pointer
495 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
496 // that has type 'array of type' ...". The relevant change is "an lvalue"
497 // (C90) to "an expression" (C99).
498 //
499 // C++ 4.2p1:
500 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
501 // T" can be converted to an rvalue of type "pointer to T".
502 //
503 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
504 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
505 CK_ArrayToPointerDecay).get();
506 }
507 return E;
508 }
509
510 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
511 // Check to see if we are dereferencing a null pointer. If so,
512 // and if not volatile-qualified, this is undefined behavior that the
513 // optimizer will delete, so warn about it. People sometimes try to use this
514 // to get a deterministic trap and are surprised by clang's behavior. This
515 // only handles the pattern "*null", which is a very syntactic check.
516 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
517 if (UO && UO->getOpcode() == UO_Deref &&
518 UO->getSubExpr()->getType()->isPointerType()) {
519 const LangAS AS =
520 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
521 if ((!isTargetAddressSpace(AS) ||
522 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
523 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
524 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
525 !UO->getType().isVolatileQualified()) {
526 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
527 S.PDiag(diag::warn_indirection_through_null)
528 << UO->getSubExpr()->getSourceRange());
529 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
530 S.PDiag(diag::note_indirection_through_null));
531 }
532 }
533 }
534
535 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
536 SourceLocation AssignLoc,
537 const Expr* RHS) {
538 const ObjCIvarDecl *IV = OIRE->getDecl();
539 if (!IV)
540 return;
541
542 DeclarationName MemberName = IV->getDeclName();
543 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
544 if (!Member || !Member->isStr("isa"))
545 return;
546
547 const Expr *Base = OIRE->getBase();
548 QualType BaseType = Base->getType();
549 if (OIRE->isArrow())
550 BaseType = BaseType->getPointeeType();
551 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
552 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
553 ObjCInterfaceDecl *ClassDeclared = nullptr;
554 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
555 if (!ClassDeclared->getSuperClass()
556 && (*ClassDeclared->ivar_begin()) == IV) {
557 if (RHS) {
558 NamedDecl *ObjectSetClass =
559 S.LookupSingleName(S.TUScope,
560 &S.Context.Idents.get("object_setClass"),
561 SourceLocation(), S.LookupOrdinaryName);
562 if (ObjectSetClass) {
563 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
564 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
565 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
566 "object_setClass(")
567 << FixItHint::CreateReplacement(
568 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
569 << FixItHint::CreateInsertion(RHSLocEnd, ")");
570 }
571 else
572 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
573 } else {
574 NamedDecl *ObjectGetClass =
575 S.LookupSingleName(S.TUScope,
576 &S.Context.Idents.get("object_getClass"),
577 SourceLocation(), S.LookupOrdinaryName);
578 if (ObjectGetClass)
579 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
580 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
581 "object_getClass(")
582 << FixItHint::CreateReplacement(
583 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
584 else
585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
586 }
587 S.Diag(IV->getLocation(), diag::note_ivar_decl);
588 }
589 }
590 }
591
592 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
593 // Handle any placeholder expressions which made it here.
594 if (E->getType()->isPlaceholderType()) {
595 ExprResult result = CheckPlaceholderExpr(E);
596 if (result.isInvalid()) return ExprError();
597 E = result.get();
598 }
599
600 // C++ [conv.lval]p1:
601 // A glvalue of a non-function, non-array type T can be
602 // converted to a prvalue.
603 if (!E->isGLValue()) return E;
604
605 QualType T = E->getType();
606 assert(!T.isNull() && "r-value conversion on typeless expression?");
607
608 // We don't want to throw lvalue-to-rvalue casts on top of
609 // expressions of certain types in C++.
610 if (getLangOpts().CPlusPlus &&
611 (E->getType() == Context.OverloadTy ||
612 T->isDependentType() ||
613 T->isRecordType()))
614 return E;
615
616 // The C standard is actually really unclear on this point, and
617 // DR106 tells us what the result should be but not why. It's
618 // generally best to say that void types just doesn't undergo
619 // lvalue-to-rvalue at all. Note that expressions of unqualified
620 // 'void' type are never l-values, but qualified void can be.
621 if (T->isVoidType())
622 return E;
623
624 // OpenCL usually rejects direct accesses to values of 'half' type.
625 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
626 T->isHalfType()) {
627 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
628 << 0 << T;
629 return ExprError();
630 }
631
632 CheckForNullPointerDereference(*this, E);
633 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
634 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
635 &Context.Idents.get("object_getClass"),
636 SourceLocation(), LookupOrdinaryName);
637 if (ObjectGetClass)
638 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
639 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
640 << FixItHint::CreateReplacement(
641 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
642 else
643 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
644 }
645 else if (const ObjCIvarRefExpr *OIRE =
646 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
647 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
648
649 // C++ [conv.lval]p1:
650 // [...] If T is a non-class type, the type of the prvalue is the
651 // cv-unqualified version of T. Otherwise, the type of the
652 // rvalue is T.
653 //
654 // C99 6.3.2.1p2:
655 // If the lvalue has qualified type, the value has the unqualified
656 // version of the type of the lvalue; otherwise, the value has the
657 // type of the lvalue.
658 if (T.hasQualifiers())
659 T = T.getUnqualifiedType();
660
661 // Under the MS ABI, lock down the inheritance model now.
662 if (T->isMemberPointerType() &&
663 Context.getTargetInfo().getCXXABI().isMicrosoft())
664 (void)isCompleteType(E->getExprLoc(), T);
665
666 ExprResult Res = CheckLValueToRValueConversionOperand(E);
667 if (Res.isInvalid())
668 return Res;
669 E = Res.get();
670
671 // Loading a __weak object implicitly retains the value, so we need a cleanup to
672 // balance that.
673 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
674 Cleanup.setExprNeedsCleanups(true);
675
676 // C++ [conv.lval]p3:
677 // If T is cv std::nullptr_t, the result is a null pointer constant.
678 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
679 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
680
681 // C11 6.3.2.1p2:
682 // ... if the lvalue has atomic type, the value has the non-atomic version
683 // of the type of the lvalue ...
684 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
685 T = Atomic->getValueType().getUnqualifiedType();
686 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
687 nullptr, VK_RValue);
688 }
689
690 return Res;
691 }
692
693 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
694 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
695 if (Res.isInvalid())
696 return ExprError();
697 Res = DefaultLvalueConversion(Res.get());
698 if (Res.isInvalid())
699 return ExprError();
700 return Res;
701 }
702
703 /// CallExprUnaryConversions - a special case of an unary conversion
704 /// performed on a function designator of a call expression.
705 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
706 QualType Ty = E->getType();
707 ExprResult Res = E;
708 // Only do implicit cast for a function type, but not for a pointer
709 // to function type.
710 if (Ty->isFunctionType()) {
711 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
712 CK_FunctionToPointerDecay).get();
713 if (Res.isInvalid())
714 return ExprError();
715 }
716 Res = DefaultLvalueConversion(Res.get());
717 if (Res.isInvalid())
718 return ExprError();
719 return Res.get();
720 }
721
722 /// UsualUnaryConversions - Performs various conversions that are common to most
723 /// operators (C99 6.3). The conversions of array and function types are
724 /// sometimes suppressed. For example, the array->pointer conversion doesn't
725 /// apply if the array is an argument to the sizeof or address (&) operators.
726 /// In these instances, this routine should *not* be called.
727 ExprResult Sema::UsualUnaryConversions(Expr *E) {
728 // First, convert to an r-value.
729 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
730 if (Res.isInvalid())
731 return ExprError();
732 E = Res.get();
733
734 QualType Ty = E->getType();
735 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
736
737 // Half FP have to be promoted to float unless it is natively supported
738 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
739 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
740
741 // Try to perform integral promotions if the object has a theoretically
742 // promotable type.
743 if (Ty->isIntegralOrUnscopedEnumerationType()) {
744 // C99 6.3.1.1p2:
745 //
746 // The following may be used in an expression wherever an int or
747 // unsigned int may be used:
748 // - an object or expression with an integer type whose integer
749 // conversion rank is less than or equal to the rank of int
750 // and unsigned int.
751 // - A bit-field of type _Bool, int, signed int, or unsigned int.
752 //
753 // If an int can represent all values of the original type, the
754 // value is converted to an int; otherwise, it is converted to an
755 // unsigned int. These are called the integer promotions. All
756 // other types are unchanged by the integer promotions.
757
758 QualType PTy = Context.isPromotableBitField(E);
759 if (!PTy.isNull()) {
760 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
761 return E;
762 }
763 if (Ty->isPromotableIntegerType()) {
764 QualType PT = Context.getPromotedIntegerType(Ty);
765 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
766 return E;
767 }
768 }
769 return E;
770 }
771
772 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
773 /// do not have a prototype. Arguments that have type float or __fp16
774 /// are promoted to double. All other argument types are converted by
775 /// UsualUnaryConversions().
776 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
777 QualType Ty = E->getType();
778 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
779
780 ExprResult Res = UsualUnaryConversions(E);
781 if (Res.isInvalid())
782 return ExprError();
783 E = Res.get();
784
785 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
786 // promote to double.
787 // Note that default argument promotion applies only to float (and
788 // half/fp16); it does not apply to _Float16.
789 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
790 if (BTy && (BTy->getKind() == BuiltinType::Half ||
791 BTy->getKind() == BuiltinType::Float)) {
792 if (getLangOpts().OpenCL &&
793 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
794 if (BTy->getKind() == BuiltinType::Half) {
795 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
796 }
797 } else {
798 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
799 }
800 }
801
802 // C++ performs lvalue-to-rvalue conversion as a default argument
803 // promotion, even on class types, but note:
804 // C++11 [conv.lval]p2:
805 // When an lvalue-to-rvalue conversion occurs in an unevaluated
806 // operand or a subexpression thereof the value contained in the
807 // referenced object is not accessed. Otherwise, if the glvalue
808 // has a class type, the conversion copy-initializes a temporary
809 // of type T from the glvalue and the result of the conversion
810 // is a prvalue for the temporary.
811 // FIXME: add some way to gate this entire thing for correctness in
812 // potentially potentially evaluated contexts.
813 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
814 ExprResult Temp = PerformCopyInitialization(
815 InitializedEntity::InitializeTemporary(E->getType()),
816 E->getExprLoc(), E);
817 if (Temp.isInvalid())
818 return ExprError();
819 E = Temp.get();
820 }
821
822 return E;
823 }
824
825 /// Determine the degree of POD-ness for an expression.
826 /// Incomplete types are considered POD, since this check can be performed
827 /// when we're in an unevaluated context.
828 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
829 if (Ty->isIncompleteType()) {
830 // C++11 [expr.call]p7:
831 // After these conversions, if the argument does not have arithmetic,
832 // enumeration, pointer, pointer to member, or class type, the program
833 // is ill-formed.
834 //
835 // Since we've already performed array-to-pointer and function-to-pointer
836 // decay, the only such type in C++ is cv void. This also handles
837 // initializer lists as variadic arguments.
838 if (Ty->isVoidType())
839 return VAK_Invalid;
840
841 if (Ty->isObjCObjectType())
842 return VAK_Invalid;
843 return VAK_Valid;
844 }
845
846 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
847 return VAK_Invalid;
848
849 if (Ty.isCXX98PODType(Context))
850 return VAK_Valid;
851
852 // C++11 [expr.call]p7:
853 // Passing a potentially-evaluated argument of class type (Clause 9)
854 // having a non-trivial copy constructor, a non-trivial move constructor,
855 // or a non-trivial destructor, with no corresponding parameter,
856 // is conditionally-supported with implementation-defined semantics.
857 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
858 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
859 if (!Record->hasNonTrivialCopyConstructor() &&
860 !Record->hasNonTrivialMoveConstructor() &&
861 !Record->hasNonTrivialDestructor())
862 return VAK_ValidInCXX11;
863
864 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
865 return VAK_Valid;
866
867 if (Ty->isObjCObjectType())
868 return VAK_Invalid;
869
870 if (getLangOpts().MSVCCompat)
871 return VAK_MSVCUndefined;
872
873 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
874 // permitted to reject them. We should consider doing so.
875 return VAK_Undefined;
876 }
877
878 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
879 // Don't allow one to pass an Objective-C interface to a vararg.
880 const QualType &Ty = E->getType();
881 VarArgKind VAK = isValidVarArgType(Ty);
882
883 // Complain about passing non-POD types through varargs.
884 switch (VAK) {
885 case VAK_ValidInCXX11:
886 DiagRuntimeBehavior(
887 E->getBeginLoc(), nullptr,
888 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
889 LLVM_FALLTHROUGH;
890 case VAK_Valid:
891 if (Ty->isRecordType()) {
892 // This is unlikely to be what the user intended. If the class has a
893 // 'c_str' member function, the user probably meant to call that.
894 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
895 PDiag(diag::warn_pass_class_arg_to_vararg)
896 << Ty << CT << hasCStrMethod(E) << ".c_str()");
897 }
898 break;
899
900 case VAK_Undefined:
901 case VAK_MSVCUndefined:
902 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
903 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
904 << getLangOpts().CPlusPlus11 << Ty << CT);
905 break;
906
907 case VAK_Invalid:
908 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
909 Diag(E->getBeginLoc(),
910 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
911 << Ty << CT;
912 else if (Ty->isObjCObjectType())
913 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
914 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
915 << Ty << CT);
916 else
917 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
918 << isa<InitListExpr>(E) << Ty << CT;
919 break;
920 }
921 }
922
923 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
924 /// will create a trap if the resulting type is not a POD type.
925 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
926 FunctionDecl *FDecl) {
927 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
928 // Strip the unbridged-cast placeholder expression off, if applicable.
929 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
930 (CT == VariadicMethod ||
931 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
932 E = stripARCUnbridgedCast(E);
933
934 // Otherwise, do normal placeholder checking.
935 } else {
936 ExprResult ExprRes = CheckPlaceholderExpr(E);
937 if (ExprRes.isInvalid())
938 return ExprError();
939 E = ExprRes.get();
940 }
941 }
942
943 ExprResult ExprRes = DefaultArgumentPromotion(E);
944 if (ExprRes.isInvalid())
945 return ExprError();
946 E = ExprRes.get();
947
948 // Diagnostics regarding non-POD argument types are
949 // emitted along with format string checking in Sema::CheckFunctionCall().
950 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
951 // Turn this into a trap.
952 CXXScopeSpec SS;
953 SourceLocation TemplateKWLoc;
954 UnqualifiedId Name;
955 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
956 E->getBeginLoc());
957 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
958 /*HasTrailingLParen=*/true,
959 /*IsAddressOfOperand=*/false);
960 if (TrapFn.isInvalid())
961 return ExprError();
962
963 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
964 None, E->getEndLoc());
965 if (Call.isInvalid())
966 return ExprError();
967
968 ExprResult Comma =
969 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
970 if (Comma.isInvalid())
971 return ExprError();
972 return Comma.get();
973 }
974
975 if (!getLangOpts().CPlusPlus &&
976 RequireCompleteType(E->getExprLoc(), E->getType(),
977 diag::err_call_incomplete_argument))
978 return ExprError();
979
980 return E;
981 }
982
983 /// Converts an integer to complex float type. Helper function of
984 /// UsualArithmeticConversions()
985 ///
986 /// \return false if the integer expression is an integer type and is
987 /// successfully converted to the complex type.
988 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
989 ExprResult &ComplexExpr,
990 QualType IntTy,
991 QualType ComplexTy,
992 bool SkipCast) {
993 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
994 if (SkipCast) return false;
995 if (IntTy->isIntegerType()) {
996 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
997 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
998 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
999 CK_FloatingRealToComplex);
1000 } else {
1001 assert(IntTy->isComplexIntegerType());
1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1003 CK_IntegralComplexToFloatingComplex);
1004 }
1005 return false;
1006 }
1007
1008 /// Handle arithmetic conversion with complex types. Helper function of
1009 /// UsualArithmeticConversions()
1010 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1011 ExprResult &RHS, QualType LHSType,
1012 QualType RHSType,
1013 bool IsCompAssign) {
1014 // if we have an integer operand, the result is the complex type.
1015 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1016 /*skipCast*/false))
1017 return LHSType;
1018 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1019 /*skipCast*/IsCompAssign))
1020 return RHSType;
1021
1022 // This handles complex/complex, complex/float, or float/complex.
1023 // When both operands are complex, the shorter operand is converted to the
1024 // type of the longer, and that is the type of the result. This corresponds
1025 // to what is done when combining two real floating-point operands.
1026 // The fun begins when size promotion occur across type domains.
1027 // From H&S 6.3.4: When one operand is complex and the other is a real
1028 // floating-point type, the less precise type is converted, within it's
1029 // real or complex domain, to the precision of the other type. For example,
1030 // when combining a "long double" with a "double _Complex", the
1031 // "double _Complex" is promoted to "long double _Complex".
1032
1033 // Compute the rank of the two types, regardless of whether they are complex.
1034 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1035
1036 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1037 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1038 QualType LHSElementType =
1039 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1040 QualType RHSElementType =
1041 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1042
1043 QualType ResultType = S.Context.getComplexType(LHSElementType);
1044 if (Order < 0) {
1045 // Promote the precision of the LHS if not an assignment.
1046 ResultType = S.Context.getComplexType(RHSElementType);
1047 if (!IsCompAssign) {
1048 if (LHSComplexType)
1049 LHS =
1050 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1051 else
1052 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1053 }
1054 } else if (Order > 0) {
1055 // Promote the precision of the RHS.
1056 if (RHSComplexType)
1057 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1058 else
1059 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1060 }
1061 return ResultType;
1062 }
1063
1064 /// Handle arithmetic conversion from integer to float. Helper function
1065 /// of UsualArithmeticConversions()
1066 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1067 ExprResult &IntExpr,
1068 QualType FloatTy, QualType IntTy,
1069 bool ConvertFloat, bool ConvertInt) {
1070 if (IntTy->isIntegerType()) {
1071 if (ConvertInt)
1072 // Convert intExpr to the lhs floating point type.
1073 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1074 CK_IntegralToFloating);
1075 return FloatTy;
1076 }
1077
1078 // Convert both sides to the appropriate complex float.
1079 assert(IntTy->isComplexIntegerType());
1080 QualType result = S.Context.getComplexType(FloatTy);
1081
1082 // _Complex int -> _Complex float
1083 if (ConvertInt)
1084 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1085 CK_IntegralComplexToFloatingComplex);
1086
1087 // float -> _Complex float
1088 if (ConvertFloat)
1089 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1090 CK_FloatingRealToComplex);
1091
1092 return result;
1093 }
1094
1095 /// Handle arithmethic conversion with floating point types. Helper
1096 /// function of UsualArithmeticConversions()
1097 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1098 ExprResult &RHS, QualType LHSType,
1099 QualType RHSType, bool IsCompAssign) {
1100 bool LHSFloat = LHSType->isRealFloatingType();
1101 bool RHSFloat = RHSType->isRealFloatingType();
1102
1103 // If we have two real floating types, convert the smaller operand
1104 // to the bigger result.
1105 if (LHSFloat && RHSFloat) {
1106 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1107 if (order > 0) {
1108 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1109 return LHSType;
1110 }
1111
1112 assert(order < 0 && "illegal float comparison");
1113 if (!IsCompAssign)
1114 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1115 return RHSType;
1116 }
1117
1118 if (LHSFloat) {
1119 // Half FP has to be promoted to float unless it is natively supported
1120 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1121 LHSType = S.Context.FloatTy;
1122
1123 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1124 /*ConvertFloat=*/!IsCompAssign,
1125 /*ConvertInt=*/ true);
1126 }
1127 assert(RHSFloat);
1128 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1129 /*convertInt=*/ true,
1130 /*convertFloat=*/!IsCompAssign);
1131 }
1132
1133 /// Diagnose attempts to convert between __float128 and long double if
1134 /// there is no support for such conversion. Helper function of
1135 /// UsualArithmeticConversions().
1136 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1137 QualType RHSType) {
1138 /* No issue converting if at least one of the types is not a floating point
1139 type or the two types have the same rank.
1140 */
1141 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1142 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1143 return false;
1144
1145 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1146 "The remaining types must be floating point types.");
1147
1148 auto *LHSComplex = LHSType->getAs<ComplexType>();
1149 auto *RHSComplex = RHSType->getAs<ComplexType>();
1150
1151 QualType LHSElemType = LHSComplex ?
1152 LHSComplex->getElementType() : LHSType;
1153 QualType RHSElemType = RHSComplex ?
1154 RHSComplex->getElementType() : RHSType;
1155
1156 // No issue if the two types have the same representation
1157 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1158 &S.Context.getFloatTypeSemantics(RHSElemType))
1159 return false;
1160
1161 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1162 RHSElemType == S.Context.LongDoubleTy);
1163 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1164 RHSElemType == S.Context.Float128Ty);
1165
1166 // We've handled the situation where __float128 and long double have the same
1167 // representation. We allow all conversions for all possible long double types
1168 // except PPC's double double.
1169 return Float128AndLongDouble &&
1170 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1171 &llvm::APFloat::PPCDoubleDouble());
1172 }
1173
1174 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1175
1176 namespace {
1177 /// These helper callbacks are placed in an anonymous namespace to
1178 /// permit their use as function template parameters.
1179 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1180 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1181 }
1182
1183 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1184 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1185 CK_IntegralComplexCast);
1186 }
1187 }
1188
1189 /// Handle integer arithmetic conversions. Helper function of
1190 /// UsualArithmeticConversions()
1191 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1192 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 // The rules for this case are in C99 6.3.1.8
1196 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1197 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1198 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1199 if (LHSSigned == RHSSigned) {
1200 // Same signedness; use the higher-ranked type
1201 if (order >= 0) {
1202 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1203 return LHSType;
1204 } else if (!IsCompAssign)
1205 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1206 return RHSType;
1207 } else if (order != (LHSSigned ? 1 : -1)) {
1208 // The unsigned type has greater than or equal rank to the
1209 // signed type, so use the unsigned type
1210 if (RHSSigned) {
1211 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1212 return LHSType;
1213 } else if (!IsCompAssign)
1214 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1215 return RHSType;
1216 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1217 // The two types are different widths; if we are here, that
1218 // means the signed type is larger than the unsigned type, so
1219 // use the signed type.
1220 if (LHSSigned) {
1221 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1222 return LHSType;
1223 } else if (!IsCompAssign)
1224 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1225 return RHSType;
1226 } else {
1227 // The signed type is higher-ranked than the unsigned type,
1228 // but isn't actually any bigger (like unsigned int and long
1229 // on most 32-bit systems). Use the unsigned type corresponding
1230 // to the signed type.
1231 QualType result =
1232 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1233 RHS = (*doRHSCast)(S, RHS.get(), result);
1234 if (!IsCompAssign)
1235 LHS = (*doLHSCast)(S, LHS.get(), result);
1236 return result;
1237 }
1238 }
1239
1240 /// Handle conversions with GCC complex int extension. Helper function
1241 /// of UsualArithmeticConversions()
1242 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1243 ExprResult &RHS, QualType LHSType,
1244 QualType RHSType,
1245 bool IsCompAssign) {
1246 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1247 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1248
1249 if (LHSComplexInt && RHSComplexInt) {
1250 QualType LHSEltType = LHSComplexInt->getElementType();
1251 QualType RHSEltType = RHSComplexInt->getElementType();
1252 QualType ScalarType =
1253 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1254 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1255
1256 return S.Context.getComplexType(ScalarType);
1257 }
1258
1259 if (LHSComplexInt) {
1260 QualType LHSEltType = LHSComplexInt->getElementType();
1261 QualType ScalarType =
1262 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1263 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1264 QualType ComplexType = S.Context.getComplexType(ScalarType);
1265 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1266 CK_IntegralRealToComplex);
1267
1268 return ComplexType;
1269 }
1270
1271 assert(RHSComplexInt);
1272
1273 QualType RHSEltType = RHSComplexInt->getElementType();
1274 QualType ScalarType =
1275 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1276 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1277 QualType ComplexType = S.Context.getComplexType(ScalarType);
1278
1279 if (!IsCompAssign)
1280 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1281 CK_IntegralRealToComplex);
1282 return ComplexType;
1283 }
1284
1285 /// Return the rank of a given fixed point or integer type. The value itself
1286 /// doesn't matter, but the values must be increasing with proper increasing
1287 /// rank as described in N1169 4.1.1.
1288 static unsigned GetFixedPointRank(QualType Ty) {
1289 const auto *BTy = Ty->getAs<BuiltinType>();
1290 assert(BTy && "Expected a builtin type.");
1291
1292 switch (BTy->getKind()) {
1293 case BuiltinType::ShortFract:
1294 case BuiltinType::UShortFract:
1295 case BuiltinType::SatShortFract:
1296 case BuiltinType::SatUShortFract:
1297 return 1;
1298 case BuiltinType::Fract:
1299 case BuiltinType::UFract:
1300 case BuiltinType::SatFract:
1301 case BuiltinType::SatUFract:
1302 return 2;
1303 case BuiltinType::LongFract:
1304 case BuiltinType::ULongFract:
1305 case BuiltinType::SatLongFract:
1306 case BuiltinType::SatULongFract:
1307 return 3;
1308 case BuiltinType::ShortAccum:
1309 case BuiltinType::UShortAccum:
1310 case BuiltinType::SatShortAccum:
1311 case BuiltinType::SatUShortAccum:
1312 return 4;
1313 case BuiltinType::Accum:
1314 case BuiltinType::UAccum:
1315 case BuiltinType::SatAccum:
1316 case BuiltinType::SatUAccum:
1317 return 5;
1318 case BuiltinType::LongAccum:
1319 case BuiltinType::ULongAccum:
1320 case BuiltinType::SatLongAccum:
1321 case BuiltinType::SatULongAccum:
1322 return 6;
1323 default:
1324 if (BTy->isInteger())
1325 return 0;
1326 llvm_unreachable("Unexpected fixed point or integer type");
1327 }
1328 }
1329
1330 /// handleFixedPointConversion - Fixed point operations between fixed
1331 /// point types and integers or other fixed point types do not fall under
1332 /// usual arithmetic conversion since these conversions could result in loss
1333 /// of precsision (N1169 4.1.4). These operations should be calculated with
1334 /// the full precision of their result type (N1169 4.1.6.2.1).
1335 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1336 QualType RHSTy) {
1337 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1338 "Expected at least one of the operands to be a fixed point type");
1339 assert((LHSTy->isFixedPointOrIntegerType() ||
1340 RHSTy->isFixedPointOrIntegerType()) &&
1341 "Special fixed point arithmetic operation conversions are only "
1342 "applied to ints or other fixed point types");
1343
1344 // If one operand has signed fixed-point type and the other operand has
1345 // unsigned fixed-point type, then the unsigned fixed-point operand is
1346 // converted to its corresponding signed fixed-point type and the resulting
1347 // type is the type of the converted operand.
1348 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1349 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1350 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1351 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1352
1353 // The result type is the type with the highest rank, whereby a fixed-point
1354 // conversion rank is always greater than an integer conversion rank; if the
1355 // type of either of the operands is a saturating fixedpoint type, the result
1356 // type shall be the saturating fixed-point type corresponding to the type
1357 // with the highest rank; the resulting value is converted (taking into
1358 // account rounding and overflow) to the precision of the resulting type.
1359 // Same ranks between signed and unsigned types are resolved earlier, so both
1360 // types are either signed or both unsigned at this point.
1361 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1362 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1363
1364 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1365
1366 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1367 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1368
1369 return ResultTy;
1370 }
1371
1372 /// Check that the usual arithmetic conversions can be performed on this pair of
1373 /// expressions that might be of enumeration type.
1374 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1375 SourceLocation Loc,
1376 Sema::ArithConvKind ACK) {
1377 // C++2a [expr.arith.conv]p1:
1378 // If one operand is of enumeration type and the other operand is of a
1379 // different enumeration type or a floating-point type, this behavior is
1380 // deprecated ([depr.arith.conv.enum]).
1381 //
1382 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1383 // Eventually we will presumably reject these cases (in C++23 onwards?).
1384 QualType L = LHS->getType(), R = RHS->getType();
1385 bool LEnum = L->isUnscopedEnumerationType(),
1386 REnum = R->isUnscopedEnumerationType();
1387 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1388 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1389 (REnum && L->isFloatingType())) {
1390 S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1391 ? diag::warn_arith_conv_enum_float_cxx2a
1392 : diag::warn_arith_conv_enum_float)
1393 << LHS->getSourceRange() << RHS->getSourceRange()
1394 << (int)ACK << LEnum << L << R;
1395 } else if (!IsCompAssign && LEnum && REnum &&
1396 !S.Context.hasSameUnqualifiedType(L, R)) {
1397 unsigned DiagID;
1398 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1399 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1400 // If either enumeration type is unnamed, it's less likely that the
1401 // user cares about this, but this situation is still deprecated in
1402 // C++2a. Use a different warning group.
1403 DiagID = S.getLangOpts().CPlusPlus2a
1404 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1405 : diag::warn_arith_conv_mixed_anon_enum_types;
1406 } else if (ACK == Sema::ACK_Conditional) {
1407 // Conditional expressions are separated out because they have
1408 // historically had a different warning flag.
1409 DiagID = S.getLangOpts().CPlusPlus2a
1410 ? diag::warn_conditional_mixed_enum_types_cxx2a
1411 : diag::warn_conditional_mixed_enum_types;
1412 } else if (ACK == Sema::ACK_Comparison) {
1413 // Comparison expressions are separated out because they have
1414 // historically had a different warning flag.
1415 DiagID = S.getLangOpts().CPlusPlus2a
1416 ? diag::warn_comparison_mixed_enum_types_cxx2a
1417 : diag::warn_comparison_mixed_enum_types;
1418 } else {
1419 DiagID = S.getLangOpts().CPlusPlus2a
1420 ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1421 : diag::warn_arith_conv_mixed_enum_types;
1422 }
1423 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1424 << (int)ACK << L << R;
1425 }
1426 }
1427
1428 /// UsualArithmeticConversions - Performs various conversions that are common to
1429 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1430 /// routine returns the first non-arithmetic type found. The client is
1431 /// responsible for emitting appropriate error diagnostics.
1432 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1433 SourceLocation Loc,
1434 ArithConvKind ACK) {
1435 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1436
1437 if (ACK != ACK_CompAssign) {
1438 LHS = UsualUnaryConversions(LHS.get());
1439 if (LHS.isInvalid())
1440 return QualType();
1441 }
1442
1443 RHS = UsualUnaryConversions(RHS.get());
1444 if (RHS.isInvalid())
1445 return QualType();
1446
1447 // For conversion purposes, we ignore any qualifiers.
1448 // For example, "const float" and "float" are equivalent.
1449 QualType LHSType =
1450 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1451 QualType RHSType =
1452 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1453
1454 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1455 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1456 LHSType = AtomicLHS->getValueType();
1457
1458 // If both types are identical, no conversion is needed.
1459 if (LHSType == RHSType)
1460 return LHSType;
1461
1462 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1463 // The caller can deal with this (e.g. pointer + int).
1464 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1465 return QualType();
1466
1467 // Apply unary and bitfield promotions to the LHS's type.
1468 QualType LHSUnpromotedType = LHSType;
1469 if (LHSType->isPromotableIntegerType())
1470 LHSType = Context.getPromotedIntegerType(LHSType);
1471 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1472 if (!LHSBitfieldPromoteTy.isNull())
1473 LHSType = LHSBitfieldPromoteTy;
1474 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1475 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1476
1477 // If both types are identical, no conversion is needed.
1478 if (LHSType == RHSType)
1479 return LHSType;
1480
1481 // At this point, we have two different arithmetic types.
1482
1483 // Diagnose attempts to convert between __float128 and long double where
1484 // such conversions currently can't be handled.
1485 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1486 return QualType();
1487
1488 // Handle complex types first (C99 6.3.1.8p1).
1489 if (LHSType->isComplexType() || RHSType->isComplexType())
1490 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1491 ACK == ACK_CompAssign);
1492
1493 // Now handle "real" floating types (i.e. float, double, long double).
1494 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1495 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1496 ACK == ACK_CompAssign);
1497
1498 // Handle GCC complex int extension.
1499 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1500 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1501 ACK == ACK_CompAssign);
1502
1503 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1504 return handleFixedPointConversion(*this, LHSType, RHSType);
1505
1506 // Finally, we have two differing integer types.
1507 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1508 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1509 }
1510
1511 //===----------------------------------------------------------------------===//
1512 // Semantic Analysis for various Expression Types
1513 //===----------------------------------------------------------------------===//
1514
1515
1516 ExprResult
1517 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1518 SourceLocation DefaultLoc,
1519 SourceLocation RParenLoc,
1520 Expr *ControllingExpr,
1521 ArrayRef<ParsedType> ArgTypes,
1522 ArrayRef<Expr *> ArgExprs) {
1523 unsigned NumAssocs = ArgTypes.size();
1524 assert(NumAssocs == ArgExprs.size());
1525
1526 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1527 for (unsigned i = 0; i < NumAssocs; ++i) {
1528 if (ArgTypes[i])
1529 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1530 else
1531 Types[i] = nullptr;
1532 }
1533
1534 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1535 ControllingExpr,
1536 llvm::makeArrayRef(Types, NumAssocs),
1537 ArgExprs);
1538 delete [] Types;
1539 return ER;
1540 }
1541
1542 ExprResult
1543 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1544 SourceLocation DefaultLoc,
1545 SourceLocation RParenLoc,
1546 Expr *ControllingExpr,
1547 ArrayRef<TypeSourceInfo *> Types,
1548 ArrayRef<Expr *> Exprs) {
1549 unsigned NumAssocs = Types.size();
1550 assert(NumAssocs == Exprs.size());
1551
1552 // Decay and strip qualifiers for the controlling expression type, and handle
1553 // placeholder type replacement. See committee discussion from WG14 DR423.
1554 {
1555 EnterExpressionEvaluationContext Unevaluated(
1556 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1557 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1558 if (R.isInvalid())
1559 return ExprError();
1560 ControllingExpr = R.get();
1561 }
1562
1563 // The controlling expression is an unevaluated operand, so side effects are
1564 // likely unintended.
1565 if (!inTemplateInstantiation() &&
1566 ControllingExpr->HasSideEffects(Context, false))
1567 Diag(ControllingExpr->getExprLoc(),
1568 diag::warn_side_effects_unevaluated_context);
1569
1570 bool TypeErrorFound = false,
1571 IsResultDependent = ControllingExpr->isTypeDependent(),
1572 ContainsUnexpandedParameterPack
1573 = ControllingExpr->containsUnexpandedParameterPack();
1574
1575 for (unsigned i = 0; i < NumAssocs; ++i) {
1576 if (Exprs[i]->containsUnexpandedParameterPack())
1577 ContainsUnexpandedParameterPack = true;
1578
1579 if (Types[i]) {
1580 if (Types[i]->getType()->containsUnexpandedParameterPack())
1581 ContainsUnexpandedParameterPack = true;
1582
1583 if (Types[i]->getType()->isDependentType()) {
1584 IsResultDependent = true;
1585 } else {
1586 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1587 // complete object type other than a variably modified type."
1588 unsigned D = 0;
1589 if (Types[i]->getType()->isIncompleteType())
1590 D = diag::err_assoc_type_incomplete;
1591 else if (!Types[i]->getType()->isObjectType())
1592 D = diag::err_assoc_type_nonobject;
1593 else if (Types[i]->getType()->isVariablyModifiedType())
1594 D = diag::err_assoc_type_variably_modified;
1595
1596 if (D != 0) {
1597 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1598 << Types[i]->getTypeLoc().getSourceRange()
1599 << Types[i]->getType();
1600 TypeErrorFound = true;
1601 }
1602
1603 // C11 6.5.1.1p2 "No two generic associations in the same generic
1604 // selection shall specify compatible types."
1605 for (unsigned j = i+1; j < NumAssocs; ++j)
1606 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1607 Context.typesAreCompatible(Types[i]->getType(),
1608 Types[j]->getType())) {
1609 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1610 diag::err_assoc_compatible_types)
1611 << Types[j]->getTypeLoc().getSourceRange()
1612 << Types[j]->getType()
1613 << Types[i]->getType();
1614 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1615 diag::note_compat_assoc)
1616 << Types[i]->getTypeLoc().getSourceRange()
1617 << Types[i]->getType();
1618 TypeErrorFound = true;
1619 }
1620 }
1621 }
1622 }
1623 if (TypeErrorFound)
1624 return ExprError();
1625
1626 // If we determined that the generic selection is result-dependent, don't
1627 // try to compute the result expression.
1628 if (IsResultDependent)
1629 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1630 Exprs, DefaultLoc, RParenLoc,
1631 ContainsUnexpandedParameterPack);
1632
1633 SmallVector<unsigned, 1> CompatIndices;
1634 unsigned DefaultIndex = -1U;
1635 for (unsigned i = 0; i < NumAssocs; ++i) {
1636 if (!Types[i])
1637 DefaultIndex = i;
1638 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1639 Types[i]->getType()))
1640 CompatIndices.push_back(i);
1641 }
1642
1643 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1644 // type compatible with at most one of the types named in its generic
1645 // association list."
1646 if (CompatIndices.size() > 1) {
1647 // We strip parens here because the controlling expression is typically
1648 // parenthesized in macro definitions.
1649 ControllingExpr = ControllingExpr->IgnoreParens();
1650 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1651 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1652 << (unsigned)CompatIndices.size();
1653 for (unsigned I : CompatIndices) {
1654 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1655 diag::note_compat_assoc)
1656 << Types[I]->getTypeLoc().getSourceRange()
1657 << Types[I]->getType();
1658 }
1659 return ExprError();
1660 }
1661
1662 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1663 // its controlling expression shall have type compatible with exactly one of
1664 // the types named in its generic association list."
1665 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1666 // We strip parens here because the controlling expression is typically
1667 // parenthesized in macro definitions.
1668 ControllingExpr = ControllingExpr->IgnoreParens();
1669 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1670 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1671 return ExprError();
1672 }
1673
1674 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1675 // type name that is compatible with the type of the controlling expression,
1676 // then the result expression of the generic selection is the expression
1677 // in that generic association. Otherwise, the result expression of the
1678 // generic selection is the expression in the default generic association."
1679 unsigned ResultIndex =
1680 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1681
1682 return GenericSelectionExpr::Create(
1683 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1684 ContainsUnexpandedParameterPack, ResultIndex);
1685 }
1686
1687 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1688 /// location of the token and the offset of the ud-suffix within it.
1689 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1690 unsigned Offset) {
1691 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1692 S.getLangOpts());
1693 }
1694
1695 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1696 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1697 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1698 IdentifierInfo *UDSuffix,
1699 SourceLocation UDSuffixLoc,
1700 ArrayRef<Expr*> Args,
1701 SourceLocation LitEndLoc) {
1702 assert(Args.size() <= 2 && "too many arguments for literal operator");
1703
1704 QualType ArgTy[2];
1705 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1706 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1707 if (ArgTy[ArgIdx]->isArrayType())
1708 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1709 }
1710
1711 DeclarationName OpName =
1712 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1713 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1714 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1715
1716 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1717 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1718 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1719 /*AllowStringTemplate*/ false,
1720 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1721 return ExprError();
1722
1723 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1724 }
1725
1726 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1727 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1728 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1729 /// multiple tokens. However, the common case is that StringToks points to one
1730 /// string.
1731 ///
1732 ExprResult
1733 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1734 assert(!StringToks.empty() && "Must have at least one string!");
1735
1736 StringLiteralParser Literal(StringToks, PP);
1737 if (Literal.hadError)
1738 return ExprError();
1739
1740 SmallVector<SourceLocation, 4> StringTokLocs;
1741 for (const Token &Tok : StringToks)
1742 StringTokLocs.push_back(Tok.getLocation());
1743
1744 QualType CharTy = Context.CharTy;
1745 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1746 if (Literal.isWide()) {
1747 CharTy = Context.getWideCharType();
1748 Kind = StringLiteral::Wide;
1749 } else if (Literal.isUTF8()) {
1750 if (getLangOpts().Char8)
1751 CharTy = Context.Char8Ty;
1752 Kind = StringLiteral::UTF8;
1753 } else if (Literal.isUTF16()) {
1754 CharTy = Context.Char16Ty;
1755 Kind = StringLiteral::UTF16;
1756 } else if (Literal.isUTF32()) {
1757 CharTy = Context.Char32Ty;
1758 Kind = StringLiteral::UTF32;
1759 } else if (Literal.isPascal()) {
1760 CharTy = Context.UnsignedCharTy;
1761 }
1762
1763 // Warn on initializing an array of char from a u8 string literal; this
1764 // becomes ill-formed in C++2a.
1765 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1766 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1767 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1768
1769 // Create removals for all 'u8' prefixes in the string literal(s). This
1770 // ensures C++2a compatibility (but may change the program behavior when
1771 // built by non-Clang compilers for which the execution character set is
1772 // not always UTF-8).
1773 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1774 SourceLocation RemovalDiagLoc;
1775 for (const Token &Tok : StringToks) {
1776 if (Tok.getKind() == tok::utf8_string_literal) {
1777 if (RemovalDiagLoc.isInvalid())
1778 RemovalDiagLoc = Tok.getLocation();
1779 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1780 Tok.getLocation(),
1781 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1782 getSourceManager(), getLangOpts())));
1783 }
1784 }
1785 Diag(RemovalDiagLoc, RemovalDiag);
1786 }
1787
1788 QualType StrTy =
1789 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1790
1791 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1792 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1793 Kind, Literal.Pascal, StrTy,
1794 &StringTokLocs[0],
1795 StringTokLocs.size());
1796 if (Literal.getUDSuffix().empty())
1797 return Lit;
1798
1799 // We're building a user-defined literal.
1800 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1801 SourceLocation UDSuffixLoc =
1802 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1803 Literal.getUDSuffixOffset());
1804
1805 // Make sure we're allowed user-defined literals here.
1806 if (!UDLScope)
1807 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1808
1809 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1810 // operator "" X (str, len)
1811 QualType SizeType = Context.getSizeType();
1812
1813 DeclarationName OpName =
1814 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1815 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1816 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1817
1818 QualType ArgTy[] = {
1819 Context.getArrayDecayedType(StrTy), SizeType
1820 };
1821
1822 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1823 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1824 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1825 /*AllowStringTemplate*/ true,
1826 /*DiagnoseMissing*/ true)) {
1827
1828 case LOLR_Cooked: {
1829 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1830 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1831 StringTokLocs[0]);
1832 Expr *Args[] = { Lit, LenArg };
1833
1834 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1835 }
1836
1837 case LOLR_StringTemplate: {
1838 TemplateArgumentListInfo ExplicitArgs;
1839
1840 unsigned CharBits = Context.getIntWidth(CharTy);
1841 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1842 llvm::APSInt Value(CharBits, CharIsUnsigned);
1843
1844 TemplateArgument TypeArg(CharTy);
1845 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1846 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1847
1848 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1849 Value = Lit->getCodeUnit(I);
1850 TemplateArgument Arg(Context, Value, CharTy);
1851 TemplateArgumentLocInfo ArgInfo;
1852 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1853 }
1854 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1855 &ExplicitArgs);
1856 }
1857 case LOLR_Raw:
1858 case LOLR_Template:
1859 case LOLR_ErrorNoDiagnostic:
1860 llvm_unreachable("unexpected literal operator lookup result");
1861 case LOLR_Error:
1862 return ExprError();
1863 }
1864 llvm_unreachable("unexpected literal operator lookup result");
1865 }
1866
1867 DeclRefExpr *
1868 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1869 SourceLocation Loc,
1870 const CXXScopeSpec *SS) {
1871 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1872 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1873 }
1874
1875 DeclRefExpr *
1876 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1877 const DeclarationNameInfo &NameInfo,
1878 const CXXScopeSpec *SS, NamedDecl *FoundD,
1879 SourceLocation TemplateKWLoc,
1880 const TemplateArgumentListInfo *TemplateArgs) {
1881 NestedNameSpecifierLoc NNS =
1882 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1883 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1884 TemplateArgs);
1885 }
1886
1887 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1888 // A declaration named in an unevaluated operand never constitutes an odr-use.
1889 if (isUnevaluatedContext())
1890 return NOUR_Unevaluated;
1891
1892 // C++2a [basic.def.odr]p4:
1893 // A variable x whose name appears as a potentially-evaluated expression e
1894 // is odr-used by e unless [...] x is a reference that is usable in
1895 // constant expressions.
1896 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1897 if (VD->getType()->isReferenceType() &&
1898 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1899 VD->isUsableInConstantExpressions(Context))
1900 return NOUR_Constant;
1901 }
1902
1903 // All remaining non-variable cases constitute an odr-use. For variables, we
1904 // need to wait and see how the expression is used.
1905 return NOUR_None;
1906 }
1907
1908 /// BuildDeclRefExpr - Build an expression that references a
1909 /// declaration that does not require a closure capture.
1910 DeclRefExpr *
1911 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1912 const DeclarationNameInfo &NameInfo,
1913 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1914 SourceLocation TemplateKWLoc,
1915 const TemplateArgumentListInfo *TemplateArgs) {
1916 bool RefersToCapturedVariable =
1917 isa<VarDecl>(D) &&
1918 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1919
1920 DeclRefExpr *E = DeclRefExpr::Create(
1921 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1922 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1923 MarkDeclRefReferenced(E);
1924
1925 // C++ [except.spec]p17:
1926 // An exception-specification is considered to be needed when:
1927 // - in an expression, the function is the unique lookup result or
1928 // the selected member of a set of overloaded functions.
1929 //
1930 // We delay doing this until after we've built the function reference and
1931 // marked it as used so that:
1932 // a) if the function is defaulted, we get errors from defining it before /
1933 // instead of errors from computing its exception specification, and
1934 // b) if the function is a defaulted comparison, we can use the body we
1935 // build when defining it as input to the exception specification
1936 // computation rather than computing a new body.
1937 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1938 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1939 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1940 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1941 }
1942 }
1943
1944 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1945 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1946 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1947 getCurFunction()->recordUseOfWeak(E);
1948
1949 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1950 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1951 FD = IFD->getAnonField();
1952 if (FD) {
1953 UnusedPrivateFields.remove(FD);
1954 // Just in case we're building an illegal pointer-to-member.
1955 if (FD->isBitField())
1956 E->setObjectKind(OK_BitField);
1957 }
1958
1959 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1960 // designates a bit-field.
1961 if (auto *BD = dyn_cast<BindingDecl>(D))
1962 if (auto *BE = BD->getBinding())
1963 E->setObjectKind(BE->getObjectKind());
1964
1965 return E;
1966 }
1967
1968 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1969 /// possibly a list of template arguments.
1970 ///
1971 /// If this produces template arguments, it is permitted to call
1972 /// DecomposeTemplateName.
1973 ///
1974 /// This actually loses a lot of source location information for
1975 /// non-standard name kinds; we should consider preserving that in
1976 /// some way.
1977 void
1978 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1979 TemplateArgumentListInfo &Buffer,
1980 DeclarationNameInfo &NameInfo,
1981 const TemplateArgumentListInfo *&TemplateArgs) {
1982 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1983 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1984 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1985
1986 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1987 Id.TemplateId->NumArgs);
1988 translateTemplateArguments(TemplateArgsPtr, Buffer);
1989
1990 TemplateName TName = Id.TemplateId->Template.get();
1991 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1992 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1993 TemplateArgs = &Buffer;
1994 } else {
1995 NameInfo = GetNameFromUnqualifiedId(Id);
1996 TemplateArgs = nullptr;
1997 }
1998 }
1999
2000 static void emitEmptyLookupTypoDiagnostic(
2001 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2002 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2003 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2004 DeclContext *Ctx =
2005 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2006 if (!TC) {
2007 // Emit a special diagnostic for failed member lookups.
2008 // FIXME: computing the declaration context might fail here (?)
2009 if (Ctx)
2010 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2011 << SS.getRange();
2012 else
2013 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2014 return;
2015 }
2016
2017 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2018 bool DroppedSpecifier =
2019 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2020 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2021 ? diag::note_implicit_param_decl
2022 : diag::note_previous_decl;
2023 if (!Ctx)
2024 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2025 SemaRef.PDiag(NoteID));
2026 else
2027 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2028 << Typo << Ctx << DroppedSpecifier
2029 << SS.getRange(),
2030 SemaRef.PDiag(NoteID));
2031 }
2032
2033 /// Diagnose an empty lookup.
2034 ///
2035 /// \return false if new lookup candidates were found
2036 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2037 CorrectionCandidateCallback &CCC,
2038 TemplateArgumentListInfo *ExplicitTemplateArgs,
2039 ArrayRef<Expr *> Args, TypoExpr **Out) {
2040 DeclarationName Name = R.getLookupName();
2041
2042 unsigned diagnostic = diag::err_undeclared_var_use;
2043 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2044 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2045 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2046 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2047 diagnostic = diag::err_undeclared_use;
2048 diagnostic_suggest = diag::err_undeclared_use_suggest;
2049 }
2050
2051 // If the original lookup was an unqualified lookup, fake an
2052 // unqualified lookup. This is useful when (for example) the
2053 // original lookup would not have found something because it was a
2054 // dependent name.
2055 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2056 while (DC) {
2057 if (isa<CXXRecordDecl>(DC)) {
2058 LookupQualifiedName(R, DC);
2059
2060 if (!R.empty()) {
2061 // Don't give errors about ambiguities in this lookup.
2062 R.suppressDiagnostics();
2063
2064 // During a default argument instantiation the CurContext points
2065 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2066 // function parameter list, hence add an explicit check.
2067 bool isDefaultArgument =
2068 !CodeSynthesisContexts.empty() &&
2069 CodeSynthesisContexts.back().Kind ==
2070 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2071 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2072 bool isInstance = CurMethod &&
2073 CurMethod->isInstance() &&
2074 DC == CurMethod->getParent() && !isDefaultArgument;
2075
2076 // Give a code modification hint to insert 'this->'.
2077 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2078 // Actually quite difficult!
2079 if (getLangOpts().MSVCCompat)
2080 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2081 if (isInstance) {
2082 Diag(R.getNameLoc(), diagnostic) << Name
2083 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2084 CheckCXXThisCapture(R.getNameLoc());
2085 } else {
2086 Diag(R.getNameLoc(), diagnostic) << Name;
2087 }
2088
2089 // Do we really want to note all of these?
2090 for (NamedDecl *D : R)
2091 Diag(D->getLocation(), diag::note_dependent_var_use);
2092
2093 // Return true if we are inside a default argument instantiation
2094 // and the found name refers to an instance member function, otherwise
2095 // the function calling DiagnoseEmptyLookup will try to create an
2096 // implicit member call and this is wrong for default argument.
2097 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2098 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2099 return true;
2100 }
2101
2102 // Tell the callee to try to recover.
2103 return false;
2104 }
2105
2106 R.clear();
2107 }
2108
2109 DC = DC->getLookupParent();
2110 }
2111
2112 // We didn't find anything, so try to correct for a typo.
2113 TypoCorrection Corrected;
2114 if (S && Out) {
2115 SourceLocation TypoLoc = R.getNameLoc();
2116 assert(!ExplicitTemplateArgs &&
2117 "Diagnosing an empty lookup with explicit template args!");
2118 *Out = CorrectTypoDelayed(
2119 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2120 [=](const TypoCorrection &TC) {
2121 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2122 diagnostic, diagnostic_suggest);
2123 },
2124 nullptr, CTK_ErrorRecovery);
2125 if (*Out)
2126 return true;
2127 } else if (S &&
2128 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2129 S, &SS, CCC, CTK_ErrorRecovery))) {
2130 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2131 bool DroppedSpecifier =
2132 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2133 R.setLookupName(Corrected.getCorrection());
2134
2135 bool AcceptableWithRecovery = false;
2136 bool AcceptableWithoutRecovery = false;
2137 NamedDecl *ND = Corrected.getFoundDecl();
2138 if (ND) {
2139 if (Corrected.isOverloaded()) {
2140 OverloadCandidateSet OCS(R.getNameLoc(),
2141 OverloadCandidateSet::CSK_Normal);
2142 OverloadCandidateSet::iterator Best;
2143 for (NamedDecl *CD : Corrected) {
2144 if (FunctionTemplateDecl *FTD =
2145 dyn_cast<FunctionTemplateDecl>(CD))
2146 AddTemplateOverloadCandidate(
2147 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2148 Args, OCS);
2149 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2150 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2151 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2152 Args, OCS);
2153 }
2154 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2155 case OR_Success:
2156 ND = Best->FoundDecl;
2157 Corrected.setCorrectionDecl(ND);
2158 break;
2159 default:
2160 // FIXME: Arbitrarily pick the first declaration for the note.
2161 Corrected.setCorrectionDecl(ND);
2162 break;
2163 }
2164 }
2165 R.addDecl(ND);
2166 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2167 CXXRecordDecl *Record = nullptr;
2168 if (Corrected.getCorrectionSpecifier()) {
2169 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2170 Record = Ty->getAsCXXRecordDecl();
2171 }
2172 if (!Record)
2173 Record = cast<CXXRecordDecl>(
2174 ND->getDeclContext()->getRedeclContext());
2175 R.setNamingClass(Record);
2176 }
2177
2178 auto *UnderlyingND = ND->getUnderlyingDecl();
2179 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2180 isa<FunctionTemplateDecl>(UnderlyingND);
2181 // FIXME: If we ended up with a typo for a type name or
2182 // Objective-C class name, we're in trouble because the parser
2183 // is in the wrong place to recover. Suggest the typo
2184 // correction, but don't make it a fix-it since we're not going
2185 // to recover well anyway.
2186 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2187 getAsTypeTemplateDecl(UnderlyingND) ||
2188 isa<ObjCInterfaceDecl>(UnderlyingND);
2189 } else {
2190 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2191 // because we aren't able to recover.
2192 AcceptableWithoutRecovery = true;
2193 }
2194
2195 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2196 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2197 ? diag::note_implicit_param_decl
2198 : diag::note_previous_decl;
2199 if (SS.isEmpty())
2200 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2201 PDiag(NoteID), AcceptableWithRecovery);
2202 else
2203 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2204 << Name << computeDeclContext(SS, false)
2205 << DroppedSpecifier << SS.getRange(),
2206 PDiag(NoteID), AcceptableWithRecovery);
2207
2208 // Tell the callee whether to try to recover.
2209 return !AcceptableWithRecovery;
2210 }
2211 }
2212 R.clear();
2213
2214 // Emit a special diagnostic for failed member lookups.
2215 // FIXME: computing the declaration context might fail here (?)
2216 if (!SS.isEmpty()) {
2217 Diag(R.getNameLoc(), diag::err_no_member)
2218 << Name << computeDeclContext(SS, false)
2219 << SS.getRange();
2220 return true;
2221 }
2222
2223 // Give up, we can't recover.
2224 Diag(R.getNameLoc(), diagnostic) << Name;
2225 return true;
2226 }
2227
2228 /// In Microsoft mode, if we are inside a template class whose parent class has
2229 /// dependent base classes, and we can't resolve an unqualified identifier, then
2230 /// assume the identifier is a member of a dependent base class. We can only
2231 /// recover successfully in static methods, instance methods, and other contexts
2232 /// where 'this' is available. This doesn't precisely match MSVC's
2233 /// instantiation model, but it's close enough.
2234 static Expr *
2235 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2236 DeclarationNameInfo &NameInfo,
2237 SourceLocation TemplateKWLoc,
2238 const TemplateArgumentListInfo *TemplateArgs) {
2239 // Only try to recover from lookup into dependent bases in static methods or
2240 // contexts where 'this' is available.
2241 QualType ThisType = S.getCurrentThisType();
2242 const CXXRecordDecl *RD = nullptr;
2243 if (!ThisType.isNull())
2244 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2245 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2246 RD = MD->getParent();
2247 if (!RD || !RD->hasAnyDependentBases())
2248 return nullptr;
2249
2250 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2251 // is available, suggest inserting 'this->' as a fixit.
2252 SourceLocation Loc = NameInfo.getLoc();
2253 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2254 DB << NameInfo.getName() << RD;
2255
2256 if (!ThisType.isNull()) {
2257 DB << FixItHint::CreateInsertion(Loc, "this->");
2258 return CXXDependentScopeMemberExpr::Create(
2259 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2260 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2261 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2262 }
2263
2264 // Synthesize a fake NNS that points to the derived class. This will
2265 // perform name lookup during template instantiation.
2266 CXXScopeSpec SS;
2267 auto *NNS =
2268 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2269 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2270 return DependentScopeDeclRefExpr::Create(
2271 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2272 TemplateArgs);
2273 }
2274
2275 ExprResult
2276 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2277 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2278 bool HasTrailingLParen, bool IsAddressOfOperand,
2279 CorrectionCandidateCallback *CCC,
2280 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2281 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2282 "cannot be direct & operand and have a trailing lparen");
2283 if (SS.isInvalid())
2284 return ExprError();
2285
2286 TemplateArgumentListInfo TemplateArgsBuffer;
2287
2288 // Decompose the UnqualifiedId into the following data.
2289 DeclarationNameInfo NameInfo;
2290 const TemplateArgumentListInfo *TemplateArgs;
2291 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2292
2293 DeclarationName Name = NameInfo.getName();
2294 IdentifierInfo *II = Name.getAsIdentifierInfo();
2295 SourceLocation NameLoc = NameInfo.getLoc();
2296
2297 if (II && II->isEditorPlaceholder()) {
2298 // FIXME: When typed placeholders are supported we can create a typed
2299 // placeholder expression node.
2300 return ExprError();
2301 }
2302
2303 // C++ [temp.dep.expr]p3:
2304 // An id-expression is type-dependent if it contains:
2305 // -- an identifier that was declared with a dependent type,
2306 // (note: handled after lookup)
2307 // -- a template-id that is dependent,
2308 // (note: handled in BuildTemplateIdExpr)
2309 // -- a conversion-function-id that specifies a dependent type,
2310 // -- a nested-name-specifier that contains a class-name that
2311 // names a dependent type.
2312 // Determine whether this is a member of an unknown specialization;
2313 // we need to handle these differently.
2314 bool DependentID = false;
2315 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2316 Name.getCXXNameType()->isDependentType()) {
2317 DependentID = true;
2318 } else if (SS.isSet()) {
2319 if (DeclContext *DC = computeDeclContext(SS, false)) {
2320 if (RequireCompleteDeclContext(SS, DC))
2321 return ExprError();
2322 } else {
2323 DependentID = true;
2324 }
2325 }
2326
2327 if (DependentID)
2328 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2329 IsAddressOfOperand, TemplateArgs);
2330
2331 // Perform the required lookup.
2332 LookupResult R(*this, NameInfo,
2333 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2334 ? LookupObjCImplicitSelfParam
2335 : LookupOrdinaryName);
2336 if (TemplateKWLoc.isValid() || TemplateArgs) {
2337 // Lookup the template name again to correctly establish the context in
2338 // which it was found. This is really unfortunate as we already did the
2339 // lookup to determine that it was a template name in the first place. If
2340 // this becomes a performance hit, we can work harder to preserve those
2341 // results until we get here but it's likely not worth it.
2342 bool MemberOfUnknownSpecialization;
2343 AssumedTemplateKind AssumedTemplate;
2344 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2345 MemberOfUnknownSpecialization, TemplateKWLoc,
2346 &AssumedTemplate))
2347 return ExprError();
2348
2349 if (MemberOfUnknownSpecialization ||
2350 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2351 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2352 IsAddressOfOperand, TemplateArgs);
2353 } else {
2354 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2355 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2356
2357 // If the result might be in a dependent base class, this is a dependent
2358 // id-expression.
2359 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2360 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2361 IsAddressOfOperand, TemplateArgs);
2362
2363 // If this reference is in an Objective-C method, then we need to do
2364 // some special Objective-C lookup, too.
2365 if (IvarLookupFollowUp) {
2366 ExprResult E(LookupInObjCMethod(R, S, II, true));
2367 if (E.isInvalid())
2368 return ExprError();
2369
2370 if (Expr *Ex = E.getAs<Expr>())
2371 return Ex;
2372 }
2373 }
2374
2375 if (R.isAmbiguous())
2376 return ExprError();
2377
2378 // This could be an implicitly declared function reference (legal in C90,
2379 // extension in C99, forbidden in C++).
2380 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2381 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2382 if (D) R.addDecl(D);
2383 }
2384
2385 // Determine whether this name might be a candidate for
2386 // argument-dependent lookup.
2387 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2388
2389 if (R.empty() && !ADL) {
2390 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2391 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2392 TemplateKWLoc, TemplateArgs))
2393 return E;
2394 }
2395
2396 // Don't diagnose an empty lookup for inline assembly.
2397 if (IsInlineAsmIdentifier)
2398 return ExprError();
2399
2400 // If this name wasn't predeclared and if this is not a function
2401 // call, diagnose the problem.
2402 TypoExpr *TE = nullptr;
2403 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2404 : nullptr);
2405 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2406 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2407 "Typo correction callback misconfigured");
2408 if (CCC) {
2409 // Make sure the callback knows what the typo being diagnosed is.
2410 CCC->setTypoName(II);
2411 if (SS.isValid())
2412 CCC->setTypoNNS(SS.getScopeRep());
2413 }
2414 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2415 // a template name, but we happen to have always already looked up the name
2416 // before we get here if it must be a template name.
2417 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2418 None, &TE)) {
2419 if (TE && KeywordReplacement) {
2420 auto &State = getTypoExprState(TE);
2421 auto BestTC = State.Consumer->getNextCorrection();
2422 if (BestTC.isKeyword()) {
2423 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2424 if (State.DiagHandler)
2425 State.DiagHandler(BestTC);
2426 KeywordReplacement->startToken();
2427 KeywordReplacement->setKind(II->getTokenID());
2428 KeywordReplacement->setIdentifierInfo(II);
2429 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2430 // Clean up the state associated with the TypoExpr, since it has
2431 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2432 clearDelayedTypo(TE);
2433 // Signal that a correction to a keyword was performed by returning a
2434 // valid-but-null ExprResult.
2435 return (Expr*)nullptr;
2436 }
2437 State.Consumer->resetCorrectionStream();
2438 }
2439 return TE ? TE : ExprError();
2440 }
2441
2442 assert(!R.empty() &&
2443 "DiagnoseEmptyLookup returned false but added no results");
2444
2445 // If we found an Objective-C instance variable, let
2446 // LookupInObjCMethod build the appropriate expression to
2447 // reference the ivar.
2448 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2449 R.clear();
2450 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2451 // In a hopelessly buggy code, Objective-C instance variable
2452 // lookup fails and no expression will be built to reference it.
2453 if (!E.isInvalid() && !E.get())
2454 return ExprError();
2455 return E;
2456 }
2457 }
2458
2459 // This is guaranteed from this point on.
2460 assert(!R.empty() || ADL);
2461
2462 // Check whether this might be a C++ implicit instance member access.
2463 // C++ [class.mfct.non-static]p3:
2464 // When an id-expression that is not part of a class member access
2465 // syntax and not used to form a pointer to member is used in the
2466 // body of a non-static member function of class X, if name lookup
2467 // resolves the name in the id-expression to a non-static non-type
2468 // member of some class C, the id-expression is transformed into a
2469 // class member access expression using (*this) as the
2470 // postfix-expression to the left of the . operator.
2471 //
2472 // But we don't actually need to do this for '&' operands if R
2473 // resolved to a function or overloaded function set, because the
2474 // expression is ill-formed if it actually works out to be a
2475 // non-static member function:
2476 //
2477 // C++ [expr.ref]p4:
2478 // Otherwise, if E1.E2 refers to a non-static member function. . .
2479 // [t]he expression can be used only as the left-hand operand of a
2480 // member function call.
2481 //
2482 // There are other safeguards against such uses, but it's important
2483 // to get this right here so that we don't end up making a
2484 // spuriously dependent expression if we're inside a dependent
2485 // instance method.
2486 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2487 bool MightBeImplicitMember;
2488 if (!IsAddressOfOperand)
2489 MightBeImplicitMember = true;
2490 else if (!SS.isEmpty())
2491 MightBeImplicitMember = false;
2492 else if (R.isOverloadedResult())
2493 MightBeImplicitMember = false;
2494 else if (R.isUnresolvableResult())
2495 MightBeImplicitMember = true;
2496 else
2497 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2498 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2499 isa<MSPropertyDecl>(R.getFoundDecl());
2500
2501 if (MightBeImplicitMember)
2502 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2503 R, TemplateArgs, S);
2504 }
2505
2506 if (TemplateArgs || TemplateKWLoc.isValid()) {
2507
2508 // In C++1y, if this is a variable template id, then check it
2509 // in BuildTemplateIdExpr().
2510 // The single lookup result must be a variable template declaration.
2511 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2512 Id.TemplateId->Kind == TNK_Var_template) {
2513 assert(R.getAsSingle<VarTemplateDecl>() &&
2514 "There should only be one declaration found.");
2515 }
2516
2517 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2518 }
2519
2520 return BuildDeclarationNameExpr(SS, R, ADL);
2521 }
2522
2523 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2524 /// declaration name, generally during template instantiation.
2525 /// There's a large number of things which don't need to be done along
2526 /// this path.
2527 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2528 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2529 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2530 DeclContext *DC = computeDeclContext(SS, false);
2531 if (!DC)
2532 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2533 NameInfo, /*TemplateArgs=*/nullptr);
2534
2535 if (RequireCompleteDeclContext(SS, DC))
2536 return ExprError();
2537
2538 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2539 LookupQualifiedName(R, DC);
2540
2541 if (R.isAmbiguous())
2542 return ExprError();
2543
2544 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2545 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2546 NameInfo, /*TemplateArgs=*/nullptr);
2547
2548 if (R.empty()) {
2549 Diag(NameInfo.getLoc(), diag::err_no_member)
2550 << NameInfo.getName() << DC << SS.getRange();
2551 return ExprError();
2552 }
2553
2554 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2555 // Diagnose a missing typename if this resolved unambiguously to a type in
2556 // a dependent context. If we can recover with a type, downgrade this to
2557 // a warning in Microsoft compatibility mode.
2558 unsigned DiagID = diag::err_typename_missing;
2559 if (RecoveryTSI && getLangOpts().MSVCCompat)
2560 DiagID = diag::ext_typename_missing;
2561 SourceLocation Loc = SS.getBeginLoc();
2562 auto D = Diag(Loc, DiagID);
2563 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2564 << SourceRange(Loc, NameInfo.getEndLoc());
2565
2566 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2567 // context.
2568 if (!RecoveryTSI)
2569 return ExprError();
2570
2571 // Only issue the fixit if we're prepared to recover.
2572 D << FixItHint::CreateInsertion(Loc, "typename ");
2573
2574 // Recover by pretending this was an elaborated type.
2575 QualType Ty = Context.getTypeDeclType(TD);
2576 TypeLocBuilder TLB;
2577 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2578
2579 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2580 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2581 QTL.setElaboratedKeywordLoc(SourceLocation());
2582 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2583
2584 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2585
2586 return ExprEmpty();
2587 }
2588
2589 // Defend against this resolving to an implicit member access. We usually
2590 // won't get here if this might be a legitimate a class member (we end up in
2591 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2592 // a pointer-to-member or in an unevaluated context in C++11.
2593 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2594 return BuildPossibleImplicitMemberExpr(SS,
2595 /*TemplateKWLoc=*/SourceLocation(),
2596 R, /*TemplateArgs=*/nullptr, S);
2597
2598 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2599 }
2600
2601 /// The parser has read a name in, and Sema has detected that we're currently
2602 /// inside an ObjC method. Perform some additional checks and determine if we
2603 /// should form a reference to an ivar.
2604 ///
2605 /// Ideally, most of this would be done by lookup, but there's
2606 /// actually quite a lot of extra work involved.
2607 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2608 IdentifierInfo *II) {
2609 SourceLocation Loc = Lookup.getNameLoc();
2610 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2611
2612 // Check for error condition which is already reported.
2613 if (!CurMethod)
2614 return DeclResult(true);
2615
2616 // There are two cases to handle here. 1) scoped lookup could have failed,
2617 // in which case we should look for an ivar. 2) scoped lookup could have
2618 // found a decl, but that decl is outside the current instance method (i.e.
2619 // a global variable). In these two cases, we do a lookup for an ivar with
2620 // this name, if the lookup sucedes, we replace it our current decl.
2621
2622 // If we're in a class method, we don't normally want to look for
2623 // ivars. But if we don't find anything else, and there's an
2624 // ivar, that's an error.
2625 bool IsClassMethod = CurMethod->isClassMethod();
2626
2627 bool LookForIvars;
2628 if (Lookup.empty())
2629 LookForIvars = true;
2630 else if (IsClassMethod)
2631 LookForIvars = false;
2632 else
2633 LookForIvars = (Lookup.isSingleResult() &&
2634 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2635 ObjCInterfaceDecl *IFace = nullptr;
2636 if (LookForIvars) {
2637 IFace = CurMethod->getClassInterface();
2638 ObjCInterfaceDecl *ClassDeclared;
2639 ObjCIvarDecl *IV = nullptr;
2640 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2641 // Diagnose using an ivar in a class method.
2642 if (IsClassMethod) {
2643 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2644 return DeclResult(true);
2645 }
2646
2647 // Diagnose the use of an ivar outside of the declaring class.
2648 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2649 !declaresSameEntity(ClassDeclared, IFace) &&
2650 !getLangOpts().DebuggerSupport)
2651 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2652
2653 // Success.
2654 return IV;
2655 }
2656 } else if (CurMethod->isInstanceMethod()) {
2657 // We should warn if a local variable hides an ivar.
2658 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2659 ObjCInterfaceDecl *ClassDeclared;
2660 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2661 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2662 declaresSameEntity(IFace, ClassDeclared))
2663 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2664 }
2665 }
2666 } else if (Lookup.isSingleResult() &&
2667 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2668 // If accessing a stand-alone ivar in a class method, this is an error.
2669 if (const ObjCIvarDecl *IV =
2670 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2671 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2672 return DeclResult(true);
2673 }
2674 }
2675
2676 // Didn't encounter an error, didn't find an ivar.
2677 return DeclResult(false);
2678 }
2679
2680 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2681 ObjCIvarDecl *IV) {
2682 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2683 assert(CurMethod && CurMethod->isInstanceMethod() &&
2684 "should not reference ivar from this context");
2685
2686 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2687 assert(IFace && "should not reference ivar from this context");
2688
2689 // If we're referencing an invalid decl, just return this as a silent
2690 // error node. The error diagnostic was already emitted on the decl.
2691 if (IV->isInvalidDecl())
2692 return ExprError();
2693
2694 // Check if referencing a field with __attribute__((deprecated)).
2695 if (DiagnoseUseOfDecl(IV, Loc))
2696 return ExprError();
2697
2698 // FIXME: This should use a new expr for a direct reference, don't
2699 // turn this into Self->ivar, just return a BareIVarExpr or something.
2700 IdentifierInfo &II = Context.Idents.get("self");
2701 UnqualifiedId SelfName;
2702 SelfName.setIdentifier(&II, SourceLocation());
2703 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2704 CXXScopeSpec SelfScopeSpec;
2705 SourceLocation TemplateKWLoc;
2706 ExprResult SelfExpr =
2707 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2708 /*HasTrailingLParen=*/false,
2709 /*IsAddressOfOperand=*/false);
2710 if (SelfExpr.isInvalid())
2711 return ExprError();
2712
2713 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2714 if (SelfExpr.isInvalid())
2715 return ExprError();
2716
2717 MarkAnyDeclReferenced(Loc, IV, true);
2718
2719 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2720 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2721 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2722 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2723
2724 ObjCIvarRefExpr *Result = new (Context)
2725 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2726 IV->getLocation(), SelfExpr.get(), true, true);
2727
2728 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2729 if (!isUnevaluatedContext() &&
2730 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2731 getCurFunction()->recordUseOfWeak(Result);
2732 }
2733 if (getLangOpts().ObjCAutoRefCount)
2734 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2735 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2736
2737 return Result;
2738 }
2739
2740 /// The parser has read a name in, and Sema has detected that we're currently
2741 /// inside an ObjC method. Perform some additional checks and determine if we
2742 /// should form a reference to an ivar. If so, build an expression referencing
2743 /// that ivar.
2744 ExprResult
2745 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2746 IdentifierInfo *II, bool AllowBuiltinCreation) {
2747 // FIXME: Integrate this lookup step into LookupParsedName.
2748 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2749 if (Ivar.isInvalid())
2750 return ExprError();
2751 if (Ivar.isUsable())
2752 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2753 cast<ObjCIvarDecl>(Ivar.get()));
2754
2755 if (Lookup.empty() && II && AllowBuiltinCreation)
2756 LookupBuiltin(Lookup);
2757
2758 // Sentinel value saying that we didn't do anything special.
2759 return ExprResult(false);
2760 }
2761
2762 /// Cast a base object to a member's actual type.
2763 ///
2764 /// Logically this happens in three phases:
2765 ///
2766 /// * First we cast from the base type to the naming class.
2767 /// The naming class is the class into which we were looking
2768 /// when we found the member; it's the qualifier type if a
2769 /// qualifier was provided, and otherwise it's the base type.
2770 ///
2771 /// * Next we cast from the naming class to the declaring class.
2772 /// If the member we found was brought into a class's scope by
2773 /// a using declaration, this is that class; otherwise it's
2774 /// the class declaring the member.
2775 ///
2776 /// * Finally we cast from the declaring class to the "true"
2777 /// declaring class of the member. This conversion does not
2778 /// obey access control.
2779 ExprResult
2780 Sema::PerformObjectMemberConversion(Expr *From,
2781 NestedNameSpecifier *Qualifier,
2782 NamedDecl *FoundDecl,
2783 NamedDecl *Member) {
2784 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2785 if (!RD)
2786 return From;
2787
2788 QualType DestRecordType;
2789 QualType DestType;
2790 QualType FromRecordType;
2791 QualType FromType = From->getType();
2792 bool PointerConversions = false;
2793 if (isa<FieldDecl>(Member)) {
2794 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2795 auto FromPtrType = FromType->getAs<PointerType>();
2796 DestRecordType = Context.getAddrSpaceQualType(
2797 DestRecordType, FromPtrType
2798 ? FromType->getPointeeType().getAddressSpace()
2799 : FromType.getAddressSpace());
2800
2801 if (FromPtrType) {
2802 DestType = Context.getPointerType(DestRecordType);
2803 FromRecordType = FromPtrType->getPointeeType();
2804 PointerConversions = true;
2805 } else {
2806 DestType = DestRecordType;
2807 FromRecordType = FromType;
2808 }
2809 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2810 if (Method->isStatic())
2811 return From;
2812
2813 DestType = Method->getThisType();
2814 DestRecordType = DestType->getPointeeType();
2815
2816 if (FromType->getAs<PointerType>()) {
2817 FromRecordType = FromType->getPointeeType();
2818 PointerConversions = true;
2819 } else {
2820 FromRecordType = FromType;
2821 DestType = DestRecordType;
2822 }
2823
2824 LangAS FromAS = FromRecordType.getAddressSpace();
2825 LangAS DestAS = DestRecordType.getAddressSpace();
2826 if (FromAS != DestAS) {
2827 QualType FromRecordTypeWithoutAS =
2828 Context.removeAddrSpaceQualType(FromRecordType);
2829 QualType FromTypeWithDestAS =
2830 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2831 if (PointerConversions)
2832 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2833 From = ImpCastExprToType(From, FromTypeWithDestAS,
2834 CK_AddressSpaceConversion, From->getValueKind())
2835 .get();
2836 }
2837 } else {
2838 // No conversion necessary.
2839 return From;
2840 }
2841
2842 if (DestType->isDependentType() || FromType->isDependentType())
2843 return From;
2844
2845 // If the unqualified types are the same, no conversion is necessary.
2846 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2847 return From;
2848
2849 SourceRange FromRange = From->getSourceRange();
2850 SourceLocation FromLoc = FromRange.getBegin();
2851
2852 ExprValueKind VK = From->getValueKind();
2853
2854 // C++ [class.member.lookup]p8:
2855 // [...] Ambiguities can often be resolved by qualifying a name with its
2856 // class name.
2857 //
2858 // If the member was a qualified name and the qualified referred to a
2859 // specific base subobject type, we'll cast to that intermediate type
2860 // first and then to the object in which the member is declared. That allows
2861 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2862 //
2863 // class Base { public: int x; };
2864 // class Derived1 : public Base { };
2865 // class Derived2 : public Base { };
2866 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2867 //
2868 // void VeryDerived::f() {
2869 // x = 17; // error: ambiguous base subobjects
2870 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2871 // }
2872 if (Qualifier && Qualifier->getAsType()) {
2873 QualType QType = QualType(Qualifier->getAsType(), 0);
2874 assert(QType->isRecordType() && "lookup done with non-record type");
2875
2876 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2877
2878 // In C++98, the qualifier type doesn't actually have to be a base
2879 // type of the object type, in which case we just ignore it.
2880 // Otherwise build the appropriate casts.
2881 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2882 CXXCastPath BasePath;
2883 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2884 FromLoc, FromRange, &BasePath))
2885 return ExprError();
2886
2887 if (PointerConversions)
2888 QType = Context.getPointerType(QType);
2889 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2890 VK, &BasePath).get();
2891
2892 FromType = QType;
2893 FromRecordType = QRecordType;
2894
2895 // If the qualifier type was the same as the destination type,
2896 // we're done.
2897 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2898 return From;
2899 }
2900 }
2901
2902 bool IgnoreAccess = false;
2903
2904 // If we actually found the member through a using declaration, cast
2905 // down to the using declaration's type.
2906 //
2907 // Pointer equality is fine here because only one declaration of a
2908 // class ever has member declarations.
2909 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2910 assert(isa<UsingShadowDecl>(FoundDecl));
2911 QualType URecordType = Context.getTypeDeclType(
2912 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2913
2914 // We only need to do this if the naming-class to declaring-class
2915 // conversion is non-trivial.
2916 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2917 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2918 CXXCastPath BasePath;
2919 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2920 FromLoc, FromRange, &BasePath))
2921 return ExprError();
2922
2923 QualType UType = URecordType;
2924 if (PointerConversions)
2925 UType = Context.getPointerType(UType);
2926 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2927 VK, &BasePath).get();
2928 FromType = UType;
2929 FromRecordType = URecordType;
2930 }
2931
2932 // We don't do access control for the conversion from the
2933 // declaring class to the true declaring class.
2934 IgnoreAccess = true;
2935 }
2936
2937 CXXCastPath BasePath;
2938 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2939 FromLoc, FromRange, &BasePath,
2940 IgnoreAccess))
2941 return ExprError();
2942
2943 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2944 VK, &BasePath);
2945 }
2946
2947 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2948 const LookupResult &R,
2949 bool HasTrailingLParen) {
2950 // Only when used directly as the postfix-expression of a call.
2951 if (!HasTrailingLParen)
2952 return false;
2953
2954 // Never if a scope specifier was provided.
2955 if (SS.isSet())
2956 return false;
2957
2958 // Only in C++ or ObjC++.
2959 if (!getLangOpts().CPlusPlus)
2960 return false;
2961
2962 // Turn off ADL when we find certain kinds of declarations during
2963 // normal lookup:
2964 for (NamedDecl *D : R) {
2965 // C++0x [basic.lookup.argdep]p3:
2966 // -- a declaration of a class member
2967 // Since using decls preserve this property, we check this on the
2968 // original decl.
2969 if (D->isCXXClassMember())
2970 return false;
2971
2972 // C++0x [basic.lookup.argdep]p3:
2973 // -- a block-scope function declaration that is not a
2974 // using-declaration
2975 // NOTE: we also trigger this for function templates (in fact, we
2976 // don't check the decl type at all, since all other decl types
2977 // turn off ADL anyway).
2978 if (isa<UsingShadowDecl>(D))
2979 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2980 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2981 return false;
2982
2983 // C++0x [basic.lookup.argdep]p3:
2984 // -- a declaration that is neither a function or a function
2985 // template
2986 // And also for builtin functions.
2987 if (isa<FunctionDecl>(D)) {
2988 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2989
2990 // But also builtin functions.
2991 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2992 return false;
2993 } else if (!isa<FunctionTemplateDecl>(D))
2994 return false;
2995 }
2996
2997 return true;
2998 }
2999
3000
3001 /// Diagnoses obvious problems with the use of the given declaration
3002 /// as an expression. This is only actually called for lookups that
3003 /// were not overloaded, and it doesn't promise that the declaration
3004 /// will in fact be used.
3005 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3006 if (D->isInvalidDecl())
3007 return true;
3008
3009 if (isa<TypedefNameDecl>(D)) {
3010 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3011 return true;
3012 }
3013
3014 if (isa<ObjCInterfaceDecl>(D)) {
3015 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3016 return true;
3017 }
3018
3019 if (isa<NamespaceDecl>(D)) {
3020 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3021 return true;
3022 }
3023
3024 return false;
3025 }
3026
3027 // Certain multiversion types should be treated as overloaded even when there is
3028 // only one result.
3029 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3030 assert(R.isSingleResult() && "Expected only a single result");
3031 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3032 return FD &&
3033 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3034 }
3035
3036 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3037 LookupResult &R, bool NeedsADL,
3038 bool AcceptInvalidDecl) {
3039 // If this is a single, fully-resolved result and we don't need ADL,
3040 // just build an ordinary singleton decl ref.
3041 if (!NeedsADL && R.isSingleResult() &&
3042 !R.getAsSingle<FunctionTemplateDecl>() &&
3043 !ShouldLookupResultBeMultiVersionOverload(R))
3044 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3045 R.getRepresentativeDecl(), nullptr,
3046 AcceptInvalidDecl);
3047
3048 // We only need to check the declaration if there's exactly one
3049 // result, because in the overloaded case the results can only be
3050 // functions and function templates.
3051 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3052 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3053 return ExprError();
3054
3055 // Otherwise, just build an unresolved lookup expression. Suppress
3056 // any lookup-related diagnostics; we'll hash these out later, when
3057 // we've picked a target.
3058 R.suppressDiagnostics();
3059
3060 UnresolvedLookupExpr *ULE
3061 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3062 SS.getWithLocInContext(Context),
3063 R.getLookupNameInfo(),
3064 NeedsADL, R.isOverloadedResult(),
3065 R.begin(), R.end());
3066
3067 return ULE;
3068 }
3069
3070 static void
3071 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3072 ValueDecl *var, DeclContext *DC);
3073
3074 /// Complete semantic analysis for a reference to the given declaration.
3075 ExprResult Sema::BuildDeclarationNameExpr(
3076 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3077 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3078 bool AcceptInvalidDecl) {
3079 assert(D && "Cannot refer to a NULL declaration");
3080 assert(!isa<FunctionTemplateDecl>(D) &&
3081 "Cannot refer unambiguously to a function template");
3082
3083 SourceLocation Loc = NameInfo.getLoc();
3084 if (CheckDeclInExpr(*this, Loc, D))
3085 return ExprError();
3086
3087 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3088 // Specifically diagnose references to class templates that are missing
3089 // a template argument list.
3090 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3091 return ExprError();
3092 }
3093
3094 // Make sure that we're referring to a value.
3095 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3096 if (!VD) {
3097 Diag(Loc, diag::err_ref_non_value)
3098 << D << SS.getRange();
3099 Diag(D->getLocation(), diag::note_declared_at);
3100 return ExprError();
3101 }
3102
3103 // Check whether this declaration can be used. Note that we suppress
3104 // this check when we're going to perform argument-dependent lookup
3105 // on this function name, because this might not be the function
3106 // that overload resolution actually selects.
3107 if (DiagnoseUseOfDecl(VD, Loc))
3108 return ExprError();
3109
3110 // Only create DeclRefExpr's for valid Decl's.
3111 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3112 return ExprError();
3113
3114 // Handle members of anonymous structs and unions. If we got here,
3115 // and the reference is to a class member indirect field, then this
3116 // must be the subject of a pointer-to-member expression.
3117 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3118 if (!indirectField->isCXXClassMember())
3119 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3120 indirectField);
3121
3122 {
3123 QualType type = VD->getType();
3124 if (type.isNull())
3125 return ExprError();
3126 ExprValueKind valueKind = VK_RValue;
3127
3128 switch (D->getKind()) {
3129 // Ignore all the non-ValueDecl kinds.
3130 #define ABSTRACT_DECL(kind)
3131 #define VALUE(type, base)
3132 #define DECL(type, base) \
3133 case Decl::type:
3134 #include "clang/AST/DeclNodes.inc"
3135 llvm_unreachable("invalid value decl kind");
3136
3137 // These shouldn't make it here.
3138 case Decl::ObjCAtDefsField:
3139 llvm_unreachable("forming non-member reference to ivar?");
3140
3141 // Enum constants are always r-values and never references.
3142 // Unresolved using declarations are dependent.
3143 case Decl::EnumConstant:
3144 case Decl::UnresolvedUsingValue:
3145 case Decl::OMPDeclareReduction:
3146 case Decl::OMPDeclareMapper:
3147 valueKind = VK_RValue;
3148 break;
3149
3150 // Fields and indirect fields that got here must be for
3151 // pointer-to-member expressions; we just call them l-values for
3152 // internal consistency, because this subexpression doesn't really
3153 // exist in the high-level semantics.
3154 case Decl::Field:
3155 case Decl::IndirectField:
3156 case Decl::ObjCIvar:
3157 assert(getLangOpts().CPlusPlus &&
3158 "building reference to field in C?");
3159
3160 // These can't have reference type in well-formed programs, but
3161 // for internal consistency we do this anyway.
3162 type = type.getNonReferenceType();
3163 valueKind = VK_LValue;
3164 break;
3165
3166 // Non-type template parameters are either l-values or r-values
3167 // depending on the type.
3168 case Decl::NonTypeTemplateParm: {
3169 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3170 type = reftype->getPointeeType();
3171 valueKind = VK_LValue; // even if the parameter is an r-value reference
3172 break;
3173 }
3174
3175 // For non-references, we need to strip qualifiers just in case
3176 // the template parameter was declared as 'const int' or whatever.
3177 valueKind = VK_RValue;
3178 type = type.getUnqualifiedType();
3179 break;
3180 }
3181
3182 case Decl::Var:
3183 case Decl::VarTemplateSpecialization:
3184 case Decl::VarTemplatePartialSpecialization:
3185 case Decl::Decomposition:
3186 case Decl::OMPCapturedExpr:
3187 // In C, "extern void blah;" is valid and is an r-value.
3188 if (!getLangOpts().CPlusPlus &&
3189 !type.hasQualifiers() &&
3190 type->isVoidType()) {
3191 valueKind = VK_RValue;
3192 break;
3193 }
3194 LLVM_FALLTHROUGH;
3195
3196 case Decl::ImplicitParam:
3197 case Decl::ParmVar: {
3198 // These are always l-values.
3199 valueKind = VK_LValue;
3200 type = type.getNonReferenceType();
3201
3202 // FIXME: Does the addition of const really only apply in
3203 // potentially-evaluated contexts? Since the variable isn't actually
3204 // captured in an unevaluated context, it seems that the answer is no.
3205 if (!isUnevaluatedContext()) {
3206 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3207 if (!CapturedType.isNull())
3208 type = CapturedType;
3209 }
3210
3211 break;
3212 }
3213
3214 case Decl::Binding: {
3215 // These are always lvalues.
3216 valueKind = VK_LValue;
3217 type = type.getNonReferenceType();
3218 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3219 // decides how that's supposed to work.
3220 auto *BD = cast<BindingDecl>(VD);
3221 if (BD->getDeclContext() != CurContext) {
3222 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3223 if (DD && DD->hasLocalStorage())
3224 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3225 }
3226 break;
3227 }
3228
3229 case Decl::Function: {
3230 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3231 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3232 type = Context.BuiltinFnTy;
3233 valueKind = VK_RValue;
3234 break;
3235 }
3236 }
3237
3238 const FunctionType *fty = type->castAs<FunctionType>();
3239
3240 // If we're referring to a function with an __unknown_anytype
3241 // result type, make the entire expression __unknown_anytype.
3242 if (fty->getReturnType() == Context.UnknownAnyTy) {
3243 type = Context.UnknownAnyTy;
3244 valueKind = VK_RValue;
3245 break;
3246 }
3247
3248 // Functions are l-values in C++.
3249 if (getLangOpts().CPlusPlus) {
3250 valueKind = VK_LValue;
3251 break;
3252 }
3253
3254 // C99 DR 316 says that, if a function type comes from a
3255 // function definition (without a prototype), that type is only
3256 // used for checking compatibility. Therefore, when referencing
3257 // the function, we pretend that we don't have the full function
3258 // type.
3259 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3260 isa<FunctionProtoType>(fty))
3261 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3262 fty->getExtInfo());
3263
3264 // Functions are r-values in C.
3265 valueKind = VK_RValue;
3266 break;
3267 }
3268
3269 case Decl::CXXDeductionGuide:
3270 llvm_unreachable("building reference to deduction guide");
3271
3272 case Decl::MSProperty:
3273 valueKind = VK_LValue;
3274 break;
3275
3276 case Decl::CXXMethod:
3277 // If we're referring to a method with an __unknown_anytype
3278 // result type, make the entire expression __unknown_anytype.
3279 // This should only be possible with a type written directly.
3280 if (const FunctionProtoType *proto
3281 = dyn_cast<FunctionProtoType>(VD->getType()))
3282 if (proto->getReturnType() == Context.UnknownAnyTy) {
3283 type = Context.UnknownAnyTy;
3284 valueKind = VK_RValue;
3285 break;
3286 }
3287
3288 // C++ methods are l-values if static, r-values if non-static.
3289 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3290 valueKind = VK_LValue;
3291 break;
3292 }
3293 LLVM_FALLTHROUGH;
3294
3295 case Decl::CXXConversion:
3296 case Decl::CXXDestructor:
3297 case Decl::CXXConstructor:
3298 valueKind = VK_RValue;
3299 break;
3300 }
3301
3302 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3303 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3304 TemplateArgs);
3305 }
3306 }
3307
3308 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3309 SmallString<32> &Target) {
3310 Target.resize(CharByteWidth * (Source.size() + 1));
3311 char *ResultPtr = &Target[0];
3312 const llvm::UTF8 *ErrorPtr;
3313 bool success =
3314 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3315 (void)success;
3316 assert(success);
3317 Target.resize(ResultPtr - &Target[0]);
3318 }
3319
3320 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3321 PredefinedExpr::IdentKind IK) {
3322 // Pick the current block, lambda, captured statement or function.
3323 Decl *currentDecl = nullptr;
3324 if (const BlockScopeInfo *BSI = getCurBlock())
3325 currentDecl = BSI->TheDecl;
3326 else if (const LambdaScopeInfo *LSI = getCurLambda())
3327 currentDecl = LSI->CallOperator;
3328 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3329 currentDecl = CSI->TheCapturedDecl;
3330 else
3331 currentDecl = getCurFunctionOrMethodDecl();
3332
3333 if (!currentDecl) {
3334 Diag(Loc, diag::ext_predef_outside_function);
3335 currentDecl = Context.getTranslationUnitDecl();
3336 }
3337
3338 QualType ResTy;
3339 StringLiteral *SL = nullptr;
3340 if (cast<DeclContext>(currentDecl)->isDependentContext())
3341 ResTy = Context.DependentTy;
3342 else {
3343 // Pre-defined identifiers are of type char[x], where x is the length of
3344 // the string.
3345 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3346 unsigned Length = Str.length();
3347
3348 llvm::APInt LengthI(32, Length + 1);
3349 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3350 ResTy =
3351 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3352 SmallString<32> RawChars;
3353 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3354 Str, RawChars);
3355 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3356 ArrayType::Normal,
3357 /*IndexTypeQuals*/ 0);
3358 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3359 /*Pascal*/ false, ResTy, Loc);
3360 } else {
3361 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3362 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3363 ArrayType::Normal,
3364 /*IndexTypeQuals*/ 0);
3365 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3366 /*Pascal*/ false, ResTy, Loc);
3367 }
3368 }
3369
3370 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3371 }
3372
3373 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3374 PredefinedExpr::IdentKind IK;
3375
3376 switch (Kind) {
3377 default: llvm_unreachable("Unknown simple primary expr!");
3378 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3379 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3380 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3381 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3382 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3383 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3384 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3385 }
3386
3387 return BuildPredefinedExpr(Loc, IK);
3388 }
3389
3390 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3391 SmallString<16> CharBuffer;
3392 bool Invalid = false;
3393 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3394 if (Invalid)
3395 return ExprError();
3396
3397 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3398 PP, Tok.getKind());
3399 if (Literal.hadError())
3400 return ExprError();
3401
3402 QualType Ty;
3403 if (Literal.isWide())
3404 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3405 else if (Literal.isUTF8() && getLangOpts().Char8)
3406 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3407 else if (Literal.isUTF16())
3408 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3409 else if (Literal.isUTF32())
3410 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3411 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3412 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3413 else
3414 Ty = Context.CharTy; // 'x' -> char in C++
3415
3416 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3417 if (Literal.isWide())
3418 Kind = CharacterLiteral::Wide;
3419 else if (Literal.isUTF16())
3420 Kind = CharacterLiteral::UTF16;
3421 else if (Literal.isUTF32())
3422 Kind = CharacterLiteral::UTF32;
3423 else if (Literal.isUTF8())
3424 Kind = CharacterLiteral::UTF8;
3425
3426 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3427 Tok.getLocation());
3428
3429 if (Literal.getUDSuffix().empty())
3430 return Lit;
3431
3432 // We're building a user-defined literal.
3433 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3434 SourceLocation UDSuffixLoc =
3435 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3436
3437 // Make sure we're allowed user-defined literals here.
3438 if (!UDLScope)
3439 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3440
3441 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3442 // operator "" X (ch)
3443 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3444 Lit, Tok.getLocation());
3445 }
3446
3447 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3448 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3449 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3450 Context.IntTy, Loc);
3451 }
3452
3453 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3454 QualType Ty, SourceLocation Loc) {
3455 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3456
3457 using llvm::APFloat;
3458 APFloat Val(Format);
3459
3460 APFloat::opStatus result = Literal.GetFloatValue(Val);
3461
3462 // Overflow is always an error, but underflow is only an error if
3463 // we underflowed to zero (APFloat reports denormals as underflow).
3464 if ((result & APFloat::opOverflow) ||
3465 ((result & APFloat::opUnderflow) && Val.isZero())) {
3466 unsigned diagnostic;
3467 SmallString<20> buffer;
3468 if (result & APFloat::opOverflow) {
3469 diagnostic = diag::warn_float_overflow;
3470 APFloat::getLargest(Format).toString(buffer);
3471 } else {
3472 diagnostic = diag::warn_float_underflow;
3473 APFloat::getSmallest(Format).toString(buffer);
3474 }
3475
3476 S.Diag(Loc, diagnostic)
3477 << Ty
3478 << StringRef(buffer.data(), buffer.size());
3479 }
3480
3481 bool isExact = (result == APFloat::opOK);
3482 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3483 }
3484
3485 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3486 assert(E && "Invalid expression");
3487
3488 if (E->isValueDependent())
3489 return false;
3490
3491 QualType QT = E->getType();
3492 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3493 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3494 return true;
3495 }
3496
3497 llvm::APSInt ValueAPS;
3498 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3499
3500 if (R.isInvalid())
3501 return true;
3502
3503 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3504 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3505 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3506 << ValueAPS.toString(10) << ValueIsPositive;
3507 return true;
3508 }
3509
3510 return false;
3511 }
3512
3513 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3514 // Fast path for a single digit (which is quite common). A single digit
3515 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3516 if (Tok.getLength() == 1) {
3517 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3518 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3519 }
3520
3521 SmallString<128> SpellingBuffer;
3522 // NumericLiteralParser wants to overread by one character. Add padding to
3523 // the buffer in case the token is copied to the buffer. If getSpelling()
3524 // returns a StringRef to the memory buffer, it should have a null char at
3525 // the EOF, so it is also safe.
3526 SpellingBuffer.resize(Tok.getLength() + 1);
3527
3528 // Get the spelling of the token, which eliminates trigraphs, etc.
3529 bool Invalid = false;
3530 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3531 if (Invalid)
3532 return ExprError();
3533
3534 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3535 if (Literal.hadError)
3536 return ExprError();
3537
3538 if (Literal.hasUDSuffix()) {
3539 // We're building a user-defined literal.
3540 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3541 SourceLocation UDSuffixLoc =
3542 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3543
3544 // Make sure we're allowed user-defined literals here.
3545 if (!UDLScope)
3546 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3547
3548 QualType CookedTy;
3549 if (Literal.isFloatingLiteral()) {
3550 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3551 // long double, the literal is treated as a call of the form
3552 // operator "" X (f L)
3553 CookedTy = Context.LongDoubleTy;
3554 } else {
3555 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3556 // unsigned long long, the literal is treated as a call of the form
3557 // operator "" X (n ULL)
3558 CookedTy = Context.UnsignedLongLongTy;
3559 }
3560
3561 DeclarationName OpName =
3562 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3563 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3564 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3565
3566 SourceLocation TokLoc = Tok.getLocation();
3567
3568 // Perform literal operator lookup to determine if we're building a raw
3569 // literal or a cooked one.
3570 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3571 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3572 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3573 /*AllowStringTemplate*/ false,
3574 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3575 case LOLR_ErrorNoDiagnostic:
3576 // Lookup failure for imaginary constants isn't fatal, there's still the
3577 // GNU extension producing _Complex types.
3578 break;
3579 case LOLR_Error:
3580 return ExprError();
3581 case LOLR_Cooked: {
3582 Expr *Lit;
3583 if (Literal.isFloatingLiteral()) {
3584 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3585 } else {
3586 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3587 if (Literal.GetIntegerValue(ResultVal))
3588 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3589 << /* Unsigned */ 1;
3590 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3591 Tok.getLocation());
3592 }
3593 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3594 }
3595
3596 case LOLR_Raw: {
3597 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3598 // literal is treated as a call of the form
3599 // operator "" X ("n")
3600 unsigned Length = Literal.getUDSuffixOffset();
3601 QualType StrTy = Context.getConstantArrayType(
3602 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3603 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3604 Expr *Lit = StringLiteral::Create(
3605 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3606 /*Pascal*/false, StrTy, &TokLoc, 1);
3607 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3608 }
3609
3610 case LOLR_Template: {
3611 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3612 // template), L is treated as a call fo the form
3613 // operator "" X <'c1', 'c2', ... 'ck'>()
3614 // where n is the source character sequence c1 c2 ... ck.
3615 TemplateArgumentListInfo ExplicitArgs;
3616 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3617 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3618 llvm::APSInt Value(CharBits, CharIsUnsigned);
3619 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3620 Value = TokSpelling[I];
3621 TemplateArgument Arg(Context, Value, Context.CharTy);
3622 TemplateArgumentLocInfo ArgInfo;
3623 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3624 }
3625 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3626 &ExplicitArgs);
3627 }
3628 case LOLR_StringTemplate:
3629 llvm_unreachable("unexpected literal operator lookup result");
3630 }
3631 }
3632
3633 Expr *Res;
3634
3635 if (Literal.isFixedPointLiteral()) {
3636 QualType Ty;
3637
3638 if (Literal.isAccum) {
3639 if (Literal.isHalf) {
3640 Ty = Context.ShortAccumTy;
3641 } else if (Literal.isLong) {
3642 Ty = Context.LongAccumTy;
3643 } else {
3644 Ty = Context.AccumTy;
3645 }
3646 } else if (Literal.isFract) {
3647 if (Literal.isHalf) {
3648 Ty = Context.ShortFractTy;
3649 } else if (Literal.isLong) {
3650 Ty = Context.LongFractTy;
3651 } else {
3652 Ty = Context.FractTy;
3653 }
3654 }
3655
3656 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3657
3658 bool isSigned = !Literal.isUnsigned;
3659 unsigned scale = Context.getFixedPointScale(Ty);
3660 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3661
3662 llvm::APInt Val(bit_width, 0, isSigned);
3663 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3664 bool ValIsZero = Val.isNullValue() && !Overflowed;
3665
3666 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3667 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3668 // Clause 6.4.4 - The value of a constant shall be in the range of
3669 // representable values for its type, with exception for constants of a
3670 // fract type with a value of exactly 1; such a constant shall denote
3671 // the maximal value for the type.
3672 --Val;
3673 else if (Val.ugt(MaxVal) || Overflowed)
3674 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3675
3676 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3677 Tok.getLocation(), scale);
3678 } else if (Literal.isFloatingLiteral()) {
3679 QualType Ty;
3680 if (Literal.isHalf){
3681 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3682 Ty = Context.HalfTy;
3683 else {
3684 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3685 return ExprError();
3686 }
3687 } else if (Literal.isFloat)
3688 Ty = Context.FloatTy;
3689 else if (Literal.isLong)
3690 Ty = Context.LongDoubleTy;
3691 else if (Literal.isFloat16)
3692 Ty = Context.Float16Ty;
3693 else if (Literal.isFloat128)
3694 Ty = Context.Float128Ty;
3695 else
3696 Ty = Context.DoubleTy;
3697
3698 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3699
3700 if (Ty == Context.DoubleTy) {
3701 if (getLangOpts().SinglePrecisionConstants) {
3702 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3703 if (BTy->getKind() != BuiltinType::Float) {
3704 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3705 }
3706 } else if (getLangOpts().OpenCL &&
3707 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3708 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3709 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3710 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3711 }
3712 }
3713 } else if (!Literal.isIntegerLiteral()) {
3714 return ExprError();
3715 } else {
3716 QualType Ty;
3717
3718 // 'long long' is a C99 or C++11 feature.
3719 if (!getLangOpts().C99 && Literal.isLongLong) {
3720 if (getLangOpts().CPlusPlus)
3721 Diag(Tok.getLocation(),
3722 getLangOpts().CPlusPlus11 ?
3723 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3724 else
3725 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3726 }
3727
3728 // Get the value in the widest-possible width.
3729 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3730 llvm::APInt ResultVal(MaxWidth, 0);
3731
3732 if (Literal.GetIntegerValue(ResultVal)) {
3733 // If this value didn't fit into uintmax_t, error and force to ull.
3734 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3735 << /* Unsigned */ 1;
3736 Ty = Context.UnsignedLongLongTy;
3737 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3738 "long long is not intmax_t?");
3739 } else {
3740 // If this value fits into a ULL, try to figure out what else it fits into
3741 // according to the rules of C99 6.4.4.1p5.
3742
3743 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3744 // be an unsigned int.
3745 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3746
3747 // Check from smallest to largest, picking the smallest type we can.
3748 unsigned Width = 0;
3749
3750 // Microsoft specific integer suffixes are explicitly sized.
3751 if (Literal.MicrosoftInteger) {
3752 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3753 Width = 8;
3754 Ty = Context.CharTy;
3755 } else {
3756 Width = Literal.MicrosoftInteger;
3757 Ty = Context.getIntTypeForBitwidth(Width,
3758 /*Signed=*/!Literal.isUnsigned);
3759 }
3760 }
3761
3762 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3763 // Are int/unsigned possibilities?
3764 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3765
3766 // Does it fit in a unsigned int?
3767 if (ResultVal.isIntN(IntSize)) {
3768 // Does it fit in a signed int?
3769 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3770 Ty = Context.IntTy;
3771 else if (AllowUnsigned)
3772 Ty = Context.UnsignedIntTy;
3773 Width = IntSize;
3774 }
3775 }
3776
3777 // Are long/unsigned long possibilities?
3778 if (Ty.isNull() && !Literal.isLongLong) {
3779 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3780
3781 // Does it fit in a unsigned long?
3782 if (ResultVal.isIntN(LongSize)) {
3783 // Does it fit in a signed long?
3784 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3785 Ty = Context.LongTy;
3786 else if (AllowUnsigned)
3787 Ty = Context.UnsignedLongTy;
3788 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3789 // is compatible.
3790 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3791 const unsigned LongLongSize =
3792 Context.getTargetInfo().getLongLongWidth();
3793 Diag(Tok.getLocation(),
3794 getLangOpts().CPlusPlus
3795 ? Literal.isLong
3796 ? diag::warn_old_implicitly_unsigned_long_cxx
3797 : /*C++98 UB*/ diag::
3798 ext_old_implicitly_unsigned_long_cxx
3799 : diag::warn_old_implicitly_unsigned_long)
3800 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3801 : /*will be ill-formed*/ 1);
3802 Ty = Context.UnsignedLongTy;
3803 }
3804 Width = LongSize;
3805 }
3806 }
3807
3808 // Check long long if needed.
3809 if (Ty.isNull()) {
3810 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3811
3812 // Does it fit in a unsigned long long?
3813 if (ResultVal.isIntN(LongLongSize)) {
3814 // Does it fit in a signed long long?
3815 // To be compatible with MSVC, hex integer literals ending with the
3816 // LL or i64 suffix are always signed in Microsoft mode.
3817 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3818 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3819 Ty = Context.LongLongTy;
3820 else if (AllowUnsigned)
3821 Ty = Context.UnsignedLongLongTy;
3822 Width = LongLongSize;
3823 }
3824 }
3825
3826 // If we still couldn't decide a type, we probably have something that
3827 // does not fit in a signed long long, but has no U suffix.
3828 if (Ty.isNull()) {
3829 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3830 Ty = Context.UnsignedLongLongTy;
3831 Width = Context.getTargetInfo().getLongLongWidth();
3832 }
3833
3834 if (ResultVal.getBitWidth() != Width)
3835 ResultVal = ResultVal.trunc(Width);
3836 }
3837 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3838 }
3839
3840 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3841 if (Literal.isImaginary) {
3842 Res = new (Context) ImaginaryLiteral(Res,
3843 Context.getComplexType(Res->getType()));
3844
3845 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3846 }
3847 return Res;
3848 }
3849
3850 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3851 assert(E && "ActOnParenExpr() missing expr");
3852 return new (Context) ParenExpr(L, R, E);
3853 }
3854
3855 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3856 SourceLocation Loc,
3857 SourceRange ArgRange) {
3858 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3859 // scalar or vector data type argument..."
3860 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3861 // type (C99 6.2.5p18) or void.
3862 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3863 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3864 << T << ArgRange;
3865 return true;
3866 }
3867
3868 assert((T->isVoidType() || !T->isIncompleteType()) &&
3869 "Scalar types should always be complete");
3870 return false;
3871 }
3872
3873 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3874 SourceLocation Loc,
3875 SourceRange ArgRange,
3876 UnaryExprOrTypeTrait TraitKind) {
3877 // Invalid types must be hard errors for SFINAE in C++.
3878 if (S.LangOpts.CPlusPlus)
3879 return true;
3880
3881 // C99 6.5.3.4p1:
3882 if (T->isFunctionType() &&
3883 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3884 TraitKind == UETT_PreferredAlignOf)) {
3885 // sizeof(function)/alignof(function) is allowed as an extension.
3886 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3887 << TraitKind << ArgRange;
3888 return false;
3889 }
3890
3891 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3892 // this is an error (OpenCL v1.1 s6.3.k)
3893 if (T->isVoidType()) {
3894 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3895 : diag::ext_sizeof_alignof_void_type;
3896 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3897 return false;
3898 }
3899
3900 return true;
3901 }
3902
3903 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3904 SourceLocation Loc,
3905 SourceRange ArgRange,
3906 UnaryExprOrTypeTrait TraitKind) {
3907 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3908 // runtime doesn't allow it.
3909 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3910 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3911 << T << (TraitKind == UETT_SizeOf)
3912 << ArgRange;
3913 return true;
3914 }
3915
3916 return false;
3917 }
3918
3919 /// Check whether E is a pointer from a decayed array type (the decayed
3920 /// pointer type is equal to T) and emit a warning if it is.
3921 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3922 Expr *E) {
3923 // Don't warn if the operation changed the type.
3924 if (T != E->getType())
3925 return;
3926
3927 // Now look for array decays.
3928 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3929 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3930 return;
3931
3932 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3933 << ICE->getType()
3934 << ICE->getSubExpr()->getType();
3935 }
3936
3937 /// Check the constraints on expression operands to unary type expression
3938 /// and type traits.
3939 ///
3940 /// Completes any types necessary and validates the constraints on the operand
3941 /// expression. The logic mostly mirrors the type-based overload, but may modify
3942 /// the expression as it completes the type for that expression through template
3943 /// instantiation, etc.
3944 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3945 UnaryExprOrTypeTrait ExprKind) {
3946 QualType ExprTy = E->getType();
3947 assert(!ExprTy->isReferenceType());
3948
3949 bool IsUnevaluatedOperand =
3950 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3951 ExprKind == UETT_PreferredAlignOf);
3952 if (IsUnevaluatedOperand) {
3953 ExprResult Result = CheckUnevaluatedOperand(E);
3954 if (Result.isInvalid())
3955 return true;
3956 E = Result.get();
3957 }
3958
3959 if (ExprKind == UETT_VecStep)
3960 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3961 E->getSourceRange());
3962
3963 // Whitelist some types as extensions
3964 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3965 E->getSourceRange(), ExprKind))
3966 return false;
3967
3968 // 'alignof' applied to an expression only requires the base element type of
3969 // the expression to be complete. 'sizeof' requires the expression's type to
3970 // be complete (and will attempt to complete it if it's an array of unknown
3971 // bound).
3972 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3973 if (RequireCompleteType(E->getExprLoc(),
3974 Context.getBaseElementType(E->getType()),
3975 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3976 E->getSourceRange()))
3977 return true;
3978 } else {
3979 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3980 ExprKind, E->getSourceRange()))
3981 return true;
3982 }
3983
3984 // Completing the expression's type may have changed it.
3985 ExprTy = E->getType();
3986 assert(!ExprTy->isReferenceType());
3987
3988 if (ExprTy->isFunctionType()) {
3989 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3990 << ExprKind << E->getSourceRange();
3991 return true;
3992 }
3993
3994 // The operand for sizeof and alignof is in an unevaluated expression context,
3995 // so side effects could result in unintended consequences.
3996 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3997 E->HasSideEffects(Context, false))
3998 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3999
4000 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4001 E->getSourceRange(), ExprKind))
4002 return true;
4003
4004 if (ExprKind == UETT_SizeOf) {
4005 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4006 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4007 QualType OType = PVD->getOriginalType();
4008 QualType Type = PVD->getType();
4009 if (Type->isPointerType() && OType->isArrayType()) {
4010 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4011 << Type << OType;
4012 Diag(PVD->getLocation(), diag::note_declared_at);
4013 }
4014 }
4015 }
4016
4017 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4018 // decays into a pointer and returns an unintended result. This is most
4019 // likely a typo for "sizeof(array) op x".
4020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4021 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4022 BO->getLHS());
4023 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4024 BO->getRHS());
4025 }
4026 }
4027
4028 return false;
4029 }
4030
4031 /// Check the constraints on operands to unary expression and type
4032 /// traits.
4033 ///
4034 /// This will complete any types necessary, and validate the various constraints
4035 /// on those operands.
4036 ///
4037 /// The UsualUnaryConversions() function is *not* called by this routine.
4038 /// C99 6.3.2.1p[2-4] all state:
4039 /// Except when it is the operand of the sizeof operator ...
4040 ///
4041 /// C++ [expr.sizeof]p4
4042 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4043 /// standard conversions are not applied to the operand of sizeof.
4044 ///
4045 /// This policy is followed for all of the unary trait expressions.
4046 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4047 SourceLocation OpLoc,
4048 SourceRange ExprRange,
4049 UnaryExprOrTypeTrait ExprKind) {
4050 if (ExprType->isDependentType())
4051 return false;
4052
4053 // C++ [expr.sizeof]p2:
4054 // When applied to a reference or a reference type, the result
4055 // is the size of the referenced type.
4056 // C++11 [expr.alignof]p3:
4057 // When alignof is applied to a reference type, the result
4058 // shall be the alignment of the referenced type.
4059 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4060 ExprType = Ref->getPointeeType();
4061
4062 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4063 // When alignof or _Alignof is applied to an array type, the result
4064 // is the alignment of the element type.
4065 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4066 ExprKind == UETT_OpenMPRequiredSimdAlign)
4067 ExprType = Context.getBaseElementType(ExprType);
4068
4069 if (ExprKind == UETT_VecStep)
4070 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4071
4072 // Whitelist some types as extensions
4073 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4074 ExprKind))
4075 return false;
4076
4077 if (RequireCompleteType(OpLoc, ExprType,
4078 diag::err_sizeof_alignof_incomplete_type,
4079 ExprKind, ExprRange))
4080 return true;
4081
4082 if (ExprType->isFunctionType()) {
4083 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4084 << ExprKind << ExprRange;
4085 return true;
4086 }
4087
4088 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4089 ExprKind))
4090 return true;
4091
4092 return false;
4093 }
4094
4095 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4096 // Cannot know anything else if the expression is dependent.
4097 if (E->isTypeDependent())
4098 return false;
4099
4100 if (E->getObjectKind() == OK_BitField) {
4101 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4102 << 1 << E->getSourceRange();
4103 return true;
4104 }
4105
4106 ValueDecl *D = nullptr;
4107 Expr *Inner = E->IgnoreParens();
4108 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4109 D = DRE->getDecl();
4110 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4111 D = ME->getMemberDecl();
4112 }
4113
4114 // If it's a field, require the containing struct to have a
4115 // complete definition so that we can compute the layout.
4116 //
4117 // This can happen in C++11 onwards, either by naming the member
4118 // in a way that is not transformed into a member access expression
4119 // (in an unevaluated operand, for instance), or by naming the member
4120 // in a trailing-return-type.
4121 //
4122 // For the record, since __alignof__ on expressions is a GCC
4123 // extension, GCC seems to permit this but always gives the
4124 // nonsensical answer 0.
4125 //
4126 // We don't really need the layout here --- we could instead just
4127 // directly check for all the appropriate alignment-lowing
4128 // attributes --- but that would require duplicating a lot of
4129 // logic that just isn't worth duplicating for such a marginal
4130 // use-case.
4131 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4132 // Fast path this check, since we at least know the record has a
4133 // definition if we can find a member of it.
4134 if (!FD->getParent()->isCompleteDefinition()) {
4135 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4136 << E->getSourceRange();
4137 return true;
4138 }
4139
4140 // Otherwise, if it's a field, and the field doesn't have
4141 // reference type, then it must have a complete type (or be a
4142 // flexible array member, which we explicitly want to
4143 // white-list anyway), which makes the following checks trivial.
4144 if (!FD->getType()->isReferenceType())
4145 return false;
4146 }
4147
4148 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4149 }
4150
4151 bool Sema::CheckVecStepExpr(Expr *E) {
4152 E = E->IgnoreParens();
4153
4154 // Cannot know anything else if the expression is dependent.
4155 if (E->isTypeDependent())
4156 return false;
4157
4158 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4159 }
4160
4161 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4162 CapturingScopeInfo *CSI) {
4163 assert(T->isVariablyModifiedType());
4164 assert(CSI != nullptr);
4165
4166 // We're going to walk down into the type and look for VLA expressions.
4167 do {
4168 const Type *Ty = T.getTypePtr();
4169 switch (Ty->getTypeClass()) {
4170 #define TYPE(Class, Base)
4171 #define ABSTRACT_TYPE(Class, Base)
4172 #define NON_CANONICAL_TYPE(Class, Base)
4173 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4175 #include "clang/AST/TypeNodes.inc"
4176 T = QualType();
4177 break;
4178 // These types are never variably-modified.
4179 case Type::Builtin:
4180 case Type::Complex:
4181 case Type::Vector:
4182 case Type::ExtVector:
4183 case Type::Record:
4184 case Type::Enum:
4185 case Type::Elaborated:
4186 case Type::TemplateSpecialization:
4187 case Type::ObjCObject:
4188 case Type::ObjCInterface:
4189 case Type::ObjCObjectPointer:
4190 case Type::ObjCTypeParam:
4191 case Type::Pipe:
4192 llvm_unreachable("type class is never variably-modified!");
4193 case Type::Adjusted:
4194 T = cast<AdjustedType>(Ty)->getOriginalType();
4195 break;
4196 case Type::Decayed:
4197 T = cast<DecayedType>(Ty)->getPointeeType();
4198 break;
4199 case Type::Pointer:
4200 T = cast<PointerType>(Ty)->getPointeeType();
4201 break;
4202 case Type::BlockPointer:
4203 T = cast<BlockPointerType>(Ty)->getPointeeType();
4204 break;
4205 case Type::LValueReference:
4206 case Type::RValueReference:
4207 T = cast<ReferenceType>(Ty)->getPointeeType();
4208 break;
4209 case Type::MemberPointer:
4210 T = cast<MemberPointerType>(Ty)->getPointeeType();
4211 break;
4212 case Type::ConstantArray:
4213 case Type::IncompleteArray:
4214 // Losing element qualification here is fine.
4215 T = cast<ArrayType>(Ty)->getElementType();
4216 break;
4217 case Type::VariableArray: {
4218 // Losing element qualification here is fine.
4219 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4220
4221 // Unknown size indication requires no size computation.
4222 // Otherwise, evaluate and record it.
4223 auto Size = VAT->getSizeExpr();
4224 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4225 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4226 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4227
4228 T = VAT->getElementType();
4229 break;
4230 }
4231 case Type::FunctionProto:
4232 case Type::FunctionNoProto:
4233 T = cast<FunctionType>(Ty)->getReturnType();
4234 break;
4235 case Type::Paren:
4236 case Type::TypeOf:
4237 case Type::UnaryTransform:
4238 case Type::Attributed:
4239 case Type::SubstTemplateTypeParm:
4240 case Type::PackExpansion:
4241 case Type::MacroQualified:
4242 // Keep walking after single level desugaring.
4243 T = T.getSingleStepDesugaredType(Context);
4244 break;
4245 case Type::Typedef:
4246 T = cast<TypedefType>(Ty)->desugar();
4247 break;
4248 case Type::Decltype:
4249 T = cast<DecltypeType>(Ty)->desugar();
4250 break;
4251 case Type::Auto:
4252 case Type::DeducedTemplateSpecialization:
4253 T = cast<DeducedType>(Ty)->getDeducedType();
4254 break;
4255 case Type::TypeOfExpr:
4256 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4257 break;
4258 case Type::Atomic:
4259 T = cast<AtomicType>(Ty)->getValueType();
4260 break;
4261 }
4262 } while (!T.isNull() && T->isVariablyModifiedType());
4263 }
4264
4265 /// Build a sizeof or alignof expression given a type operand.
4266 ExprResult
4267 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4268 SourceLocation OpLoc,
4269 UnaryExprOrTypeTrait ExprKind,
4270 SourceRange R) {
4271 if (!TInfo)
4272 return ExprError();
4273
4274 QualType T = TInfo->getType();
4275
4276 if (!T->isDependentType() &&
4277 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4278 return ExprError();
4279
4280 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4281 if (auto *TT = T->getAs<TypedefType>()) {
4282 for (auto I = FunctionScopes.rbegin(),
4283 E = std::prev(FunctionScopes.rend());
4284 I != E; ++I) {
4285 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4286 if (CSI == nullptr)
4287 break;
4288 DeclContext *DC = nullptr;
4289 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4290 DC = LSI->CallOperator;
4291 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4292 DC = CRSI->TheCapturedDecl;
4293 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4294 DC = BSI->TheDecl;
4295 if (DC) {
4296 if (DC->containsDecl(TT->getDecl()))
4297 break;
4298 captureVariablyModifiedType(Context, T, CSI);
4299 }
4300 }
4301 }
4302 }
4303
4304 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4305 return new (Context) UnaryExprOrTypeTraitExpr(
4306 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4307 }
4308
4309 /// Build a sizeof or alignof expression given an expression
4310 /// operand.
4311 ExprResult
4312 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4313 UnaryExprOrTypeTrait ExprKind) {
4314 ExprResult PE = CheckPlaceholderExpr(E);
4315 if (PE.isInvalid())
4316 return ExprError();
4317
4318 E = PE.get();
4319
4320 // Verify that the operand is valid.
4321 bool isInvalid = false;
4322 if (E->isTypeDependent()) {
4323 // Delay type-checking for type-dependent expressions.
4324 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4325 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4326 } else if (ExprKind == UETT_VecStep) {
4327 isInvalid = CheckVecStepExpr(E);
4328 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4329 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4330 isInvalid = true;
4331 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4332 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4333 isInvalid = true;
4334 } else {
4335 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4336 }
4337
4338 if (isInvalid)
4339 return ExprError();
4340
4341 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4342 PE = TransformToPotentiallyEvaluated(E);
4343 if (PE.isInvalid()) return ExprError();
4344 E = PE.get();
4345 }
4346
4347 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4348 return new (Context) UnaryExprOrTypeTraitExpr(
4349 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4350 }
4351
4352 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4353 /// expr and the same for @c alignof and @c __alignof
4354 /// Note that the ArgRange is invalid if isType is false.
4355 ExprResult
4356 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4357 UnaryExprOrTypeTrait ExprKind, bool IsType,
4358 void *TyOrEx, SourceRange ArgRange) {
4359 // If error parsing type, ignore.
4360 if (!TyOrEx) return ExprError();
4361
4362 if (IsType) {
4363 TypeSourceInfo *TInfo;
4364 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4365 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4366 }
4367
4368 Expr *ArgEx = (Expr *)TyOrEx;
4369 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4370 return Result;
4371 }
4372
4373 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4374 bool IsReal) {
4375 if (V.get()->isTypeDependent())
4376 return S.Context.DependentTy;
4377
4378 // _Real and _Imag are only l-values for normal l-values.
4379 if (V.get()->getObjectKind() != OK_Ordinary) {
4380 V = S.DefaultLvalueConversion(V.get());
4381 if (V.isInvalid())
4382 return QualType();
4383 }
4384
4385 // These operators return the element type of a complex type.
4386 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4387 return CT->getElementType();
4388
4389 // Otherwise they pass through real integer and floating point types here.
4390 if (V.get()->getType()->isArithmeticType())
4391 return V.get()->getType();
4392
4393 // Test for placeholders.
4394 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4395 if (PR.isInvalid()) return QualType();
4396 if (PR.get() != V.get()) {
4397 V = PR;
4398 return CheckRealImagOperand(S, V, Loc, IsReal);
4399 }
4400
4401 // Reject anything else.
4402 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4403 << (IsReal ? "__real" : "__imag");
4404 return QualType();
4405 }
4406
4407
4408
4409 ExprResult
4410 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4411 tok::TokenKind Kind, Expr *Input) {
4412 UnaryOperatorKind Opc;
4413 switch (Kind) {
4414 default: llvm_unreachable("Unknown unary op!");
4415 case tok::plusplus: Opc = UO_PostInc; break;
4416 case tok::minusminus: Opc = UO_PostDec; break;
4417 }
4418
4419 // Since this might is a postfix expression, get rid of ParenListExprs.
4420 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4421 if (Result.isInvalid()) return ExprError();
4422 Input = Result.get();
4423
4424 return BuildUnaryOp(S, OpLoc, Opc, Input);
4425 }
4426
4427 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4428 ///
4429 /// \return true on error
4430 static bool checkArithmeticOnObjCPointer(Sema &S,
4431 SourceLocation opLoc,
4432 Expr *op) {
4433 assert(op->getType()->isObjCObjectPointerType());
4434 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4435 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4436 return false;
4437
4438 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4439 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4440 << op->getSourceRange();
4441 return true;
4442 }
4443
4444 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4445 auto *BaseNoParens = Base->IgnoreParens();
4446 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4447 return MSProp->getPropertyDecl()->getType()->isArrayType();
4448 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4449 }
4450
4451 ExprResult
4452 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4453 Expr *idx, SourceLocation rbLoc) {
4454 if (base && !base->getType().isNull() &&
4455 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4456 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4457 /*Length=*/nullptr, rbLoc);
4458
4459 // Since this might be a postfix expression, get rid of ParenListExprs.
4460 if (isa<ParenListExpr>(base)) {
4461 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4462 if (result.isInvalid()) return ExprError();
4463 base = result.get();
4464 }
4465
4466 // A comma-expression as the index is deprecated in C++2a onwards.
4467 if (getLangOpts().CPlusPlus2a &&
4468 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4469 (isa<CXXOperatorCallExpr>(idx) &&
4470 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4471 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4472 << SourceRange(base->getBeginLoc(), rbLoc);
4473 }
4474
4475 // Handle any non-overload placeholder types in the base and index
4476 // expressions. We can't handle overloads here because the other
4477 // operand might be an overloadable type, in which case the overload
4478 // resolution for the operator overload should get the first crack
4479 // at the overload.
4480 bool IsMSPropertySubscript = false;
4481 if (base->getType()->isNonOverloadPlaceholderType()) {
4482 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4483 if (!IsMSPropertySubscript) {
4484 ExprResult result = CheckPlaceholderExpr(base);
4485 if (result.isInvalid())
4486 return ExprError();
4487 base = result.get();
4488 }
4489 }
4490 if (idx->getType()->isNonOverloadPlaceholderType()) {
4491 ExprResult result = CheckPlaceholderExpr(idx);
4492 if (result.isInvalid()) return ExprError();
4493 idx = result.get();
4494 }
4495
4496 // Build an unanalyzed expression if either operand is type-dependent.
4497 if (getLangOpts().CPlusPlus &&
4498 (base->isTypeDependent() || idx->isTypeDependent())) {
4499 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4500 VK_LValue, OK_Ordinary, rbLoc);
4501 }
4502
4503 // MSDN, property (C++)
4504 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4505 // This attribute can also be used in the declaration of an empty array in a
4506 // class or structure definition. For example:
4507 // __declspec(property(get=GetX, put=PutX)) int x[];
4508 // The above statement indicates that x[] can be used with one or more array
4509 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4510 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4511 if (IsMSPropertySubscript) {
4512 // Build MS property subscript expression if base is MS property reference
4513 // or MS property subscript.
4514 return new (Context) MSPropertySubscriptExpr(
4515 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4516 }
4517
4518 // Use C++ overloaded-operator rules if either operand has record
4519 // type. The spec says to do this if either type is *overloadable*,
4520 // but enum types can't declare subscript operators or conversion
4521 // operators, so there's nothing interesting for overload resolution
4522 // to do if there aren't any record types involved.
4523 //
4524 // ObjC pointers have their own subscripting logic that is not tied
4525 // to overload resolution and so should not take this path.
4526 if (getLangOpts().CPlusPlus &&
4527 (base->getType()->isRecordType() ||
4528 (!base->getType()->isObjCObjectPointerType() &&
4529 idx->getType()->isRecordType()))) {
4530 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4531 }
4532
4533 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4534
4535 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4536 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4537
4538 return Res;
4539 }
4540
4541 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4542 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4543 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4544
4545 // For expressions like `&(*s).b`, the base is recorded and what should be
4546 // checked.
4547 const MemberExpr *Member = nullptr;
4548 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4549 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4550
4551 LastRecord.PossibleDerefs.erase(StrippedExpr);
4552 }
4553
4554 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4555 QualType ResultTy = E->getType();
4556 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4557
4558 // Bail if the element is an array since it is not memory access.
4559 if (isa<ArrayType>(ResultTy))
4560 return;
4561
4562 if (ResultTy->hasAttr(attr::NoDeref)) {
4563 LastRecord.PossibleDerefs.insert(E);
4564 return;
4565 }
4566
4567 // Check if the base type is a pointer to a member access of a struct
4568 // marked with noderef.
4569 const Expr *Base = E->getBase();
4570 QualType BaseTy = Base->getType();
4571 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4572 // Not a pointer access
4573 return;
4574
4575 const MemberExpr *Member = nullptr;
4576 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4577 Member->isArrow())
4578 Base = Member->getBase();
4579
4580 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4581 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4582 LastRecord.PossibleDerefs.insert(E);
4583 }
4584 }
4585
4586 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4587 Expr *LowerBound,
4588 SourceLocation ColonLoc, Expr *Length,
4589 SourceLocation RBLoc) {
4590 if (Base->getType()->isPlaceholderType() &&
4591 !Base->getType()->isSpecificPlaceholderType(
4592 BuiltinType::OMPArraySection)) {
4593 ExprResult Result = CheckPlaceholderExpr(Base);
4594 if (Result.isInvalid())
4595 return ExprError();
4596 Base = Result.get();
4597 }
4598 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4599 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4600 if (Result.isInvalid())
4601 return ExprError();
4602 Result = DefaultLvalueConversion(Result.get());
4603 if (Result.isInvalid())
4604 return ExprError();
4605 LowerBound = Result.get();
4606 }
4607 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4608 ExprResult Result = CheckPlaceholderExpr(Length);
4609 if (Result.isInvalid())
4610 return ExprError();
4611 Result = DefaultLvalueConversion(Result.get());
4612 if (Result.isInvalid())
4613 return ExprError();
4614 Length = Result.get();
4615 }
4616
4617 // Build an unanalyzed expression if either operand is type-dependent.
4618 if (Base->isTypeDependent() ||
4619 (LowerBound &&
4620 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4621 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4622 return new (Context)
4623 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4624 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4625 }
4626
4627 // Perform default conversions.
4628 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4629 QualType ResultTy;
4630 if (OriginalTy->isAnyPointerType()) {
4631 ResultTy = OriginalTy->getPointeeType();
4632 } else if (OriginalTy->isArrayType()) {
4633 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4634 } else {
4635 return ExprError(
4636 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4637 << Base->getSourceRange());
4638 }
4639 // C99 6.5.2.1p1
4640 if (LowerBound) {
4641 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4642 LowerBound);
4643 if (Res.isInvalid())
4644 return ExprError(Diag(LowerBound->getExprLoc(),
4645 diag::err_omp_typecheck_section_not_integer)
4646 << 0 << LowerBound->getSourceRange());
4647 LowerBound = Res.get();
4648
4649 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4650 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4651 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4652 << 0 << LowerBound->getSourceRange();
4653 }
4654 if (Length) {
4655 auto Res =
4656 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4657 if (Res.isInvalid())
4658 return ExprError(Diag(Length->getExprLoc(),
4659 diag::err_omp_typecheck_section_not_integer)
4660 << 1 << Length->getSourceRange());
4661 Length = Res.get();
4662
4663 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4664 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4665 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4666 << 1 << Length->getSourceRange();
4667 }
4668
4669 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4670 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4671 // type. Note that functions are not objects, and that (in C99 parlance)
4672 // incomplete types are not object types.
4673 if (ResultTy->isFunctionType()) {
4674 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4675 << ResultTy << Base->getSourceRange();
4676 return ExprError();
4677 }
4678
4679 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4680 diag::err_omp_section_incomplete_type, Base))
4681 return ExprError();
4682
4683 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4684 Expr::EvalResult Result;
4685 if (LowerBound->EvaluateAsInt(Result, Context)) {
4686 // OpenMP 4.5, [2.4 Array Sections]
4687 // The array section must be a subset of the original array.
4688 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4689 if (LowerBoundValue.isNegative()) {
4690 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4691 << LowerBound->getSourceRange();
4692 return ExprError();
4693 }
4694 }
4695 }
4696
4697 if (Length) {
4698 Expr::EvalResult Result;
4699 if (Length->EvaluateAsInt(Result, Context)) {
4700 // OpenMP 4.5, [2.4 Array Sections]
4701 // The length must evaluate to non-negative integers.
4702 llvm::APSInt LengthValue = Result.Val.getInt();
4703 if (LengthValue.isNegative()) {
4704 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4705 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4706 << Length->getSourceRange();
4707 return ExprError();
4708 }
4709 }
4710 } else if (ColonLoc.isValid() &&
4711 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4712 !OriginalTy->isVariableArrayType()))) {
4713 // OpenMP 4.5, [2.4 Array Sections]
4714 // When the size of the array dimension is not known, the length must be
4715 // specified explicitly.
4716 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4717 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4718 return ExprError();
4719 }
4720
4721 if (!Base->getType()->isSpecificPlaceholderType(
4722 BuiltinType::OMPArraySection)) {
4723 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4724 if (Result.isInvalid())
4725 return ExprError();
4726 Base = Result.get();
4727 }
4728 return new (Context)
4729 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4730 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4731 }
4732
4733 ExprResult
4734 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4735 Expr *Idx, SourceLocation RLoc) {
4736 Expr *LHSExp = Base;
4737 Expr *RHSExp = Idx;
4738
4739 ExprValueKind VK = VK_LValue;
4740 ExprObjectKind OK = OK_Ordinary;
4741
4742 // Per C++ core issue 1213, the result is an xvalue if either operand is
4743 // a non-lvalue array, and an lvalue otherwise.
4744 if (getLangOpts().CPlusPlus11) {
4745 for (auto *Op : {LHSExp, RHSExp}) {
4746 Op = Op->IgnoreImplicit();
4747 if (Op->getType()->isArrayType() && !Op->isLValue())
4748 VK = VK_XValue;
4749 }
4750 }
4751
4752 // Perform default conversions.
4753 if (!LHSExp->getType()->getAs<VectorType>()) {
4754 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4755 if (Result.isInvalid())
4756 return ExprError();
4757 LHSExp = Result.get();
4758 }
4759 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4760 if (Result.isInvalid())
4761 return ExprError();
4762 RHSExp = Result.get();
4763
4764 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4765
4766 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4767 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4768 // in the subscript position. As a result, we need to derive the array base
4769 // and index from the expression types.
4770 Expr *BaseExpr, *IndexExpr;
4771 QualType ResultType;
4772 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4773 BaseExpr = LHSExp;
4774 IndexExpr = RHSExp;
4775 ResultType = Context.DependentTy;
4776 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4777 BaseExpr = LHSExp;
4778 IndexExpr = RHSExp;
4779 ResultType = PTy->getPointeeType();
4780 } else if (const ObjCObjectPointerType *PTy =
4781 LHSTy->getAs<ObjCObjectPointerType>()) {
4782 BaseExpr = LHSExp;
4783 IndexExpr = RHSExp;
4784
4785 // Use custom logic if this should be the pseudo-object subscript
4786 // expression.
4787 if (!LangOpts.isSubscriptPointerArithmetic())
4788 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4789 nullptr);
4790
4791 ResultType = PTy->getPointeeType();
4792 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4793 // Handle the uncommon case of "123[Ptr]".
4794 BaseExpr = RHSExp;
4795 IndexExpr = LHSExp;
4796 ResultType = PTy->getPointeeType();
4797 } else if (const ObjCObjectPointerType *PTy =
4798 RHSTy->getAs<ObjCObjectPointerType>()) {
4799 // Handle the uncommon case of "123[Ptr]".
4800 BaseExpr = RHSExp;
4801 IndexExpr = LHSExp;
4802 ResultType = PTy->getPointeeType();
4803 if (!LangOpts.isSubscriptPointerArithmetic()) {
4804 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4805 << ResultType << BaseExpr->getSourceRange();
4806 return ExprError();
4807 }
4808 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4809 BaseExpr = LHSExp; // vectors: V[123]
4810 IndexExpr = RHSExp;
4811 // We apply C++ DR1213 to vector subscripting too.
4812 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4813 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4814 if (Materialized.isInvalid())
4815 return ExprError();
4816 LHSExp = Materialized.get();
4817 }
4818 VK = LHSExp->getValueKind();
4819 if (VK != VK_RValue)
4820 OK = OK_VectorComponent;
4821
4822 ResultType = VTy->getElementType();
4823 QualType BaseType = BaseExpr->getType();
4824 Qualifiers BaseQuals = BaseType.getQualifiers();
4825 Qualifiers MemberQuals = ResultType.getQualifiers();
4826 Qualifiers Combined = BaseQuals + MemberQuals;
4827 if (Combined != MemberQuals)
4828 ResultType = Context.getQualifiedType(ResultType, Combined);
4829 } else if (LHSTy->isArrayType()) {
4830 // If we see an array that wasn't promoted by
4831 // DefaultFunctionArrayLvalueConversion, it must be an array that
4832 // wasn't promoted because of the C90 rule that doesn't
4833 // allow promoting non-lvalue arrays. Warn, then
4834 // force the promotion here.
4835 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4836 << LHSExp->getSourceRange();
4837 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4838 CK_ArrayToPointerDecay).get();
4839 LHSTy = LHSExp->getType();
4840
4841 BaseExpr = LHSExp;
4842 IndexExpr = RHSExp;
4843 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4844 } else if (RHSTy->isArrayType()) {
4845 // Same as previous, except for 123[f().a] case
4846 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4847 << RHSExp->getSourceRange();
4848 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4849 CK_ArrayToPointerDecay).get();
4850 RHSTy = RHSExp->getType();
4851
4852 BaseExpr = RHSExp;
4853 IndexExpr = LHSExp;
4854 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4855 } else {
4856 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4857 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4858 }
4859 // C99 6.5.2.1p1
4860 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4861 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4862 << IndexExpr->getSourceRange());
4863
4864 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4865 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4866 && !IndexExpr->isTypeDependent())
4867 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4868
4869 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4870 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4871 // type. Note that Functions are not objects, and that (in C99 parlance)
4872 // incomplete types are not object types.
4873 if (ResultType->isFunctionType()) {
4874 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4875 << ResultType << BaseExpr->getSourceRange();
4876 return ExprError();
4877 }
4878
4879 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4880 // GNU extension: subscripting on pointer to void
4881 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4882 << BaseExpr->getSourceRange();
4883
4884 // C forbids expressions of unqualified void type from being l-values.
4885 // See IsCForbiddenLValueType.
4886 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4887 } else if (!ResultType->isDependentType() &&
4888 RequireCompleteType(LLoc, ResultType,
4889 diag::err_subscript_incomplete_type, BaseExpr))
4890 return ExprError();
4891
4892 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4893 !ResultType.isCForbiddenLValueType());
4894
4895 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4896 FunctionScopes.size() > 1) {
4897 if (auto *TT =
4898 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4899 for (auto I = FunctionScopes.rbegin(),
4900 E = std::prev(FunctionScopes.rend());
4901 I != E; ++I) {
4902 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4903 if (CSI == nullptr)
4904 break;
4905 DeclContext *DC = nullptr;
4906 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4907 DC = LSI->CallOperator;
4908 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4909 DC = CRSI->TheCapturedDecl;
4910 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4911 DC = BSI->TheDecl;
4912 if (DC) {
4913 if (DC->containsDecl(TT->getDecl()))
4914 break;
4915 captureVariablyModifiedType(
4916 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4917 }
4918 }
4919 }
4920 }
4921
4922 return new (Context)
4923 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4924 }
4925
4926 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4927 ParmVarDecl *Param) {
4928 if (Param->hasUnparsedDefaultArg()) {
4929 Diag(CallLoc,
4930 diag::err_use_of_default_argument_to_function_declared_later) <<
4931 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4932 Diag(UnparsedDefaultArgLocs[Param],
4933 diag::note_default_argument_declared_here);
4934 return true;
4935 }
4936
4937 if (Param->hasUninstantiatedDefaultArg()) {
4938 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4939
4940 EnterExpressionEvaluationContext EvalContext(
4941 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4942
4943 // Instantiate the expression.
4944 //
4945 // FIXME: Pass in a correct Pattern argument, otherwise
4946 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4947 //
4948 // template<typename T>
4949 // struct A {
4950 // static int FooImpl();
4951 //
4952 // template<typename Tp>
4953 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4954 // // template argument list [[T], [Tp]], should be [[Tp]].
4955 // friend A<Tp> Foo(int a);
4956 // };
4957 //
4958 // template<typename T>
4959 // A<T> Foo(int a = A<T>::FooImpl());
4960 MultiLevelTemplateArgumentList MutiLevelArgList
4961 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4962
4963 InstantiatingTemplate Inst(*this, CallLoc, Param,
4964 MutiLevelArgList.getInnermost());
4965 if (Inst.isInvalid())
4966 return true;
4967 if (Inst.isAlreadyInstantiating()) {
4968 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4969 Param->setInvalidDecl();
4970 return true;
4971 }
4972
4973 ExprResult Result;
4974 {
4975 // C++ [dcl.fct.default]p5:
4976 // The names in the [default argument] expression are bound, and
4977 // the semantic constraints are checked, at the point where the
4978 // default argument expression appears.
4979 ContextRAII SavedContext(*this, FD);
4980 LocalInstantiationScope Local(*this);
4981 runWithSufficientStackSpace(CallLoc, [&] {
4982 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4983 /*DirectInit*/false);
4984 });
4985 }
4986 if (Result.isInvalid())
4987 return true;
4988
4989 // Check the expression as an initializer for the parameter.
4990 InitializedEntity Entity
4991 = InitializedEntity::InitializeParameter(Context, Param);
4992 InitializationKind Kind = InitializationKind::CreateCopy(
4993 Param->getLocation(),
4994 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4995 Expr *ResultE = Result.getAs<Expr>();
4996
4997 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4998 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4999 if (Result.isInvalid())
5000 return true;
5001
5002 Result =
5003 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5004 /*DiscardedValue*/ false);
5005 if (Result.isInvalid())
5006 return true;
5007
5008 // Remember the instantiated default argument.
5009 Param->setDefaultArg(Result.getAs<Expr>());
5010 if (ASTMutationListener *L = getASTMutationListener()) {
5011 L->DefaultArgumentInstantiated(Param);
5012 }
5013 }
5014
5015 // If the default argument expression is not set yet, we are building it now.
5016 if (!Param->hasInit()) {
5017 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5018 Param->setInvalidDecl();
5019 return true;
5020 }
5021
5022 // If the default expression creates temporaries, we need to
5023 // push them to the current stack of expression temporaries so they'll
5024 // be properly destroyed.
5025 // FIXME: We should really be rebuilding the default argument with new
5026 // bound temporaries; see the comment in PR5810.
5027 // We don't need to do that with block decls, though, because
5028 // blocks in default argument expression can never capture anything.
5029 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5030 // Set the "needs cleanups" bit regardless of whether there are
5031 // any explicit objects.
5032 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5033
5034 // Append all the objects to the cleanup list. Right now, this
5035 // should always be a no-op, because blocks in default argument
5036 // expressions should never be able to capture anything.
5037 assert(!Init->getNumObjects() &&
5038 "default argument expression has capturing blocks?");
5039 }
5040
5041 // We already type-checked the argument, so we know it works.
5042 // Just mark all of the declarations in this potentially-evaluated expression
5043 // as being "referenced".
5044 EnterExpressionEvaluationContext EvalContext(
5045 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5046 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5047 /*SkipLocalVariables=*/true);
5048 return false;
5049 }
5050
5051 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5052 FunctionDecl *FD, ParmVarDecl *Param) {
5053 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5054 return ExprError();
5055 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5056 }
5057
5058 Sema::VariadicCallType
5059 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5060 Expr *Fn) {
5061 if (Proto && Proto->isVariadic()) {
5062 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5063 return VariadicConstructor;
5064 else if (Fn && Fn->getType()->isBlockPointerType())
5065 return VariadicBlock;
5066 else if (FDecl) {
5067 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5068 if (Method->isInstance())
5069 return VariadicMethod;
5070 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5071 return VariadicMethod;
5072 return VariadicFunction;
5073 }
5074 return VariadicDoesNotApply;
5075 }
5076
5077 namespace {
5078 class FunctionCallCCC final : public FunctionCallFilterCCC {
5079 public:
5080 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5081 unsigned NumArgs, MemberExpr *ME)
5082 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5083 FunctionName(FuncName) {}
5084
5085 bool ValidateCandidate(const TypoCorrection &candidate) override {
5086 if (!candidate.getCorrectionSpecifier() ||
5087 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5088 return false;
5089 }
5090
5091 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5092 }
5093
5094 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5095 return std::make_unique<FunctionCallCCC>(*this);
5096 }
5097
5098 private:
5099 const IdentifierInfo *const FunctionName;
5100 };
5101 }
5102
5103 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5104 FunctionDecl *FDecl,
5105 ArrayRef<Expr *> Args) {
5106 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5107 DeclarationName FuncName = FDecl->getDeclName();
5108 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5109
5110 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5111 if (TypoCorrection Corrected = S.CorrectTypo(
5112 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5113 S.getScopeForContext(S.CurContext), nullptr, CCC,
5114 Sema::CTK_ErrorRecovery)) {
5115 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5116 if (Corrected.isOverloaded()) {
5117 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5118 OverloadCandidateSet::iterator Best;
5119 for (NamedDecl *CD : Corrected) {
5120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5121 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5122 OCS);
5123 }
5124 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5125 case OR_Success:
5126 ND = Best->FoundDecl;
5127 Corrected.setCorrectionDecl(ND);
5128 break;
5129 default:
5130 break;
5131 }
5132 }
5133 ND = ND->getUnderlyingDecl();
5134 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5135 return Corrected;
5136 }
5137 }
5138 return TypoCorrection();
5139 }
5140
5141 /// ConvertArgumentsForCall - Converts the arguments specified in
5142 /// Args/NumArgs to the parameter types of the function FDecl with
5143 /// function prototype Proto. Call is the call expression itself, and
5144 /// Fn is the function expression. For a C++ member function, this
5145 /// routine does not attempt to convert the object argument. Returns
5146 /// true if the call is ill-formed.
5147 bool
5148 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5149 FunctionDecl *FDecl,
5150 const FunctionProtoType *Proto,
5151 ArrayRef<Expr *> Args,
5152 SourceLocation RParenLoc,
5153 bool IsExecConfig) {
5154 // Bail out early if calling a builtin with custom typechecking.
5155 if (FDecl)
5156 if (unsigned ID = FDecl->getBuiltinID())
5157 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5158 return false;
5159
5160 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5161 // assignment, to the types of the corresponding parameter, ...
5162 unsigned NumParams = Proto->getNumParams();
5163 bool Invalid = false;
5164 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5165 unsigned FnKind = Fn->getType()->isBlockPointerType()
5166 ? 1 /* block */
5167 : (IsExecConfig ? 3 /* kernel function (exec config) */
5168 : 0 /* function */);
5169
5170 // If too few arguments are available (and we don't have default
5171 // arguments for the remaining parameters), don't make the call.
5172 if (Args.size() < NumParams) {
5173 if (Args.size() < MinArgs) {
5174 TypoCorrection TC;
5175 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5176 unsigned diag_id =
5177 MinArgs == NumParams && !Proto->isVariadic()
5178 ? diag::err_typecheck_call_too_few_args_suggest
5179 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5180 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5181 << static_cast<unsigned>(Args.size())
5182 << TC.getCorrectionRange());
5183 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5184 Diag(RParenLoc,
5185 MinArgs == NumParams && !Proto->isVariadic()
5186 ? diag::err_typecheck_call_too_few_args_one
5187 : diag::err_typecheck_call_too_few_args_at_least_one)
5188 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5189 else
5190 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5191 ? diag::err_typecheck_call_too_few_args
5192 : diag::err_typecheck_call_too_few_args_at_least)
5193 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5194 << Fn->getSourceRange();
5195
5196 // Emit the location of the prototype.
5197 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5198 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5199
5200 return true;
5201 }
5202 // We reserve space for the default arguments when we create
5203 // the call expression, before calling ConvertArgumentsForCall.
5204 assert((Call->getNumArgs() == NumParams) &&
5205 "We should have reserved space for the default arguments before!");
5206 }
5207
5208 // If too many are passed and not variadic, error on the extras and drop
5209 // them.
5210 if (Args.size() > NumParams) {
5211 if (!Proto->isVariadic()) {
5212 TypoCorrection TC;
5213 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5214 unsigned diag_id =
5215 MinArgs == NumParams && !Proto->isVariadic()
5216 ? diag::err_typecheck_call_too_many_args_suggest
5217 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5218 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5219 << static_cast<unsigned>(Args.size())
5220 << TC.getCorrectionRange());
5221 } else if (NumParams == 1 && FDecl &&
5222 FDecl->getParamDecl(0)->getDeclName())
5223 Diag(Args[NumParams]->getBeginLoc(),
5224 MinArgs == NumParams
5225 ? diag::err_typecheck_call_too_many_args_one
5226 : diag::err_typecheck_call_too_many_args_at_most_one)
5227 << FnKind << FDecl->getParamDecl(0)
5228 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5229 << SourceRange(Args[NumParams]->getBeginLoc(),
5230 Args.back()->getEndLoc());
5231 else
5232 Diag(Args[NumParams]->getBeginLoc(),
5233 MinArgs == NumParams
5234 ? diag::err_typecheck_call_too_many_args
5235 : diag::err_typecheck_call_too_many_args_at_most)
5236 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5237 << Fn->getSourceRange()
5238 << SourceRange(Args[NumParams]->getBeginLoc(),
5239 Args.back()->getEndLoc());
5240
5241 // Emit the location of the prototype.
5242 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5243 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5244
5245 // This deletes the extra arguments.
5246 Call->shrinkNumArgs(NumParams);
5247 return true;
5248 }
5249 }
5250 SmallVector<Expr *, 8> AllArgs;
5251 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5252
5253 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5254 AllArgs, CallType);
5255 if (Invalid)
5256 return true;
5257 unsigned TotalNumArgs = AllArgs.size();
5258 for (unsigned i = 0; i < TotalNumArgs; ++i)
5259 Call->setArg(i, AllArgs[i]);
5260
5261 return false;
5262 }
5263
5264 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5265 const FunctionProtoType *Proto,
5266 unsigned FirstParam, ArrayRef<Expr *> Args,
5267 SmallVectorImpl<Expr *> &AllArgs,
5268 VariadicCallType CallType, bool AllowExplicit,
5269 bool IsListInitialization) {
5270 unsigned NumParams = Proto->getNumParams();
5271 bool Invalid = false;
5272 size_t ArgIx = 0;
5273 // Continue to check argument types (even if we have too few/many args).
5274 for (unsigned i = FirstParam; i < NumParams; i++) {
5275 QualType ProtoArgType = Proto->getParamType(i);
5276
5277 Expr *Arg;
5278 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5279 if (ArgIx < Args.size()) {
5280 Arg = Args[ArgIx++];
5281
5282 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5283 diag::err_call_incomplete_argument, Arg))
5284 return true;
5285
5286 // Strip the unbridged-cast placeholder expression off, if applicable.
5287 bool CFAudited = false;
5288 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5289 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5290 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5291 Arg = stripARCUnbridgedCast(Arg);
5292 else if (getLangOpts().ObjCAutoRefCount &&
5293 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5294 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5295 CFAudited = true;
5296
5297 if (Proto->getExtParameterInfo(i).isNoEscape())
5298 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5299 BE->getBlockDecl()->setDoesNotEscape();
5300
5301 InitializedEntity Entity =
5302 Param ? InitializedEntity::InitializeParameter(Context, Param,
5303 ProtoArgType)
5304 : InitializedEntity::InitializeParameter(
5305 Context, ProtoArgType, Proto->isParamConsumed(i));
5306
5307 // Remember that parameter belongs to a CF audited API.
5308 if (CFAudited)
5309 Entity.setParameterCFAudited();
5310
5311 ExprResult ArgE = PerformCopyInitialization(
5312 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5313 if (ArgE.isInvalid())
5314 return true;
5315
5316 Arg = ArgE.getAs<Expr>();
5317 } else {
5318 assert(Param && "can't use default arguments without a known callee");
5319
5320 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5321 if (ArgExpr.isInvalid())
5322 return true;
5323
5324 Arg = ArgExpr.getAs<Expr>();
5325 }
5326
5327 // Check for array bounds violations for each argument to the call. This
5328 // check only triggers warnings when the argument isn't a more complex Expr
5329 // with its own checking, such as a BinaryOperator.
5330 CheckArrayAccess(Arg);
5331
5332 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5333 CheckStaticArrayArgument(CallLoc, Param, Arg);
5334
5335 AllArgs.push_back(Arg);
5336 }
5337
5338 // If this is a variadic call, handle args passed through "...".
5339 if (CallType != VariadicDoesNotApply) {
5340 // Assume that extern "C" functions with variadic arguments that
5341 // return __unknown_anytype aren't *really* variadic.
5342 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5343 FDecl->isExternC()) {
5344 for (Expr *A : Args.slice(ArgIx)) {
5345 QualType paramType; // ignored
5346 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5347 Invalid |= arg.isInvalid();
5348 AllArgs.push_back(arg.get());
5349 }
5350
5351 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5352 } else {
5353 for (Expr *A : Args.slice(ArgIx)) {
5354 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5355 Invalid |= Arg.isInvalid();
5356 // Copy blocks to the heap.
5357 if (A->getType()->isBlockPointerType())
5358 maybeExtendBlockObject(Arg);
5359 AllArgs.push_back(Arg.get());
5360 }
5361 }
5362
5363 // Check for array bounds violations.
5364 for (Expr *A : Args.slice(ArgIx))
5365 CheckArrayAccess(A);
5366 }
5367 return Invalid;
5368 }
5369
5370 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5371 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5372 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5373 TL = DTL.getOriginalLoc();
5374 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5375 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5376 << ATL.getLocalSourceRange();
5377 }
5378
5379 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5380 /// array parameter, check that it is non-null, and that if it is formed by
5381 /// array-to-pointer decay, the underlying array is sufficiently large.
5382 ///
5383 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5384 /// array type derivation, then for each call to the function, the value of the
5385 /// corresponding actual argument shall provide access to the first element of
5386 /// an array with at least as many elements as specified by the size expression.
5387 void
5388 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5389 ParmVarDecl *Param,
5390 const Expr *ArgExpr) {
5391 // Static array parameters are not supported in C++.
5392 if (!Param || getLangOpts().CPlusPlus)
5393 return;
5394
5395 QualType OrigTy = Param->getOriginalType();
5396
5397 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5398 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5399 return;
5400
5401 if (ArgExpr->isNullPointerConstant(Context,
5402 Expr::NPC_NeverValueDependent)) {
5403 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5404 DiagnoseCalleeStaticArrayParam(*this, Param);
5405 return;
5406 }
5407
5408 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5409 if (!CAT)
5410 return;
5411
5412 const ConstantArrayType *ArgCAT =
5413 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5414 if (!ArgCAT)
5415 return;
5416
5417 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5418 ArgCAT->getElementType())) {
5419 if (ArgCAT->getSize().ult(CAT->getSize())) {
5420 Diag(CallLoc, diag::warn_static_array_too_small)
5421 << ArgExpr->getSourceRange()
5422 << (unsigned)ArgCAT->getSize().getZExtValue()
5423 << (unsigned)CAT->getSize().getZExtValue() << 0;
5424 DiagnoseCalleeStaticArrayParam(*this, Param);
5425 }
5426 return;
5427 }
5428
5429 Optional<CharUnits> ArgSize =
5430 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5431 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5432 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5433 Diag(CallLoc, diag::warn_static_array_too_small)
5434 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5435 << (unsigned)ParmSize->getQuantity() << 1;
5436 DiagnoseCalleeStaticArrayParam(*this, Param);
5437 }
5438 }
5439
5440 /// Given a function expression of unknown-any type, try to rebuild it
5441 /// to have a function type.
5442 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5443
5444 /// Is the given type a placeholder that we need to lower out
5445 /// immediately during argument processing?
5446 static bool isPlaceholderToRemoveAsArg(QualType type) {
5447 // Placeholders are never sugared.
5448 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5449 if (!placeholder) return false;
5450
5451 switch (placeholder->getKind()) {
5452 // Ignore all the non-placeholder types.
5453 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5454 case BuiltinType::Id:
5455 #include "clang/Basic/OpenCLImageTypes.def"
5456 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5457 case BuiltinType::Id:
5458 #include "clang/Basic/OpenCLExtensionTypes.def"
5459 // In practice we'll never use this, since all SVE types are sugared
5460 // via TypedefTypes rather than exposed directly as BuiltinTypes.
5461 #define SVE_TYPE(Name, Id, SingletonId) \
5462 case BuiltinType::Id:
5463 #include "clang/Basic/AArch64SVEACLETypes.def"
5464 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5465 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5466 #include "clang/AST/BuiltinTypes.def"
5467 return false;
5468
5469 // We cannot lower out overload sets; they might validly be resolved
5470 // by the call machinery.
5471 case BuiltinType::Overload:
5472 return false;
5473
5474 // Unbridged casts in ARC can be handled in some call positions and
5475 // should be left in place.
5476 case BuiltinType::ARCUnbridgedCast:
5477 return false;
5478
5479 // Pseudo-objects should be converted as soon as possible.
5480 case BuiltinType::PseudoObject:
5481 return true;
5482
5483 // The debugger mode could theoretically but currently does not try
5484 // to resolve unknown-typed arguments based on known parameter types.
5485 case BuiltinType::UnknownAny:
5486 return true;
5487
5488 // These are always invalid as call arguments and should be reported.
5489 case BuiltinType::BoundMember:
5490 case BuiltinType::BuiltinFn:
5491 case BuiltinType::OMPArraySection:
5492 return true;
5493
5494 }
5495 llvm_unreachable("bad builtin type kind");
5496 }
5497
5498 /// Check an argument list for placeholders that we won't try to
5499 /// handle later.
5500 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5501 // Apply this processing to all the arguments at once instead of
5502 // dying at the first failure.
5503 bool hasInvalid = false;
5504 for (size_t i = 0, e = args.size(); i != e; i++) {
5505 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5506 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5507 if (result.isInvalid()) hasInvalid = true;
5508 else args[i] = result.get();
5509 } else if (hasInvalid) {
5510 (void)S.CorrectDelayedTyposInExpr(args[i]);
5511 }
5512 }
5513 return hasInvalid;
5514 }
5515
5516 /// If a builtin function has a pointer argument with no explicit address
5517 /// space, then it should be able to accept a pointer to any address
5518 /// space as input. In order to do this, we need to replace the
5519 /// standard builtin declaration with one that uses the same address space
5520 /// as the call.
5521 ///
5522 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5523 /// it does not contain any pointer arguments without
5524 /// an address space qualifer. Otherwise the rewritten
5525 /// FunctionDecl is returned.
5526 /// TODO: Handle pointer return types.
5527 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5528 FunctionDecl *FDecl,
5529 MultiExprArg ArgExprs) {
5530
5531 QualType DeclType = FDecl->getType();
5532 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5533
5534 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5535 ArgExprs.size() < FT->getNumParams())
5536 return nullptr;
5537
5538 bool NeedsNewDecl = false;
5539 unsigned i = 0;
5540 SmallVector<QualType, 8> OverloadParams;
5541
5542 for (QualType ParamType : FT->param_types()) {
5543
5544 // Convert array arguments to pointer to simplify type lookup.
5545 ExprResult ArgRes =
5546 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5547 if (ArgRes.isInvalid())
5548 return nullptr;
5549 Expr *Arg = ArgRes.get();
5550 QualType ArgType = Arg->getType();
5551 if (!ParamType->isPointerType() ||
5552 ParamType.hasAddressSpace() ||
5553 !ArgType->isPointerType() ||
5554 !ArgType->getPointeeType().hasAddressSpace()) {
5555 OverloadParams.push_back(ParamType);
5556 continue;
5557 }
5558
5559 QualType PointeeType = ParamType->getPointeeType();
5560 if (PointeeType.hasAddressSpace())
5561 continue;
5562
5563 NeedsNewDecl = true;
5564 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5565
5566 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5567 OverloadParams.push_back(Context.getPointerType(PointeeType));
5568 }
5569
5570 if (!NeedsNewDecl)
5571 return nullptr;
5572
5573 FunctionProtoType::ExtProtoInfo EPI;
5574 EPI.Variadic = FT->isVariadic();
5575 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5576 OverloadParams, EPI);
5577 DeclContext *Parent = FDecl->getParent();
5578 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5579 FDecl->getLocation(),
5580 FDecl->getLocation(),
5581 FDecl->getIdentifier(),
5582 OverloadTy,
5583 /*TInfo=*/nullptr,
5584 SC_Extern, false,
5585 /*hasPrototype=*/true);
5586 SmallVector<ParmVarDecl*, 16> Params;
5587 FT = cast<FunctionProtoType>(OverloadTy);
5588 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5589 QualType ParamType = FT->getParamType(i);
5590 ParmVarDecl *Parm =
5591 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5592 SourceLocation(), nullptr, ParamType,
5593 /*TInfo=*/nullptr, SC_None, nullptr);
5594 Parm->setScopeInfo(0, i);
5595 Params.push_back(Parm);
5596 }
5597 OverloadDecl->setParams(Params);
5598 return OverloadDecl;
5599 }
5600
5601 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5602 FunctionDecl *Callee,
5603 MultiExprArg ArgExprs) {
5604 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5605 // similar attributes) really don't like it when functions are called with an
5606 // invalid number of args.
5607 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5608 /*PartialOverloading=*/false) &&
5609 !Callee->isVariadic())
5610 return;
5611 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5612 return;
5613
5614 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5615 S.Diag(Fn->getBeginLoc(),
5616 isa<CXXMethodDecl>(Callee)
5617 ? diag::err_ovl_no_viable_member_function_in_call
5618 : diag::err_ovl_no_viable_function_in_call)
5619 << Callee << Callee->getSourceRange();
5620 S.Diag(Callee->getLocation(),
5621 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5622 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5623 return;
5624 }
5625 }
5626
5627 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5628 const UnresolvedMemberExpr *const UME, Sema &S) {
5629
5630 const auto GetFunctionLevelDCIfCXXClass =
5631 [](Sema &S) -> const CXXRecordDecl * {
5632 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5633 if (!DC || !DC->getParent())
5634 return nullptr;
5635
5636 // If the call to some member function was made from within a member
5637 // function body 'M' return return 'M's parent.
5638 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5639 return MD->getParent()->getCanonicalDecl();
5640 // else the call was made from within a default member initializer of a
5641 // class, so return the class.
5642 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5643 return RD->getCanonicalDecl();
5644 return nullptr;
5645 };
5646 // If our DeclContext is neither a member function nor a class (in the
5647 // case of a lambda in a default member initializer), we can't have an
5648 // enclosing 'this'.
5649
5650 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5651 if (!CurParentClass)
5652 return false;
5653
5654 // The naming class for implicit member functions call is the class in which
5655 // name lookup starts.
5656 const CXXRecordDecl *const NamingClass =
5657 UME->getNamingClass()->getCanonicalDecl();
5658 assert(NamingClass && "Must have naming class even for implicit access");
5659
5660 // If the unresolved member functions were found in a 'naming class' that is
5661 // related (either the same or derived from) to the class that contains the
5662 // member function that itself contained the implicit member access.
5663
5664 return CurParentClass == NamingClass ||
5665 CurParentClass->isDerivedFrom(NamingClass);
5666 }
5667
5668 static void
5669 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5670 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5671
5672 if (!UME)
5673 return;
5674
5675 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5676 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5677 // already been captured, or if this is an implicit member function call (if
5678 // it isn't, an attempt to capture 'this' should already have been made).
5679 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5680 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5681 return;
5682
5683 // Check if the naming class in which the unresolved members were found is
5684 // related (same as or is a base of) to the enclosing class.
5685
5686 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5687 return;
5688
5689
5690 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5691 // If the enclosing function is not dependent, then this lambda is
5692 // capture ready, so if we can capture this, do so.
5693 if (!EnclosingFunctionCtx->isDependentContext()) {
5694 // If the current lambda and all enclosing lambdas can capture 'this' -
5695 // then go ahead and capture 'this' (since our unresolved overload set
5696 // contains at least one non-static member function).
5697 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5698 S.CheckCXXThisCapture(CallLoc);
5699 } else if (S.CurContext->isDependentContext()) {
5700 // ... since this is an implicit member reference, that might potentially
5701 // involve a 'this' capture, mark 'this' for potential capture in
5702 // enclosing lambdas.
5703 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5704 CurLSI->addPotentialThisCapture(CallLoc);
5705 }
5706 }
5707
5708 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5709 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5710 Expr *ExecConfig) {
5711 ExprResult Call =
5712 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5713 if (Call.isInvalid())
5714 return Call;
5715
5716 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5717 // language modes.
5718 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5719 if (ULE->hasExplicitTemplateArgs() &&
5720 ULE->decls_begin() == ULE->decls_end()) {
5721 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5722 ? diag::warn_cxx17_compat_adl_only_template_id
5723 : diag::ext_adl_only_template_id)
5724 << ULE->getName();
5725 }
5726 }
5727
5728 return Call;
5729 }
5730
5731 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5732 /// This provides the location of the left/right parens and a list of comma
5733 /// locations.
5734 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5735 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5736 Expr *ExecConfig, bool IsExecConfig) {
5737 // Since this might be a postfix expression, get rid of ParenListExprs.
5738 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5739 if (Result.isInvalid()) return ExprError();
5740 Fn = Result.get();
5741
5742 if (checkArgsForPlaceholders(*this, ArgExprs))
5743 return ExprError();
5744
5745 if (getLangOpts().CPlusPlus) {
5746 // If this is a pseudo-destructor expression, build the call immediately.
5747 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5748 if (!ArgExprs.empty()) {
5749 // Pseudo-destructor calls should not have any arguments.
5750 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5751 << FixItHint::CreateRemoval(
5752 SourceRange(ArgExprs.front()->getBeginLoc(),
5753 ArgExprs.back()->getEndLoc()));
5754 }
5755
5756 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5757 VK_RValue, RParenLoc);
5758 }
5759 if (Fn->getType() == Context.PseudoObjectTy) {
5760 ExprResult result = CheckPlaceholderExpr(Fn);
5761 if (result.isInvalid()) return ExprError();
5762 Fn = result.get();
5763 }
5764
5765 // Determine whether this is a dependent call inside a C++ template,
5766 // in which case we won't do any semantic analysis now.
5767 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5768 if (ExecConfig) {
5769 return CUDAKernelCallExpr::Create(
5770 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5771 Context.DependentTy, VK_RValue, RParenLoc);
5772 } else {
5773
5774 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5775 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5776 Fn->getBeginLoc());
5777
5778 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5779 VK_RValue, RParenLoc);
5780 }
5781 }
5782
5783 // Determine whether this is a call to an object (C++ [over.call.object]).
5784 if (Fn->getType()->isRecordType())
5785 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5786 RParenLoc);
5787
5788 if (Fn->getType() == Context.UnknownAnyTy) {
5789 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5790 if (result.isInvalid()) return ExprError();
5791 Fn = result.get();
5792 }
5793
5794 if (Fn->getType() == Context.BoundMemberTy) {
5795 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5796 RParenLoc);
5797 }
5798 }
5799
5800 // Check for overloaded calls. This can happen even in C due to extensions.
5801 if (Fn->getType() == Context.OverloadTy) {
5802 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5803
5804 // We aren't supposed to apply this logic if there's an '&' involved.
5805 if (!find.HasFormOfMemberPointer) {
5806 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5807 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5808 VK_RValue, RParenLoc);
5809 OverloadExpr *ovl = find.Expression;
5810 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5811 return BuildOverloadedCallExpr(
5812 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5813 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5814 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5815 RParenLoc);
5816 }
5817 }
5818
5819 // If we're directly calling a function, get the appropriate declaration.
5820 if (Fn->getType() == Context.UnknownAnyTy) {
5821 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5822 if (result.isInvalid()) return ExprError();
5823 Fn = result.get();
5824 }
5825
5826 Expr *NakedFn = Fn->IgnoreParens();
5827
5828 bool CallingNDeclIndirectly = false;
5829 NamedDecl *NDecl = nullptr;
5830 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5831 if (UnOp->getOpcode() == UO_AddrOf) {
5832 CallingNDeclIndirectly = true;
5833 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5834 }
5835 }
5836
5837 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5838 NDecl = DRE->getDecl();
5839
5840 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5841 if (FDecl && FDecl->getBuiltinID()) {
5842 // Rewrite the function decl for this builtin by replacing parameters
5843 // with no explicit address space with the address space of the arguments
5844 // in ArgExprs.
5845 if ((FDecl =
5846 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5847 NDecl = FDecl;
5848 Fn = DeclRefExpr::Create(
5849 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5850 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5851 nullptr, DRE->isNonOdrUse());
5852 }
5853 }
5854 } else if (isa<MemberExpr>(NakedFn))
5855 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5856
5857 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5858 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5859 FD, /*Complain=*/true, Fn->getBeginLoc()))
5860 return ExprError();
5861
5862 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5863 return ExprError();
5864
5865 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5866 }
5867
5868 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5869 ExecConfig, IsExecConfig);
5870 }
5871
5872 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5873 ///
5874 /// __builtin_astype( value, dst type )
5875 ///
5876 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5877 SourceLocation BuiltinLoc,
5878 SourceLocation RParenLoc) {
5879 ExprValueKind VK = VK_RValue;
5880 ExprObjectKind OK = OK_Ordinary;
5881 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5882 QualType SrcTy = E->getType();
5883 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5884 return ExprError(Diag(BuiltinLoc,
5885 diag::err_invalid_astype_of_different_size)
5886 << DstTy
5887 << SrcTy
5888 << E->getSourceRange());
5889 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5890 }
5891
5892 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5893 /// provided arguments.
5894 ///
5895 /// __builtin_convertvector( value, dst type )
5896 ///
5897 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5898 SourceLocation BuiltinLoc,
5899 SourceLocation RParenLoc) {
5900 TypeSourceInfo *TInfo;
5901 GetTypeFromParser(ParsedDestTy, &TInfo);
5902 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5903 }
5904
5905 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5906 /// i.e. an expression not of \p OverloadTy. The expression should
5907 /// unary-convert to an expression of function-pointer or
5908 /// block-pointer type.
5909 ///
5910 /// \param NDecl the declaration being called, if available
5911 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5912 SourceLocation LParenLoc,
5913 ArrayRef<Expr *> Args,
5914 SourceLocation RParenLoc, Expr *Config,
5915 bool IsExecConfig, ADLCallKind UsesADL) {
5916 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5917 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5918
5919 // Functions with 'interrupt' attribute cannot be called directly.
5920 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5921 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5922 return ExprError();
5923 }
5924
5925 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5926 // so there's some risk when calling out to non-interrupt handler functions
5927 // that the callee might not preserve them. This is easy to diagnose here,
5928 // but can be very challenging to debug.
5929 if (auto *Caller = getCurFunctionDecl())
5930 if (Caller->hasAttr<ARMInterruptAttr>()) {
5931 bool VFP = Context.getTargetInfo().hasFeature("vfp");
5932 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5933 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5934 }
5935
5936 // Promote the function operand.
5937 // We special-case function promotion here because we only allow promoting
5938 // builtin functions to function pointers in the callee of a call.
5939 ExprResult Result;
5940 QualType ResultTy;
5941 if (BuiltinID &&
5942 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5943 // Extract the return type from the (builtin) function pointer type.
5944 // FIXME Several builtins still have setType in
5945 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5946 // Builtins.def to ensure they are correct before removing setType calls.
5947 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5948 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5949 ResultTy = FDecl->getCallResultType();
5950 } else {
5951 Result = CallExprUnaryConversions(Fn);
5952 ResultTy = Context.BoolTy;
5953 }
5954 if (Result.isInvalid())
5955 return ExprError();
5956 Fn = Result.get();
5957
5958 // Check for a valid function type, but only if it is not a builtin which
5959 // requires custom type checking. These will be handled by
5960 // CheckBuiltinFunctionCall below just after creation of the call expression.
5961 const FunctionType *FuncT = nullptr;
5962 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5963 retry:
5964 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5965 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5966 // have type pointer to function".
5967 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5968 if (!FuncT)
5969 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5970 << Fn->getType() << Fn->getSourceRange());
5971 } else if (const BlockPointerType *BPT =
5972 Fn->getType()->getAs<BlockPointerType>()) {
5973 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5974 } else {
5975 // Handle calls to expressions of unknown-any type.
5976 if (Fn->getType() == Context.UnknownAnyTy) {
5977 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5978 if (rewrite.isInvalid())
5979 return ExprError();
5980 Fn = rewrite.get();
5981 goto retry;
5982 }
5983
5984 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5985 << Fn->getType() << Fn->getSourceRange());
5986 }
5987 }
5988
5989 // Get the number of parameters in the function prototype, if any.
5990 // We will allocate space for max(Args.size(), NumParams) arguments
5991 // in the call expression.
5992 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5993 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5994
5995 CallExpr *TheCall;
5996 if (Config) {
5997 assert(UsesADL == ADLCallKind::NotADL &&
5998 "CUDAKernelCallExpr should not use ADL");
5999 TheCall =
6000 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6001 ResultTy, VK_RValue, RParenLoc, NumParams);
6002 } else {
6003 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6004 RParenLoc, NumParams, UsesADL);
6005 }
6006
6007 if (!getLangOpts().CPlusPlus) {
6008 // Forget about the nulled arguments since typo correction
6009 // do not handle them well.
6010 TheCall->shrinkNumArgs(Args.size());
6011 // C cannot always handle TypoExpr nodes in builtin calls and direct
6012 // function calls as their argument checking don't necessarily handle
6013 // dependent types properly, so make sure any TypoExprs have been
6014 // dealt with.
6015 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6016 if (!Result.isUsable()) return ExprError();
6017 CallExpr *TheOldCall = TheCall;
6018 TheCall = dyn_cast<CallExpr>(Result.get());
6019 bool CorrectedTypos = TheCall != TheOldCall;
6020 if (!TheCall) return Result;
6021 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6022
6023 // A new call expression node was created if some typos were corrected.
6024 // However it may not have been constructed with enough storage. In this
6025 // case, rebuild the node with enough storage. The waste of space is
6026 // immaterial since this only happens when some typos were corrected.
6027 if (CorrectedTypos && Args.size() < NumParams) {
6028 if (Config)
6029 TheCall = CUDAKernelCallExpr::Create(
6030 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6031 RParenLoc, NumParams);
6032 else
6033 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6034 RParenLoc, NumParams, UsesADL);
6035 }
6036 // We can now handle the nulled arguments for the default arguments.
6037 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6038 }
6039
6040 // Bail out early if calling a builtin with custom type checking.
6041 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6042 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6043
6044 if (getLangOpts().CUDA) {
6045 if (Config) {
6046 // CUDA: Kernel calls must be to global functions
6047 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6048 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6049 << FDecl << Fn->getSourceRange());
6050
6051 // CUDA: Kernel function must have 'void' return type
6052 if (!FuncT->getReturnType()->isVoidType() &&
6053 !FuncT->getReturnType()->getAs<AutoType>() &&
6054 !FuncT->getReturnType()->isInstantiationDependentType())
6055 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6056 << Fn->getType() << Fn->getSourceRange());
6057 } else {
6058 // CUDA: Calls to global functions must be configured
6059 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6060 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6061 << FDecl << Fn->getSourceRange());
6062 }
6063 }
6064
6065 // Check for a valid return type
6066 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6067 FDecl))
6068 return ExprError();
6069
6070 // We know the result type of the call, set it.
6071 TheCall->setType(FuncT->getCallResultType(Context));
6072 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6073
6074 if (Proto) {
6075 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6076 IsExecConfig))
6077 return ExprError();
6078 } else {
6079 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6080
6081 if (FDecl) {
6082 // Check if we have too few/too many template arguments, based
6083 // on our knowledge of the function definition.
6084 const FunctionDecl *Def = nullptr;
6085 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6086 Proto = Def->getType()->getAs<FunctionProtoType>();
6087 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6088 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6089 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6090 }
6091
6092 // If the function we're calling isn't a function prototype, but we have
6093 // a function prototype from a prior declaratiom, use that prototype.
6094 if (!FDecl->hasPrototype())
6095 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6096 }
6097
6098 // Promote the arguments (C99 6.5.2.2p6).
6099 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6100 Expr *Arg = Args[i];
6101
6102 if (Proto && i < Proto->getNumParams()) {
6103 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6104 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6105 ExprResult ArgE =
6106 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6107 if (ArgE.isInvalid())
6108 return true;
6109
6110 Arg = ArgE.getAs<Expr>();
6111
6112 } else {
6113 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6114
6115 if (ArgE.isInvalid())
6116 return true;
6117
6118 Arg = ArgE.getAs<Expr>();
6119 }
6120
6121 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6122 diag::err_call_incomplete_argument, Arg))
6123 return ExprError();
6124
6125 TheCall->setArg(i, Arg);
6126 }
6127 }
6128
6129 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6130 if (!Method->isStatic())
6131 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6132 << Fn->getSourceRange());
6133
6134 // Check for sentinels
6135 if (NDecl)
6136 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6137
6138 // Do special checking on direct calls to functions.
6139 if (FDecl) {
6140 if (CheckFunctionCall(FDecl, TheCall, Proto))
6141 return ExprError();
6142
6143 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6144
6145 if (BuiltinID)
6146 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6147 } else if (NDecl) {
6148 if (CheckPointerCall(NDecl, TheCall, Proto))
6149 return ExprError();
6150 } else {
6151 if (CheckOtherCall(TheCall, Proto))
6152 return ExprError();
6153 }
6154
6155 return MaybeBindToTemporary(TheCall);
6156 }
6157
6158 ExprResult
6159 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6160 SourceLocation RParenLoc, Expr *InitExpr) {
6161 assert(Ty && "ActOnCompoundLiteral(): missing type");
6162 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6163
6164 TypeSourceInfo *TInfo;
6165 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6166 if (!TInfo)
6167 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6168
6169 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6170 }
6171
6172 ExprResult
6173 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6174 SourceLocation RParenLoc, Expr *LiteralExpr) {
6175 QualType literalType = TInfo->getType();
6176
6177 if (literalType->isArrayType()) {
6178 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6179 diag::err_illegal_decl_array_incomplete_type,
6180 SourceRange(LParenLoc,
6181 LiteralExpr->getSourceRange().getEnd())))
6182 return ExprError();
6183 if (literalType->isVariableArrayType())
6184 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6185 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6186 } else if (!literalType->isDependentType() &&
6187 RequireCompleteType(LParenLoc, literalType,
6188 diag::err_typecheck_decl_incomplete_type,
6189 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6190 return ExprError();
6191
6192 InitializedEntity Entity
6193 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6194 InitializationKind Kind
6195 = InitializationKind::CreateCStyleCast(LParenLoc,
6196 SourceRange(LParenLoc, RParenLoc),
6197 /*InitList=*/true);
6198 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6199 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6200 &literalType);
6201 if (Result.isInvalid())
6202 return ExprError();
6203 LiteralExpr = Result.get();
6204
6205 bool isFileScope = !CurContext->isFunctionOrMethod();
6206
6207 // In C, compound literals are l-values for some reason.
6208 // For GCC compatibility, in C++, file-scope array compound literals with
6209 // constant initializers are also l-values, and compound literals are
6210 // otherwise prvalues.
6211 //
6212 // (GCC also treats C++ list-initialized file-scope array prvalues with
6213 // constant initializers as l-values, but that's non-conforming, so we don't
6214 // follow it there.)
6215 //
6216 // FIXME: It would be better to handle the lvalue cases as materializing and
6217 // lifetime-extending a temporary object, but our materialized temporaries
6218 // representation only supports lifetime extension from a variable, not "out
6219 // of thin air".
6220 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6221 // is bound to the result of applying array-to-pointer decay to the compound
6222 // literal.
6223 // FIXME: GCC supports compound literals of reference type, which should
6224 // obviously have a value kind derived from the kind of reference involved.
6225 ExprValueKind VK =
6226 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6227 ? VK_RValue
6228 : VK_LValue;
6229
6230 if (isFileScope)
6231 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6232 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6233 Expr *Init = ILE->getInit(i);
6234 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6235 }
6236
6237 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6238 VK, LiteralExpr, isFileScope);
6239 if (isFileScope) {
6240 if (!LiteralExpr->isTypeDependent() &&
6241 !LiteralExpr->isValueDependent() &&
6242 !literalType->isDependentType()) // C99 6.5.2.5p3
6243 if (CheckForConstantInitializer(LiteralExpr, literalType))
6244 return ExprError();
6245 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6246 literalType.getAddressSpace() != LangAS::Default) {
6247 // Embedded-C extensions to C99 6.5.2.5:
6248 // "If the compound literal occurs inside the body of a function, the
6249 // type name shall not be qualified by an address-space qualifier."
6250 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6251 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6252 return ExprError();
6253 }
6254
6255 // Compound literals that have automatic storage duration are destroyed at
6256 // the end of the scope. Emit diagnostics if it is or contains a C union type
6257 // that is non-trivial to destruct.
6258 if (!isFileScope)
6259 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6260 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6261 NTCUC_CompoundLiteral, NTCUK_Destruct);
6262
6263 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6264 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6265 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6266 E->getInitializer()->getExprLoc());
6267
6268 return MaybeBindToTemporary(E);
6269 }
6270
6271 ExprResult
6272 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6273 SourceLocation RBraceLoc) {
6274 // Only produce each kind of designated initialization diagnostic once.
6275 SourceLocation FirstDesignator;
6276 bool DiagnosedArrayDesignator = false;
6277 bool DiagnosedNestedDesignator = false;
6278 bool DiagnosedMixedDesignator = false;
6279
6280 // Check that any designated initializers are syntactically valid in the
6281 // current language mode.
6282 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6283 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6284 if (FirstDesignator.isInvalid())
6285 FirstDesignator = DIE->getBeginLoc();
6286
6287 if (!getLangOpts().CPlusPlus)
6288 break;
6289
6290 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6291 DiagnosedNestedDesignator = true;
6292 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6293 << DIE->getDesignatorsSourceRange();
6294 }
6295
6296 for (auto &Desig : DIE->designators()) {
6297 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6298 DiagnosedArrayDesignator = true;
6299 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6300 << Desig.getSourceRange();
6301 }
6302 }
6303
6304 if (!DiagnosedMixedDesignator &&
6305 !isa<DesignatedInitExpr>(InitArgList[0])) {
6306 DiagnosedMixedDesignator = true;
6307 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6308 << DIE->getSourceRange();
6309 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6310 << InitArgList[0]->getSourceRange();
6311 }
6312 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6313 isa<DesignatedInitExpr>(InitArgList[0])) {
6314 DiagnosedMixedDesignator = true;
6315 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6316 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6317 << DIE->getSourceRange();
6318 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6319 << InitArgList[I]->getSourceRange();
6320 }
6321 }
6322
6323 if (FirstDesignator.isValid()) {
6324 // Only diagnose designated initiaization as a C++20 extension if we didn't
6325 // already diagnose use of (non-C++20) C99 designator syntax.
6326 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6327 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6328 Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6329 ? diag::warn_cxx17_compat_designated_init
6330 : diag::ext_cxx_designated_init);
6331 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6332 Diag(FirstDesignator, diag::ext_designated_init);
6333 }
6334 }
6335
6336 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6337 }
6338
6339 ExprResult
6340 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6341 SourceLocation RBraceLoc) {
6342 // Semantic analysis for initializers is done by ActOnDeclarator() and
6343 // CheckInitializer() - it requires knowledge of the object being initialized.
6344
6345 // Immediately handle non-overload placeholders. Overloads can be
6346 // resolved contextually, but everything else here can't.
6347 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6348 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6349 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6350
6351 // Ignore failures; dropping the entire initializer list because
6352 // of one failure would be terrible for indexing/etc.
6353 if (result.isInvalid()) continue;
6354
6355 InitArgList[I] = result.get();
6356 }
6357 }
6358
6359 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6360 RBraceLoc);
6361 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6362 return E;
6363 }
6364
6365 /// Do an explicit extend of the given block pointer if we're in ARC.
6366 void Sema::maybeExtendBlockObject(ExprResult &E) {
6367 assert(E.get()->getType()->isBlockPointerType());
6368 assert(E.get()->isRValue());
6369
6370 // Only do this in an r-value context.
6371 if (!getLangOpts().ObjCAutoRefCount) return;
6372
6373 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6374 CK_ARCExtendBlockObject, E.get(),
6375 /*base path*/ nullptr, VK_RValue);
6376 Cleanup.setExprNeedsCleanups(true);
6377 }
6378
6379 /// Prepare a conversion of the given expression to an ObjC object
6380 /// pointer type.
6381 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6382 QualType type = E.get()->getType();
6383 if (type->isObjCObjectPointerType()) {
6384 return CK_BitCast;
6385 } else if (type->isBlockPointerType()) {
6386 maybeExtendBlockObject(E);
6387 return CK_BlockPointerToObjCPointerCast;
6388 } else {
6389 assert(type->isPointerType());
6390 return CK_CPointerToObjCPointerCast;
6391 }
6392 }
6393
6394 /// Prepares for a scalar cast, performing all the necessary stages
6395 /// except the final cast and returning the kind required.
6396 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6397 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6398 // Also, callers should have filtered out the invalid cases with
6399 // pointers. Everything else should be possible.
6400
6401 QualType SrcTy = Src.get()->getType();
6402 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6403 return CK_NoOp;
6404
6405 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6406 case Type::STK_MemberPointer:
6407 llvm_unreachable("member pointer type in C");
6408
6409 case Type::STK_CPointer:
6410 case Type::STK_BlockPointer:
6411 case Type::STK_ObjCObjectPointer:
6412 switch (DestTy->getScalarTypeKind()) {
6413 case Type::STK_CPointer: {
6414 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6415 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6416 if (SrcAS != DestAS)
6417 return CK_AddressSpaceConversion;
6418 if (Context.hasCvrSimilarType(SrcTy, DestTy))
6419 return CK_NoOp;
6420 return CK_BitCast;
6421 }
6422 case Type::STK_BlockPointer:
6423 return (SrcKind == Type::STK_BlockPointer
6424 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6425 case Type::STK_ObjCObjectPointer:
6426 if (SrcKind == Type::STK_ObjCObjectPointer)
6427 return CK_BitCast;
6428 if (SrcKind == Type::STK_CPointer)
6429 return CK_CPointerToObjCPointerCast;
6430 maybeExtendBlockObject(Src);
6431 return CK_BlockPointerToObjCPointerCast;
6432 case Type::STK_Bool:
6433 return CK_PointerToBoolean;
6434 case Type::STK_Integral:
6435 return CK_PointerToIntegral;
6436 case Type::STK_Floating:
6437 case Type::STK_FloatingComplex:
6438 case Type::STK_IntegralComplex:
6439 case Type::STK_MemberPointer:
6440 case Type::STK_FixedPoint:
6441 llvm_unreachable("illegal cast from pointer");
6442 }
6443 llvm_unreachable("Should have returned before this");
6444
6445 case Type::STK_FixedPoint:
6446 switch (DestTy->getScalarTypeKind()) {
6447 case Type::STK_FixedPoint:
6448 return CK_FixedPointCast;
6449 case Type::STK_Bool:
6450 return CK_FixedPointToBoolean;
6451 case Type::STK_Integral:
6452 return CK_FixedPointToIntegral;
6453 case Type::STK_Floating:
6454 case Type::STK_IntegralComplex:
6455 case Type::STK_FloatingComplex:
6456 Diag(Src.get()->getExprLoc(),
6457 diag::err_unimplemented_conversion_with_fixed_point_type)
6458 << DestTy;
6459 return CK_IntegralCast;
6460 case Type::STK_CPointer:
6461 case Type::STK_ObjCObjectPointer:
6462 case Type::STK_BlockPointer:
6463 case Type::STK_MemberPointer:
6464 llvm_unreachable("illegal cast to pointer type");
6465 }
6466 llvm_unreachable("Should have returned before this");
6467
6468 case Type::STK_Bool: // casting from bool is like casting from an integer
6469 case Type::STK_Integral:
6470 switch (DestTy->getScalarTypeKind()) {
6471 case Type::STK_CPointer:
6472 case Type::STK_ObjCObjectPointer:
6473 case Type::STK_BlockPointer:
6474 if (Src.get()->isNullPointerConstant(Context,
6475 Expr::NPC_ValueDependentIsNull))
6476 return CK_NullToPointer;
6477 return CK_IntegralToPointer;
6478 case Type::STK_Bool:
6479 return CK_IntegralToBoolean;
6480 case Type::STK_Integral:
6481 return CK_IntegralCast;
6482 case Type::STK_Floating:
6483 return CK_IntegralToFloating;
6484 case Type::STK_IntegralComplex:
6485 Src = ImpCastExprToType(Src.get(),
6486 DestTy->castAs<ComplexType>()->getElementType(),
6487 CK_IntegralCast);
6488 return CK_IntegralRealToComplex;
6489 case Type::STK_FloatingComplex:
6490 Src = ImpCastExprToType(Src.get(),
6491 DestTy->castAs<ComplexType>()->getElementType(),
6492 CK_IntegralToFloating);
6493 return CK_FloatingRealToComplex;
6494 case Type::STK_MemberPointer:
6495 llvm_unreachable("member pointer type in C");
6496 case Type::STK_FixedPoint:
6497 return CK_IntegralToFixedPoint;
6498 }
6499 llvm_unreachable("Should have returned before this");
6500
6501 case Type::STK_Floating:
6502 switch (DestTy->getScalarTypeKind()) {
6503 case Type::STK_Floating:
6504 return CK_FloatingCast;
6505 case Type::STK_Bool:
6506 return CK_FloatingToBoolean;
6507 case Type::STK_Integral:
6508 return CK_FloatingToIntegral;
6509 case Type::STK_FloatingComplex:
6510 Src = ImpCastExprToType(Src.get(),
6511 DestTy->castAs<ComplexType>()->getElementType(),
6512 CK_FloatingCast);
6513 return CK_FloatingRealToComplex;
6514 case Type::STK_IntegralComplex:
6515 Src = ImpCastExprToType(Src.get(),
6516 DestTy->castAs<ComplexType>()->getElementType(),
6517 CK_FloatingToIntegral);
6518 return CK_IntegralRealToComplex;
6519 case Type::STK_CPointer:
6520 case Type::STK_ObjCObjectPointer:
6521 case Type::STK_BlockPointer:
6522 llvm_unreachable("valid float->pointer cast?");
6523 case Type::STK_MemberPointer:
6524 llvm_unreachable("member pointer type in C");
6525 case Type::STK_FixedPoint:
6526 Diag(Src.get()->getExprLoc(),
6527 diag::err_unimplemented_conversion_with_fixed_point_type)
6528 << SrcTy;
6529 return CK_IntegralCast;
6530 }
6531 llvm_unreachable("Should have returned before this");
6532
6533 case Type::STK_FloatingComplex:
6534 switch (DestTy->getScalarTypeKind()) {
6535 case Type::STK_FloatingComplex:
6536 return CK_FloatingComplexCast;
6537 case Type::STK_IntegralComplex:
6538 return CK_FloatingComplexToIntegralComplex;
6539 case Type::STK_Floating: {
6540 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6541 if (Context.hasSameType(ET, DestTy))
6542 return CK_FloatingComplexToReal;
6543 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6544 return CK_FloatingCast;
6545 }
6546 case Type::STK_Bool:
6547 return CK_FloatingComplexToBoolean;
6548 case Type::STK_Integral:
6549 Src = ImpCastExprToType(Src.get(),
6550 SrcTy->castAs<ComplexType>()->getElementType(),
6551 CK_FloatingComplexToReal);
6552 return CK_FloatingToIntegral;
6553 case Type::STK_CPointer:
6554 case Type::STK_ObjCObjectPointer:
6555 case Type::STK_BlockPointer:
6556 llvm_unreachable("valid complex float->pointer cast?");
6557 case Type::STK_MemberPointer:
6558 llvm_unreachable("member pointer type in C");
6559 case Type::STK_FixedPoint:
6560 Diag(Src.get()->getExprLoc(),
6561 diag::err_unimplemented_conversion_with_fixed_point_type)
6562 << SrcTy;
6563 return CK_IntegralCast;
6564 }
6565 llvm_unreachable("Should have returned before this");
6566
6567 case Type::STK_IntegralComplex:
6568 switch (DestTy->getScalarTypeKind()) {
6569 case Type::STK_FloatingComplex:
6570 return CK_IntegralComplexToFloatingComplex;
6571 case Type::STK_IntegralComplex:
6572 return CK_IntegralComplexCast;
6573 case Type::STK_Integral: {
6574 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6575 if (Context.hasSameType(ET, DestTy))
6576 return CK_IntegralComplexToReal;
6577 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6578 return CK_IntegralCast;
6579 }
6580 case Type::STK_Bool:
6581 return CK_IntegralComplexToBoolean;
6582 case Type::STK_Floating:
6583 Src = ImpCastExprToType(Src.get(),
6584 SrcTy->castAs<ComplexType>()->getElementType(),
6585 CK_IntegralComplexToReal);
6586 return CK_IntegralToFloating;
6587 case Type::STK_CPointer:
6588 case Type::STK_ObjCObjectPointer:
6589 case Type::STK_BlockPointer:
6590 llvm_unreachable("valid complex int->pointer cast?");
6591 case Type::STK_MemberPointer:
6592 llvm_unreachable("member pointer type in C");
6593 case Type::STK_FixedPoint:
6594 Diag(Src.get()->getExprLoc(),
6595 diag::err_unimplemented_conversion_with_fixed_point_type)
6596 << SrcTy;
6597 return CK_IntegralCast;
6598 }
6599 llvm_unreachable("Should have returned before this");
6600 }
6601
6602 llvm_unreachable("Unhandled scalar cast");
6603 }
6604
6605 static bool breakDownVectorType(QualType type, uint64_t &len,
6606 QualType &eltType) {
6607 // Vectors are simple.
6608 if (const VectorType *vecType = type->getAs<VectorType>()) {
6609 len = vecType->getNumElements();
6610 eltType = vecType->getElementType();
6611 assert(eltType->isScalarType());
6612 return true;
6613 }
6614
6615 // We allow lax conversion to and from non-vector types, but only if
6616 // they're real types (i.e. non-complex, non-pointer scalar types).
6617 if (!type->isRealType()) return false;
6618
6619 len = 1;
6620 eltType = type;
6621 return true;
6622 }
6623
6624 /// Are the two types lax-compatible vector types? That is, given
6625 /// that one of them is a vector, do they have equal storage sizes,
6626 /// where the storage size is the number of elements times the element
6627 /// size?
6628 ///
6629 /// This will also return false if either of the types is neither a
6630 /// vector nor a real type.
6631 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6632 assert(destTy->isVectorType() || srcTy->isVectorType());
6633
6634 // Disallow lax conversions between scalars and ExtVectors (these
6635 // conversions are allowed for other vector types because common headers
6636 // depend on them). Most scalar OP ExtVector cases are handled by the
6637 // splat path anyway, which does what we want (convert, not bitcast).
6638 // What this rules out for ExtVectors is crazy things like char4*float.
6639 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6640 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6641
6642 uint64_t srcLen, destLen;
6643 QualType srcEltTy, destEltTy;
6644 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6645 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6646
6647 // ASTContext::getTypeSize will return the size rounded up to a
6648 // power of 2, so instead of using that, we need to use the raw
6649 // element size multiplied by the element count.
6650 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6651 uint64_t destEltSize = Context.getTypeSize(destEltTy);
6652
6653 return (srcLen * srcEltSize == destLen * destEltSize);
6654 }
6655
6656 /// Is this a legal conversion between two types, one of which is
6657 /// known to be a vector type?
6658 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6659 assert(destTy->isVectorType() || srcTy->isVectorType());
6660
6661 switch (Context.getLangOpts().getLaxVectorConversions()) {
6662 case LangOptions::LaxVectorConversionKind::None:
6663 return false;
6664
6665 case LangOptions::LaxVectorConversionKind::Integer:
6666 if (!srcTy->isIntegralOrEnumerationType()) {
6667 auto *Vec = srcTy->getAs<VectorType>();
6668 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6669 return false;
6670 }
6671 if (!destTy->isIntegralOrEnumerationType()) {
6672 auto *Vec = destTy->getAs<VectorType>();
6673 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6674 return false;
6675 }
6676 // OK, integer (vector) -> integer (vector) bitcast.
6677 break;
6678
6679 case LangOptions::LaxVectorConversionKind::All:
6680 break;
6681 }
6682
6683 return areLaxCompatibleVectorTypes(srcTy, destTy);
6684 }
6685
6686 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6687 CastKind &Kind) {
6688 assert(VectorTy->isVectorType() && "Not a vector type!");
6689
6690 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6691 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6692 return Diag(R.getBegin(),
6693 Ty->isVectorType() ?
6694 diag::err_invalid_conversion_between_vectors :
6695 diag::err_invalid_conversion_between_vector_and_integer)
6696 << VectorTy << Ty << R;
6697 } else
6698 return Diag(R.getBegin(),
6699 diag::err_invalid_conversion_between_vector_and_scalar)
6700 << VectorTy << Ty << R;
6701
6702 Kind = CK_BitCast;
6703 return false;
6704 }
6705
6706 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6707 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6708
6709 if (DestElemTy == SplattedExpr->getType())
6710 return SplattedExpr;
6711
6712 assert(DestElemTy->isFloatingType() ||
6713 DestElemTy->isIntegralOrEnumerationType());
6714
6715 CastKind CK;
6716 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6717 // OpenCL requires that we convert `true` boolean expressions to -1, but
6718 // only when splatting vectors.
6719 if (DestElemTy->isFloatingType()) {
6720 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6721 // in two steps: boolean to signed integral, then to floating.
6722 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6723 CK_BooleanToSignedIntegral);
6724 SplattedExpr = CastExprRes.get();
6725 CK = CK_IntegralToFloating;
6726 } else {
6727 CK = CK_BooleanToSignedIntegral;
6728 }
6729 } else {
6730 ExprResult CastExprRes = SplattedExpr;
6731 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6732 if (CastExprRes.isInvalid())
6733 return ExprError();
6734 SplattedExpr = CastExprRes.get();
6735 }
6736 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6737 }
6738
6739 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6740 Expr *CastExpr, CastKind &Kind) {
6741 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6742
6743 QualType SrcTy = CastExpr->getType();
6744
6745 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6746 // an ExtVectorType.
6747 // In OpenCL, casts between vectors of different types are not allowed.
6748 // (See OpenCL 6.2).
6749 if (SrcTy->isVectorType()) {
6750 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6751 (getLangOpts().OpenCL &&
6752 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6753 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6754 << DestTy << SrcTy << R;
6755 return ExprError();
6756 }
6757 Kind = CK_BitCast;
6758 return CastExpr;
6759 }
6760
6761 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6762 // conversion will take place first from scalar to elt type, and then
6763 // splat from elt type to vector.
6764 if (SrcTy->isPointerType())
6765 return Diag(R.getBegin(),
6766 diag::err_invalid_conversion_between_vector_and_scalar)
6767 << DestTy << SrcTy << R;
6768
6769 Kind = CK_VectorSplat;
6770 return prepareVectorSplat(DestTy, CastExpr);
6771 }
6772
6773 ExprResult
6774 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6775 Declarator &D, ParsedType &Ty,
6776 SourceLocation RParenLoc, Expr *CastExpr) {
6777 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6778 "ActOnCastExpr(): missing type or expr");
6779
6780 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6781 if (D.isInvalidType())
6782 return ExprError();
6783
6784 if (getLangOpts().CPlusPlus) {
6785 // Check that there are no default arguments (C++ only).
6786 CheckExtraCXXDefaultArguments(D);
6787 } else {
6788 // Make sure any TypoExprs have been dealt with.
6789 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6790 if (!Res.isUsable())
6791 return ExprError();
6792 CastExpr = Res.get();
6793 }
6794
6795 checkUnusedDeclAttributes(D);
6796
6797 QualType castType = castTInfo->getType();
6798 Ty = CreateParsedType(castType, castTInfo);
6799
6800 bool isVectorLiteral = false;
6801
6802 // Check for an altivec or OpenCL literal,
6803 // i.e. all the elements are integer constants.
6804 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6805 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6806 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6807 && castType->isVectorType() && (PE || PLE)) {
6808 if (PLE && PLE->getNumExprs() == 0) {
6809 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6810 return ExprError();
6811 }
6812 if (PE || PLE->getNumExprs() == 1) {
6813 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6814 if (!E->getType()->isVectorType())
6815 isVectorLiteral = true;
6816 }
6817 else
6818 isVectorLiteral = true;
6819 }
6820
6821 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6822 // then handle it as such.
6823 if (isVectorLiteral)
6824 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6825
6826 // If the Expr being casted is a ParenListExpr, handle it specially.
6827 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6828 // sequence of BinOp comma operators.
6829 if (isa<ParenListExpr>(CastExpr)) {
6830 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6831 if (Result.isInvalid()) return ExprError();
6832 CastExpr = Result.get();
6833 }
6834
6835 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6836 !getSourceManager().isInSystemMacro(LParenLoc))
6837 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6838
6839 CheckTollFreeBridgeCast(castType, CastExpr);
6840
6841 CheckObjCBridgeRelatedCast(castType, CastExpr);
6842
6843 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6844
6845 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6846 }
6847
6848 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6849 SourceLocation RParenLoc, Expr *E,
6850 TypeSourceInfo *TInfo) {
6851 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6852 "Expected paren or paren list expression");
6853
6854 Expr **exprs;
6855 unsigned numExprs;
6856 Expr *subExpr;
6857 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6858 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6859 LiteralLParenLoc = PE->getLParenLoc();
6860 LiteralRParenLoc = PE->getRParenLoc();
6861 exprs = PE->getExprs();
6862 numExprs = PE->getNumExprs();
6863 } else { // isa<ParenExpr> by assertion at function entrance
6864 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6865 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6866 subExpr = cast<ParenExpr>(E)->getSubExpr();
6867 exprs = &subExpr;
6868 numExprs = 1;
6869 }
6870
6871 QualType Ty = TInfo->getType();
6872 assert(Ty->isVectorType() && "Expected vector type");
6873
6874 SmallVector<Expr *, 8> initExprs;
6875 const VectorType *VTy = Ty->castAs<VectorType>();
6876 unsigned numElems = VTy->getNumElements();
6877
6878 // '(...)' form of vector initialization in AltiVec: the number of
6879 // initializers must be one or must match the size of the vector.
6880 // If a single value is specified in the initializer then it will be
6881 // replicated to all the components of the vector
6882 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6883 // The number of initializers must be one or must match the size of the
6884 // vector. If a single value is specified in the initializer then it will
6885 // be replicated to all the components of the vector
6886 if (numExprs == 1) {
6887 QualType ElemTy = VTy->getElementType();
6888 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6889 if (Literal.isInvalid())
6890 return ExprError();
6891 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6892 PrepareScalarCast(Literal, ElemTy));
6893 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6894 }
6895 else if (numExprs < numElems) {
6896 Diag(E->getExprLoc(),
6897 diag::err_incorrect_number_of_vector_initializers);
6898 return ExprError();
6899 }
6900 else
6901 initExprs.append(exprs, exprs + numExprs);
6902 }
6903 else {
6904 // For OpenCL, when the number of initializers is a single value,
6905 // it will be replicated to all components of the vector.
6906 if (getLangOpts().OpenCL &&
6907 VTy->getVectorKind() == VectorType::GenericVector &&
6908 numExprs == 1) {
6909 QualType ElemTy = VTy->getElementType();
6910 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6911 if (Literal.isInvalid())
6912 return ExprError();
6913 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6914 PrepareScalarCast(Literal, ElemTy));
6915 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6916 }
6917
6918 initExprs.append(exprs, exprs + numExprs);
6919 }
6920 // FIXME: This means that pretty-printing the final AST will produce curly
6921 // braces instead of the original commas.
6922 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6923 initExprs, LiteralRParenLoc);
6924 initE->setType(Ty);
6925 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6926 }
6927
6928 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6929 /// the ParenListExpr into a sequence of comma binary operators.
6930 ExprResult
6931 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6932 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6933 if (!E)
6934 return OrigExpr;
6935
6936 ExprResult Result(E->getExpr(0));
6937
6938 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6939 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6940 E->getExpr(i));
6941
6942 if (Result.isInvalid()) return ExprError();
6943
6944 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6945 }
6946
6947 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6948 SourceLocation R,
6949 MultiExprArg Val) {
6950 return ParenListExpr::Create(Context, L, Val, R);
6951 }
6952
6953 /// Emit a specialized diagnostic when one expression is a null pointer
6954 /// constant and the other is not a pointer. Returns true if a diagnostic is
6955 /// emitted.
6956 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6957 SourceLocation QuestionLoc) {
6958 Expr *NullExpr = LHSExpr;
6959 Expr *NonPointerExpr = RHSExpr;
6960 Expr::NullPointerConstantKind NullKind =
6961 NullExpr->isNullPointerConstant(Context,
6962 Expr::NPC_ValueDependentIsNotNull);
6963
6964 if (NullKind == Expr::NPCK_NotNull) {
6965 NullExpr = RHSExpr;
6966 NonPointerExpr = LHSExpr;
6967 NullKind =
6968 NullExpr->isNullPointerConstant(Context,
6969 Expr::NPC_ValueDependentIsNotNull);
6970 }
6971
6972 if (NullKind == Expr::NPCK_NotNull)
6973 return false;
6974
6975 if (NullKind == Expr::NPCK_ZeroExpression)
6976 return false;
6977
6978 if (NullKind == Expr::NPCK_ZeroLiteral) {
6979 // In this case, check to make sure that we got here from a "NULL"
6980 // string in the source code.
6981 NullExpr = NullExpr->IgnoreParenImpCasts();
6982 SourceLocation loc = NullExpr->getExprLoc();
6983 if (!findMacroSpelling(loc, "NULL"))
6984 return false;
6985 }
6986
6987 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6988 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6989 << NonPointerExpr->getType() << DiagType
6990 << NonPointerExpr->getSourceRange();
6991 return true;
6992 }
6993
6994 /// Return false if the condition expression is valid, true otherwise.
6995 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6996 QualType CondTy = Cond->getType();
6997
6998 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6999 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7000 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7001 << CondTy << Cond->getSourceRange();
7002 return true;
7003 }
7004
7005 // C99 6.5.15p2
7006 if (CondTy->isScalarType()) return false;
7007
7008 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7009 << CondTy << Cond->getSourceRange();
7010 return true;
7011 }
7012
7013 /// Handle when one or both operands are void type.
7014 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7015 ExprResult &RHS) {
7016 Expr *LHSExpr = LHS.get();
7017 Expr *RHSExpr = RHS.get();
7018
7019 if (!LHSExpr->getType()->isVoidType())
7020 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7021 << RHSExpr->getSourceRange();
7022 if (!RHSExpr->getType()->isVoidType())
7023 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7024 << LHSExpr->getSourceRange();
7025 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7026 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7027 return S.Context.VoidTy;
7028 }
7029
7030 /// Return false if the NullExpr can be promoted to PointerTy,
7031 /// true otherwise.
7032 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7033 QualType PointerTy) {
7034 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7035 !NullExpr.get()->isNullPointerConstant(S.Context,
7036 Expr::NPC_ValueDependentIsNull))
7037 return true;
7038
7039 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7040 return false;
7041 }
7042
7043 /// Checks compatibility between two pointers and return the resulting
7044 /// type.
7045 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7046 ExprResult &RHS,
7047 SourceLocation Loc) {
7048 QualType LHSTy = LHS.get()->getType();
7049 QualType RHSTy = RHS.get()->getType();
7050
7051 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7052 // Two identical pointers types are always compatible.
7053 return LHSTy;
7054 }
7055
7056 QualType lhptee, rhptee;
7057
7058 // Get the pointee types.
7059 bool IsBlockPointer = false;
7060 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7061 lhptee = LHSBTy->getPointeeType();
7062 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7063 IsBlockPointer = true;
7064 } else {
7065 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7066 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7067 }
7068
7069 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7070 // differently qualified versions of compatible types, the result type is
7071 // a pointer to an appropriately qualified version of the composite
7072 // type.
7073
7074 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7075 // clause doesn't make sense for our extensions. E.g. address space 2 should
7076 // be incompatible with address space 3: they may live on different devices or
7077 // anything.
7078 Qualifiers lhQual = lhptee.getQualifiers();
7079 Qualifiers rhQual = rhptee.getQualifiers();
7080
7081 LangAS ResultAddrSpace = LangAS::Default;
7082 LangAS LAddrSpace = lhQual.getAddressSpace();
7083 LangAS RAddrSpace = rhQual.getAddressSpace();
7084
7085 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7086 // spaces is disallowed.
7087 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7088 ResultAddrSpace = LAddrSpace;
7089 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7090 ResultAddrSpace = RAddrSpace;
7091 else {
7092 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7093 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7094 << RHS.get()->getSourceRange();
7095 return QualType();
7096 }
7097
7098 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7099 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7100 lhQual.removeCVRQualifiers();
7101 rhQual.removeCVRQualifiers();
7102
7103 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7104 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7105 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7106 // qual types are compatible iff
7107 // * corresponded types are compatible
7108 // * CVR qualifiers are equal
7109 // * address spaces are equal
7110 // Thus for conditional operator we merge CVR and address space unqualified
7111 // pointees and if there is a composite type we return a pointer to it with
7112 // merged qualifiers.
7113 LHSCastKind =
7114 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7115 RHSCastKind =
7116 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7117 lhQual.removeAddressSpace();
7118 rhQual.removeAddressSpace();
7119
7120 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7121 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7122
7123 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7124
7125 if (CompositeTy.isNull()) {
7126 // In this situation, we assume void* type. No especially good
7127 // reason, but this is what gcc does, and we do have to pick
7128 // to get a consistent AST.
7129 QualType incompatTy;
7130 incompatTy = S.Context.getPointerType(
7131 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7132 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7133 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7134
7135 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7136 // for casts between types with incompatible address space qualifiers.
7137 // For the following code the compiler produces casts between global and
7138 // local address spaces of the corresponded innermost pointees:
7139 // local int *global *a;
7140 // global int *global *b;
7141 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7142 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7143 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7144 << RHS.get()->getSourceRange();
7145
7146 return incompatTy;
7147 }
7148
7149 // The pointer types are compatible.
7150 // In case of OpenCL ResultTy should have the address space qualifier
7151 // which is a superset of address spaces of both the 2nd and the 3rd
7152 // operands of the conditional operator.
7153 QualType ResultTy = [&, ResultAddrSpace]() {
7154 if (S.getLangOpts().OpenCL) {
7155 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7156 CompositeQuals.setAddressSpace(ResultAddrSpace);
7157 return S.Context
7158 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7159 .withCVRQualifiers(MergedCVRQual);
7160 }
7161 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7162 }();
7163 if (IsBlockPointer)
7164 ResultTy = S.Context.getBlockPointerType(ResultTy);
7165 else
7166 ResultTy = S.Context.getPointerType(ResultTy);
7167
7168 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7169 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7170 return ResultTy;
7171 }
7172
7173 /// Return the resulting type when the operands are both block pointers.
7174 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7175 ExprResult &LHS,
7176 ExprResult &RHS,
7177 SourceLocation Loc) {
7178 QualType LHSTy = LHS.get()->getType();
7179 QualType RHSTy = RHS.get()->getType();
7180
7181 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7182 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7183 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7184 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7185 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7186 return destType;
7187 }
7188 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7189 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7190 << RHS.get()->getSourceRange();
7191 return QualType();
7192 }
7193
7194 // We have 2 block pointer types.
7195 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7196 }
7197
7198 /// Return the resulting type when the operands are both pointers.
7199 static QualType
7200 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7201 ExprResult &RHS,
7202 SourceLocation Loc) {
7203 // get the pointer types
7204 QualType LHSTy = LHS.get()->getType();
7205 QualType RHSTy = RHS.get()->getType();
7206
7207 // get the "pointed to" types
7208 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7209 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7210
7211 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7212 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7213 // Figure out necessary qualifiers (C99 6.5.15p6)
7214 QualType destPointee
7215 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7216 QualType destType = S.Context.getPointerType(destPointee);
7217 // Add qualifiers if necessary.
7218 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7219 // Promote to void*.
7220 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7221 return destType;
7222 }
7223 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7224 QualType destPointee
7225 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7226 QualType destType = S.Context.getPointerType(destPointee);
7227 // Add qualifiers if necessary.
7228 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7229 // Promote to void*.
7230 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7231 return destType;
7232 }
7233
7234 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7235 }
7236
7237 /// Return false if the first expression is not an integer and the second
7238 /// expression is not a pointer, true otherwise.
7239 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7240 Expr* PointerExpr, SourceLocation Loc,
7241 bool IsIntFirstExpr) {
7242 if (!PointerExpr->getType()->isPointerType() ||
7243 !Int.get()->getType()->isIntegerType())
7244 return false;
7245
7246 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7247 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7248
7249 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7250 << Expr1->getType() << Expr2->getType()
7251 << Expr1->getSourceRange() << Expr2->getSourceRange();
7252 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7253 CK_IntegralToPointer);
7254 return true;
7255 }
7256
7257 /// Simple conversion between integer and floating point types.
7258 ///
7259 /// Used when handling the OpenCL conditional operator where the
7260 /// condition is a vector while the other operands are scalar.
7261 ///
7262 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7263 /// types are either integer or floating type. Between the two
7264 /// operands, the type with the higher rank is defined as the "result
7265 /// type". The other operand needs to be promoted to the same type. No
7266 /// other type promotion is allowed. We cannot use
7267 /// UsualArithmeticConversions() for this purpose, since it always
7268 /// promotes promotable types.
7269 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7270 ExprResult &RHS,
7271 SourceLocation QuestionLoc) {
7272 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7273 if (LHS.isInvalid())
7274 return QualType();
7275 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7276 if (RHS.isInvalid())
7277 return QualType();
7278
7279 // For conversion purposes, we ignore any qualifiers.
7280 // For example, "const float" and "float" are equivalent.
7281 QualType LHSType =
7282 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7283 QualType RHSType =
7284 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7285
7286 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7287 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7288 << LHSType << LHS.get()->getSourceRange();
7289 return QualType();
7290 }
7291
7292 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7293 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7294 << RHSType << RHS.get()->getSourceRange();
7295 return QualType();
7296 }
7297
7298 // If both types are identical, no conversion is needed.
7299 if (LHSType == RHSType)
7300 return LHSType;
7301
7302 // Now handle "real" floating types (i.e. float, double, long double).
7303 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7304 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7305 /*IsCompAssign = */ false);
7306
7307 // Finally, we have two differing integer types.
7308 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7309 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7310 }
7311
7312 /// Convert scalar operands to a vector that matches the
7313 /// condition in length.
7314 ///
7315 /// Used when handling the OpenCL conditional operator where the
7316 /// condition is a vector while the other operands are scalar.
7317 ///
7318 /// We first compute the "result type" for the scalar operands
7319 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7320 /// into a vector of that type where the length matches the condition
7321 /// vector type. s6.11.6 requires that the element types of the result
7322 /// and the condition must have the same number of bits.
7323 static QualType
7324 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7325 QualType CondTy, SourceLocation QuestionLoc) {
7326 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7327 if (ResTy.isNull()) return QualType();
7328
7329 const VectorType *CV = CondTy->getAs<VectorType>();
7330 assert(CV);
7331
7332 // Determine the vector result type
7333 unsigned NumElements = CV->getNumElements();
7334 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7335
7336 // Ensure that all types have the same number of bits
7337 if (S.Context.getTypeSize(CV->getElementType())
7338 != S.Context.getTypeSize(ResTy)) {
7339 // Since VectorTy is created internally, it does not pretty print
7340 // with an OpenCL name. Instead, we just print a description.
7341 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7342 SmallString<64> Str;
7343 llvm::raw_svector_ostream OS(Str);
7344 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7345 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7346 << CondTy << OS.str();
7347 return QualType();
7348 }
7349
7350 // Convert operands to the vector result type
7351 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7352 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7353
7354 return VectorTy;
7355 }
7356
7357 /// Return false if this is a valid OpenCL condition vector
7358 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7359 SourceLocation QuestionLoc) {
7360 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7361 // integral type.
7362 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7363 assert(CondTy);
7364 QualType EleTy = CondTy->getElementType();
7365 if (EleTy->isIntegerType()) return false;
7366
7367 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7368 << Cond->getType() << Cond->getSourceRange();
7369 return true;
7370 }
7371
7372 /// Return false if the vector condition type and the vector
7373 /// result type are compatible.
7374 ///
7375 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7376 /// number of elements, and their element types have the same number
7377 /// of bits.
7378 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7379 SourceLocation QuestionLoc) {
7380 const VectorType *CV = CondTy->getAs<VectorType>();
7381 const VectorType *RV = VecResTy->getAs<VectorType>();
7382 assert(CV && RV);
7383
7384 if (CV->getNumElements() != RV->getNumElements()) {
7385 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7386 << CondTy << VecResTy;
7387 return true;
7388 }
7389
7390 QualType CVE = CV->getElementType();
7391 QualType RVE = RV->getElementType();
7392
7393 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7394 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7395 << CondTy << VecResTy;
7396 return true;
7397 }
7398
7399 return false;
7400 }
7401
7402 /// Return the resulting type for the conditional operator in
7403 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
7404 /// s6.3.i) when the condition is a vector type.
7405 static QualType
7406 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7407 ExprResult &LHS, ExprResult &RHS,
7408 SourceLocation QuestionLoc) {
7409 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7410 if (Cond.isInvalid())
7411 return QualType();
7412 QualType CondTy = Cond.get()->getType();
7413
7414 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7415 return QualType();
7416
7417 // If either operand is a vector then find the vector type of the
7418 // result as specified in OpenCL v1.1 s6.3.i.
7419 if (LHS.get()->getType()->isVectorType() ||
7420 RHS.get()->getType()->isVectorType()) {
7421 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7422 /*isCompAssign*/false,
7423 /*AllowBothBool*/true,
7424 /*AllowBoolConversions*/false);
7425 if (VecResTy.isNull()) return QualType();
7426 // The result type must match the condition type as specified in
7427 // OpenCL v1.1 s6.11.6.
7428 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7429 return QualType();
7430 return VecResTy;
7431 }
7432
7433 // Both operands are scalar.
7434 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7435 }
7436
7437 /// Return true if the Expr is block type
7438 static bool checkBlockType(Sema &S, const Expr *E) {
7439 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7440 QualType Ty = CE->getCallee()->getType();
7441 if (Ty->isBlockPointerType()) {
7442 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7443 return true;
7444 }
7445 }
7446 return false;
7447 }
7448
7449 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7450 /// In that case, LHS = cond.
7451 /// C99 6.5.15
7452 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7453 ExprResult &RHS, ExprValueKind &VK,
7454 ExprObjectKind &OK,
7455 SourceLocation QuestionLoc) {
7456
7457 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7458 if (!LHSResult.isUsable()) return QualType();
7459 LHS = LHSResult;
7460
7461 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7462 if (!RHSResult.isUsable()) return QualType();
7463 RHS = RHSResult;
7464
7465 // C++ is sufficiently different to merit its own checker.
7466 if (getLangOpts().CPlusPlus)
7467 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7468
7469 VK = VK_RValue;
7470 OK = OK_Ordinary;
7471
7472 // The OpenCL operator with a vector condition is sufficiently
7473 // different to merit its own checker.
7474 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7475 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7476
7477 // First, check the condition.
7478 Cond = UsualUnaryConversions(Cond.get());
7479 if (Cond.isInvalid())
7480 return QualType();
7481 if (checkCondition(*this, Cond.get(), QuestionLoc))
7482 return QualType();
7483
7484 // Now check the two expressions.
7485 if (LHS.get()->getType()->isVectorType() ||
7486 RHS.get()->getType()->isVectorType())
7487 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7488 /*AllowBothBool*/true,
7489 /*AllowBoolConversions*/false);
7490
7491 QualType ResTy =
7492 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7493 if (LHS.isInvalid() || RHS.isInvalid())
7494 return QualType();
7495
7496 QualType LHSTy = LHS.get()->getType();
7497 QualType RHSTy = RHS.get()->getType();
7498
7499 // Diagnose attempts to convert between __float128 and long double where
7500 // such conversions currently can't be handled.
7501 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7502 Diag(QuestionLoc,
7503 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7504 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7505 return QualType();
7506 }
7507
7508 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7509 // selection operator (?:).
7510 if (getLangOpts().OpenCL &&
7511 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7512 return QualType();
7513 }
7514
7515 // If both operands have arithmetic type, do the usual arithmetic conversions
7516 // to find a common type: C99 6.5.15p3,5.
7517 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7518 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7519 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7520
7521 return ResTy;
7522 }
7523
7524 // If both operands are the same structure or union type, the result is that
7525 // type.
7526 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7527 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7528 if (LHSRT->getDecl() == RHSRT->getDecl())
7529 // "If both the operands have structure or union type, the result has
7530 // that type." This implies that CV qualifiers are dropped.
7531 return LHSTy.getUnqualifiedType();
7532 // FIXME: Type of conditional expression must be complete in C mode.
7533 }
7534
7535 // C99 6.5.15p5: "If both operands have void type, the result has void type."
7536 // The following || allows only one side to be void (a GCC-ism).
7537 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7538 return checkConditionalVoidType(*this, LHS, RHS);
7539 }
7540
7541 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7542 // the type of the other operand."
7543 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7544 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7545
7546 // All objective-c pointer type analysis is done here.
7547 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7548 QuestionLoc);
7549 if (LHS.isInvalid() || RHS.isInvalid())
7550 return QualType();
7551 if (!compositeType.isNull())
7552 return compositeType;
7553
7554
7555 // Handle block pointer types.
7556 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7557 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7558 QuestionLoc);
7559
7560 // Check constraints for C object pointers types (C99 6.5.15p3,6).
7561 if (LHSTy->isPointerType() && RHSTy->isPointerType())
7562 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7563 QuestionLoc);
7564
7565 // GCC compatibility: soften pointer/integer mismatch. Note that
7566 // null pointers have been filtered out by this point.
7567 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7568 /*IsIntFirstExpr=*/true))
7569 return RHSTy;
7570 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7571 /*IsIntFirstExpr=*/false))
7572 return LHSTy;
7573
7574 // Emit a better diagnostic if one of the expressions is a null pointer
7575 // constant and the other is not a pointer type. In this case, the user most
7576 // likely forgot to take the address of the other expression.
7577 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7578 return QualType();
7579
7580 // Otherwise, the operands are not compatible.
7581 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7582 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7583 << RHS.get()->getSourceRange();
7584 return QualType();
7585 }
7586
7587 /// FindCompositeObjCPointerType - Helper method to find composite type of
7588 /// two objective-c pointer types of the two input expressions.
7589 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7590 SourceLocation QuestionLoc) {
7591 QualType LHSTy = LHS.get()->getType();
7592 QualType RHSTy = RHS.get()->getType();
7593
7594 // Handle things like Class and struct objc_class*. Here we case the result
7595 // to the pseudo-builtin, because that will be implicitly cast back to the
7596 // redefinition type if an attempt is made to access its fields.
7597 if (LHSTy->isObjCClassType() &&
7598 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7599 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7600 return LHSTy;
7601 }
7602 if (RHSTy->isObjCClassType() &&
7603 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7604 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7605 return RHSTy;
7606 }
7607 // And the same for struct objc_object* / id
7608 if (LHSTy->isObjCIdType() &&
7609 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7610 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7611 return LHSTy;
7612 }
7613 if (RHSTy->isObjCIdType() &&
7614 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7615 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7616 return RHSTy;
7617 }
7618 // And the same for struct objc_selector* / SEL
7619 if (Context.isObjCSelType(LHSTy) &&
7620 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7621 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7622 return LHSTy;
7623 }
7624 if (Context.isObjCSelType(RHSTy) &&
7625 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7626 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7627 return RHSTy;
7628 }
7629 // Check constraints for Objective-C object pointers types.
7630 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7631
7632 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7633 // Two identical object pointer types are always compatible.
7634 return LHSTy;
7635 }
7636 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7637 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7638 QualType compositeType = LHSTy;
7639
7640 // If both operands are interfaces and either operand can be
7641 // assigned to the other, use that type as the composite
7642 // type. This allows
7643 // xxx ? (A*) a : (B*) b
7644 // where B is a subclass of A.
7645 //
7646 // Additionally, as for assignment, if either type is 'id'
7647 // allow silent coercion. Finally, if the types are
7648 // incompatible then make sure to use 'id' as the composite
7649 // type so the result is acceptable for sending messages to.
7650
7651 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7652 // It could return the composite type.
7653 if (!(compositeType =
7654 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7655 // Nothing more to do.
7656 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7657 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7658 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7659 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7660 } else if ((LHSOPT->isObjCQualifiedIdType() ||
7661 RHSOPT->isObjCQualifiedIdType()) &&
7662 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7663 true)) {
7664 // Need to handle "id<xx>" explicitly.
7665 // GCC allows qualified id and any Objective-C type to devolve to
7666 // id. Currently localizing to here until clear this should be
7667 // part of ObjCQualifiedIdTypesAreCompatible.
7668 compositeType = Context.getObjCIdType();
7669 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7670 compositeType = Context.getObjCIdType();
7671 } else {
7672 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7673 << LHSTy << RHSTy
7674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7675 QualType incompatTy = Context.getObjCIdType();
7676 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7677 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7678 return incompatTy;
7679 }
7680 // The object pointer types are compatible.
7681 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7682 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7683 return compositeType;
7684 }
7685 // Check Objective-C object pointer types and 'void *'
7686 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7687 if (getLangOpts().ObjCAutoRefCount) {
7688 // ARC forbids the implicit conversion of object pointers to 'void *',
7689 // so these types are not compatible.
7690 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7691 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7692 LHS = RHS = true;
7693 return QualType();
7694 }
7695 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7696 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7697 QualType destPointee
7698 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7699 QualType destType = Context.getPointerType(destPointee);
7700 // Add qualifiers if necessary.
7701 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7702 // Promote to void*.
7703 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7704 return destType;
7705 }
7706 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7707 if (getLangOpts().ObjCAutoRefCount) {
7708 // ARC forbids the implicit conversion of object pointers to 'void *',
7709 // so these types are not compatible.
7710 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7711 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7712 LHS = RHS = true;
7713 return QualType();
7714 }
7715 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7716 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7717 QualType destPointee
7718 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7719 QualType destType = Context.getPointerType(destPointee);
7720 // Add qualifiers if necessary.
7721 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7722 // Promote to void*.
7723 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7724 return destType;
7725 }
7726 return QualType();
7727 }
7728
7729 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7730 /// ParenRange in parentheses.
7731 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7732 const PartialDiagnostic &Note,
7733 SourceRange ParenRange) {
7734 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7735 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7736 EndLoc.isValid()) {
7737 Self.Diag(Loc, Note)
7738 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7739 << FixItHint::CreateInsertion(EndLoc, ")");
7740 } else {
7741 // We can't display the parentheses, so just show the bare note.
7742 Self.Diag(Loc, Note) << ParenRange;
7743 }
7744 }
7745
7746 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7747 return BinaryOperator::isAdditiveOp(Opc) ||
7748 BinaryOperator::isMultiplicativeOp(Opc) ||
7749 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7750 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7751 // not any of the logical operators. Bitwise-xor is commonly used as a
7752 // logical-xor because there is no logical-xor operator. The logical
7753 // operators, including uses of xor, have a high false positive rate for
7754 // precedence warnings.
7755 }
7756
7757 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7758 /// expression, either using a built-in or overloaded operator,
7759 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7760 /// expression.
7761 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7762 Expr **RHSExprs) {
7763 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7764 E = E->IgnoreImpCasts();
7765 E = E->IgnoreConversionOperator();
7766 E = E->IgnoreImpCasts();
7767 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7768 E = MTE->getSubExpr();
7769 E = E->IgnoreImpCasts();
7770 }
7771
7772 // Built-in binary operator.
7773 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7774 if (IsArithmeticOp(OP->getOpcode())) {
7775 *Opcode = OP->getOpcode();
7776 *RHSExprs = OP->getRHS();
7777 return true;
7778 }
7779 }
7780
7781 // Overloaded operator.
7782 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7783 if (Call->getNumArgs() != 2)
7784 return false;
7785
7786 // Make sure this is really a binary operator that is safe to pass into
7787 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7788 OverloadedOperatorKind OO = Call->getOperator();
7789 if (OO < OO_Plus || OO > OO_Arrow ||
7790 OO == OO_PlusPlus || OO == OO_MinusMinus)
7791 return false;
7792
7793 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7794 if (IsArithmeticOp(OpKind)) {
7795 *Opcode = OpKind;
7796 *RHSExprs = Call->getArg(1);
7797 return true;
7798 }
7799 }
7800
7801 return false;
7802 }
7803
7804 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7805 /// or is a logical expression such as (x==y) which has int type, but is
7806 /// commonly interpreted as boolean.
7807 static bool ExprLooksBoolean(Expr *E) {
7808 E = E->IgnoreParenImpCasts();
7809
7810 if (E->getType()->isBooleanType())
7811 return true;
7812 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7813 return OP->isComparisonOp() || OP->isLogicalOp();
7814 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7815 return OP->getOpcode() == UO_LNot;
7816 if (E->getType()->isPointerType())
7817 return true;
7818 // FIXME: What about overloaded operator calls returning "unspecified boolean
7819 // type"s (commonly pointer-to-members)?
7820
7821 return false;
7822 }
7823
7824 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7825 /// and binary operator are mixed in a way that suggests the programmer assumed
7826 /// the conditional operator has higher precedence, for example:
7827 /// "int x = a + someBinaryCondition ? 1 : 2".
7828 static void DiagnoseConditionalPrecedence(Sema &Self,
7829 SourceLocation OpLoc,
7830 Expr *Condition,
7831 Expr *LHSExpr,
7832 Expr *RHSExpr) {
7833 BinaryOperatorKind CondOpcode;
7834 Expr *CondRHS;
7835
7836 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7837 return;
7838 if (!ExprLooksBoolean(CondRHS))
7839 return;
7840
7841 // The condition is an arithmetic binary expression, with a right-
7842 // hand side that looks boolean, so warn.
7843
7844 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7845 ? diag::warn_precedence_bitwise_conditional
7846 : diag::warn_precedence_conditional;
7847
7848 Self.Diag(OpLoc, DiagID)
7849 << Condition->getSourceRange()
7850 << BinaryOperator::getOpcodeStr(CondOpcode);
7851
7852 SuggestParentheses(
7853 Self, OpLoc,
7854 Self.PDiag(diag::note_precedence_silence)
7855 << BinaryOperator::getOpcodeStr(CondOpcode),
7856 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7857
7858 SuggestParentheses(Self, OpLoc,
7859 Self.PDiag(diag::note_precedence_conditional_first),
7860 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7861 }
7862
7863 /// Compute the nullability of a conditional expression.
7864 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7865 QualType LHSTy, QualType RHSTy,
7866 ASTContext &Ctx) {
7867 if (!ResTy->isAnyPointerType())
7868 return ResTy;
7869
7870 auto GetNullability = [&Ctx](QualType Ty) {
7871 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7872 if (Kind)
7873 return *Kind;
7874 return NullabilityKind::Unspecified;
7875 };
7876
7877 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7878 NullabilityKind MergedKind;
7879
7880 // Compute nullability of a binary conditional expression.
7881 if (IsBin) {
7882 if (LHSKind == NullabilityKind::NonNull)
7883 MergedKind = NullabilityKind::NonNull;
7884 else
7885 MergedKind = RHSKind;
7886 // Compute nullability of a normal conditional expression.
7887 } else {
7888 if (LHSKind == NullabilityKind::Nullable ||
7889 RHSKind == NullabilityKind::Nullable)
7890 MergedKind = NullabilityKind::Nullable;
7891 else if (LHSKind == NullabilityKind::NonNull)
7892 MergedKind = RHSKind;
7893 else if (RHSKind == NullabilityKind::NonNull)
7894 MergedKind = LHSKind;
7895 else
7896 MergedKind = NullabilityKind::Unspecified;
7897 }
7898
7899 // Return if ResTy already has the correct nullability.
7900 if (GetNullability(ResTy) == MergedKind)
7901 return ResTy;
7902
7903 // Strip all nullability from ResTy.
7904 while (ResTy->getNullability(Ctx))
7905 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7906
7907 // Create a new AttributedType with the new nullability kind.
7908 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7909 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7910 }
7911
7912 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7913 /// in the case of a the GNU conditional expr extension.
7914 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7915 SourceLocation ColonLoc,
7916 Expr *CondExpr, Expr *LHSExpr,
7917 Expr *RHSExpr) {
7918 if (!getLangOpts().CPlusPlus) {
7919 // C cannot handle TypoExpr nodes in the condition because it
7920 // doesn't handle dependent types properly, so make sure any TypoExprs have
7921 // been dealt with before checking the operands.
7922 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7923 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7924 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7925
7926 if (!CondResult.isUsable())
7927 return ExprError();
7928
7929 if (LHSExpr) {
7930 if (!LHSResult.isUsable())
7931 return ExprError();
7932 }
7933
7934 if (!RHSResult.isUsable())
7935 return ExprError();
7936
7937 CondExpr = CondResult.get();
7938 LHSExpr = LHSResult.get();
7939 RHSExpr = RHSResult.get();
7940 }
7941
7942 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7943 // was the condition.
7944 OpaqueValueExpr *opaqueValue = nullptr;
7945 Expr *commonExpr = nullptr;
7946 if (!LHSExpr) {
7947 commonExpr = CondExpr;
7948 // Lower out placeholder types first. This is important so that we don't
7949 // try to capture a placeholder. This happens in few cases in C++; such
7950 // as Objective-C++'s dictionary subscripting syntax.
7951 if (commonExpr->hasPlaceholderType()) {
7952 ExprResult result = CheckPlaceholderExpr(commonExpr);
7953 if (!result.isUsable()) return ExprError();
7954 commonExpr = result.get();
7955 }
7956 // We usually want to apply unary conversions *before* saving, except
7957 // in the special case of a C++ l-value conditional.
7958 if (!(getLangOpts().CPlusPlus
7959 && !commonExpr->isTypeDependent()
7960 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7961 && commonExpr->isGLValue()
7962 && commonExpr->isOrdinaryOrBitFieldObject()
7963 && RHSExpr->isOrdinaryOrBitFieldObject()
7964 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7965 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7966 if (commonRes.isInvalid())
7967 return ExprError();
7968 commonExpr = commonRes.get();
7969 }
7970
7971 // If the common expression is a class or array prvalue, materialize it
7972 // so that we can safely refer to it multiple times.
7973 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7974 commonExpr->getType()->isArrayType())) {
7975 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7976 if (MatExpr.isInvalid())
7977 return ExprError();
7978 commonExpr = MatExpr.get();
7979 }
7980
7981 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7982 commonExpr->getType(),
7983 commonExpr->getValueKind(),
7984 commonExpr->getObjectKind(),
7985 commonExpr);
7986 LHSExpr = CondExpr = opaqueValue;
7987 }
7988
7989 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7990 ExprValueKind VK = VK_RValue;
7991 ExprObjectKind OK = OK_Ordinary;
7992 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7993 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7994 VK, OK, QuestionLoc);
7995 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7996 RHS.isInvalid())
7997 return ExprError();
7998
7999 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8000 RHS.get());
8001
8002 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8003
8004 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8005 Context);
8006
8007 if (!commonExpr)
8008 return new (Context)
8009 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8010 RHS.get(), result, VK, OK);
8011
8012 return new (Context) BinaryConditionalOperator(
8013 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8014 ColonLoc, result, VK, OK);
8015 }
8016
8017 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8018 // being closely modeled after the C99 spec:-). The odd characteristic of this
8019 // routine is it effectively iqnores the qualifiers on the top level pointee.
8020 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8021 // FIXME: add a couple examples in this comment.
8022 static Sema::AssignConvertType
8023 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8024 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8025 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8026
8027 // get the "pointed to" type (ignoring qualifiers at the top level)
8028 const Type *lhptee, *rhptee;
8029 Qualifiers lhq, rhq;
8030 std::tie(lhptee, lhq) =
8031 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8032 std::tie(rhptee, rhq) =
8033 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8034
8035 Sema::AssignConvertType ConvTy = Sema::Compatible;
8036
8037 // C99 6.5.16.1p1: This following citation is common to constraints
8038 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8039 // qualifiers of the type *pointed to* by the right;
8040
8041 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8042 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8043 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8044 // Ignore lifetime for further calculation.
8045 lhq.removeObjCLifetime();
8046 rhq.removeObjCLifetime();
8047 }
8048
8049 if (!lhq.compatiblyIncludes(rhq)) {
8050 // Treat address-space mismatches as fatal.
8051 if (!lhq.isAddressSpaceSupersetOf(rhq))
8052 return Sema::IncompatiblePointerDiscardsQualifiers;
8053
8054 // It's okay to add or remove GC or lifetime qualifiers when converting to
8055 // and from void*.
8056 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8057 .compatiblyIncludes(
8058 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8059 && (lhptee->isVoidType() || rhptee->isVoidType()))
8060 ; // keep old
8061
8062 // Treat lifetime mismatches as fatal.
8063 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8064 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8065
8066 // For GCC/MS compatibility, other qualifier mismatches are treated
8067 // as still compatible in C.
8068 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8069 }
8070
8071 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8072 // incomplete type and the other is a pointer to a qualified or unqualified
8073 // version of void...
8074 if (lhptee->isVoidType()) {
8075 if (rhptee->isIncompleteOrObjectType())
8076 return ConvTy;
8077
8078 // As an extension, we allow cast to/from void* to function pointer.
8079 assert(rhptee->isFunctionType());
8080 return Sema::FunctionVoidPointer;
8081 }
8082
8083 if (rhptee->isVoidType()) {
8084 if (lhptee->isIncompleteOrObjectType())
8085 return ConvTy;
8086
8087 // As an extension, we allow cast to/from void* to function pointer.
8088 assert(lhptee->isFunctionType());
8089 return Sema::FunctionVoidPointer;
8090 }
8091
8092 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8093 // unqualified versions of compatible types, ...
8094 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8095 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8096 // Check if the pointee types are compatible ignoring the sign.
8097 // We explicitly check for char so that we catch "char" vs
8098 // "unsigned char" on systems where "char" is unsigned.
8099 if (lhptee->isCharType())
8100 ltrans = S.Context.UnsignedCharTy;
8101 else if (lhptee->hasSignedIntegerRepresentation())
8102 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8103
8104 if (rhptee->isCharType())
8105 rtrans = S.Context.UnsignedCharTy;
8106 else if (rhptee->hasSignedIntegerRepresentation())
8107 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8108
8109 if (ltrans == rtrans) {
8110 // Types are compatible ignoring the sign. Qualifier incompatibility
8111 // takes priority over sign incompatibility because the sign
8112 // warning can be disabled.
8113 if (ConvTy != Sema::Compatible)
8114 return ConvTy;
8115
8116 return Sema::IncompatiblePointerSign;
8117 }
8118
8119 // If we are a multi-level pointer, it's possible that our issue is simply
8120 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8121 // the eventual target type is the same and the pointers have the same
8122 // level of indirection, this must be the issue.
8123 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8124 do {
8125 std::tie(lhptee, lhq) =
8126 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8127 std::tie(rhptee, rhq) =
8128 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8129
8130 // Inconsistent address spaces at this point is invalid, even if the
8131 // address spaces would be compatible.
8132 // FIXME: This doesn't catch address space mismatches for pointers of
8133 // different nesting levels, like:
8134 // __local int *** a;
8135 // int ** b = a;
8136 // It's not clear how to actually determine when such pointers are
8137 // invalidly incompatible.
8138 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8139 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8140
8141 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8142
8143 if (lhptee == rhptee)
8144 return Sema::IncompatibleNestedPointerQualifiers;
8145 }
8146
8147 // General pointer incompatibility takes priority over qualifiers.
8148 return Sema::IncompatiblePointer;
8149 }
8150 if (!S.getLangOpts().CPlusPlus &&
8151 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8152 return Sema::IncompatiblePointer;
8153 return ConvTy;
8154 }
8155
8156 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8157 /// block pointer types are compatible or whether a block and normal pointer
8158 /// are compatible. It is more restrict than comparing two function pointer
8159 // types.
8160 static Sema::AssignConvertType
8161 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8162 QualType RHSType) {
8163 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8164 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8165
8166 QualType lhptee, rhptee;
8167
8168 // get the "pointed to" type (ignoring qualifiers at the top level)
8169 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8170 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8171
8172 // In C++, the types have to match exactly.
8173 if (S.getLangOpts().CPlusPlus)
8174 return Sema::IncompatibleBlockPointer;
8175
8176 Sema::AssignConvertType ConvTy = Sema::Compatible;
8177
8178 // For blocks we enforce that qualifiers are identical.
8179 Qualifiers LQuals = lhptee.getLocalQualifiers();
8180 Qualifiers RQuals = rhptee.getLocalQualifiers();
8181 if (S.getLangOpts().OpenCL) {
8182 LQuals.removeAddressSpace();
8183 RQuals.removeAddressSpace();
8184 }
8185 if (LQuals != RQuals)
8186 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8187
8188 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8189 // assignment.
8190 // The current behavior is similar to C++ lambdas. A block might be
8191 // assigned to a variable iff its return type and parameters are compatible
8192 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8193 // an assignment. Presumably it should behave in way that a function pointer
8194 // assignment does in C, so for each parameter and return type:
8195 // * CVR and address space of LHS should be a superset of CVR and address
8196 // space of RHS.
8197 // * unqualified types should be compatible.
8198 if (S.getLangOpts().OpenCL) {
8199 if (!S.Context.typesAreBlockPointerCompatible(
8200 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8201 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8202 return Sema::IncompatibleBlockPointer;
8203 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8204 return Sema::IncompatibleBlockPointer;
8205
8206 return ConvTy;
8207 }
8208
8209 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8210 /// for assignment compatibility.
8211 static Sema::AssignConvertType
8212 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8213 QualType RHSType) {
8214 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8215 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8216
8217 if (LHSType->isObjCBuiltinType()) {
8218 // Class is not compatible with ObjC object pointers.
8219 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8220 !RHSType->isObjCQualifiedClassType())
8221 return Sema::IncompatiblePointer;
8222 return Sema::Compatible;
8223 }
8224 if (RHSType->isObjCBuiltinType()) {
8225 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8226 !LHSType->isObjCQualifiedClassType())
8227 return Sema::IncompatiblePointer;
8228 return Sema::Compatible;
8229 }
8230 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8231 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8232
8233 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8234 // make an exception for id<P>
8235 !LHSType->isObjCQualifiedIdType())
8236 return Sema::CompatiblePointerDiscardsQualifiers;
8237
8238 if (S.Context.typesAreCompatible(LHSType, RHSType))
8239 return Sema::Compatible;
8240 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8241 return Sema::IncompatibleObjCQualifiedId;
8242 return Sema::IncompatiblePointer;
8243 }
8244
8245 Sema::AssignConvertType
8246 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8247 QualType LHSType, QualType RHSType) {
8248 // Fake up an opaque expression. We don't actually care about what
8249 // cast operations are required, so if CheckAssignmentConstraints
8250 // adds casts to this they'll be wasted, but fortunately that doesn't
8251 // usually happen on valid code.
8252 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8253 ExprResult RHSPtr = &RHSExpr;
8254 CastKind K;
8255
8256 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8257 }
8258
8259 /// This helper function returns true if QT is a vector type that has element
8260 /// type ElementType.
8261 static bool isVector(QualType QT, QualType ElementType) {
8262 if (const VectorType *VT = QT->getAs<VectorType>())
8263 return VT->getElementType() == ElementType;
8264 return false;
8265 }
8266
8267 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8268 /// has code to accommodate several GCC extensions when type checking
8269 /// pointers. Here are some objectionable examples that GCC considers warnings:
8270 ///
8271 /// int a, *pint;
8272 /// short *pshort;
8273 /// struct foo *pfoo;
8274 ///
8275 /// pint = pshort; // warning: assignment from incompatible pointer type
8276 /// a = pint; // warning: assignment makes integer from pointer without a cast
8277 /// pint = a; // warning: assignment makes pointer from integer without a cast
8278 /// pint = pfoo; // warning: assignment from incompatible pointer type
8279 ///
8280 /// As a result, the code for dealing with pointers is more complex than the
8281 /// C99 spec dictates.
8282 ///
8283 /// Sets 'Kind' for any result kind except Incompatible.
8284 Sema::AssignConvertType
8285 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8286 CastKind &Kind, bool ConvertRHS) {
8287 QualType RHSType = RHS.get()->getType();
8288 QualType OrigLHSType = LHSType;
8289
8290 // Get canonical types. We're not formatting these types, just comparing
8291 // them.
8292 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8293 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8294
8295 // Common case: no conversion required.
8296 if (LHSType == RHSType) {
8297 Kind = CK_NoOp;
8298 return Compatible;
8299 }
8300
8301 // If we have an atomic type, try a non-atomic assignment, then just add an
8302 // atomic qualification step.
8303 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8304 Sema::AssignConvertType result =
8305 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8306 if (result != Compatible)
8307 return result;
8308 if (Kind != CK_NoOp && ConvertRHS)
8309 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8310 Kind = CK_NonAtomicToAtomic;
8311 return Compatible;
8312 }
8313
8314 // If the left-hand side is a reference type, then we are in a
8315 // (rare!) case where we've allowed the use of references in C,
8316 // e.g., as a parameter type in a built-in function. In this case,
8317 // just make sure that the type referenced is compatible with the
8318 // right-hand side type. The caller is responsible for adjusting
8319 // LHSType so that the resulting expression does not have reference
8320 // type.
8321 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8322 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8323 Kind = CK_LValueBitCast;
8324 return Compatible;
8325 }
8326 return Incompatible;
8327 }
8328
8329 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8330 // to the same ExtVector type.
8331 if (LHSType->isExtVectorType()) {
8332 if (RHSType->isExtVectorType())
8333 return Incompatible;
8334 if (RHSType->isArithmeticType()) {
8335 // CK_VectorSplat does T -> vector T, so first cast to the element type.
8336 if (ConvertRHS)
8337 RHS = prepareVectorSplat(LHSType, RHS.get());
8338 Kind = CK_VectorSplat;
8339 return Compatible;
8340 }
8341 }
8342
8343 // Conversions to or from vector type.
8344 if (LHSType->isVectorType() || RHSType->isVectorType()) {
8345 if (LHSType->isVectorType() && RHSType->isVectorType()) {
8346 // Allow assignments of an AltiVec vector type to an equivalent GCC
8347 // vector type and vice versa
8348 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8349 Kind = CK_BitCast;
8350 return Compatible;
8351 }
8352
8353 // If we are allowing lax vector conversions, and LHS and RHS are both
8354 // vectors, the total size only needs to be the same. This is a bitcast;
8355 // no bits are changed but the result type is different.
8356 if (isLaxVectorConversion(RHSType, LHSType)) {
8357 Kind = CK_BitCast;
8358 return IncompatibleVectors;
8359 }
8360 }
8361
8362 // When the RHS comes from another lax conversion (e.g. binops between
8363 // scalars and vectors) the result is canonicalized as a vector. When the
8364 // LHS is also a vector, the lax is allowed by the condition above. Handle
8365 // the case where LHS is a scalar.
8366 if (LHSType->isScalarType()) {
8367 const VectorType *VecType = RHSType->getAs<VectorType>();
8368 if (VecType && VecType->getNumElements() == 1 &&
8369 isLaxVectorConversion(RHSType, LHSType)) {
8370 ExprResult *VecExpr = &RHS;
8371 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8372 Kind = CK_BitCast;
8373 return Compatible;
8374 }
8375 }
8376
8377 return Incompatible;
8378 }
8379
8380 // Diagnose attempts to convert between __float128 and long double where
8381 // such conversions currently can't be handled.
8382 if (unsupportedTypeConversion(*this, LHSType, RHSType))
8383 return Incompatible;
8384
8385 // Disallow assigning a _Complex to a real type in C++ mode since it simply
8386 // discards the imaginary part.
8387 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8388 !LHSType->getAs<ComplexType>())
8389 return Incompatible;
8390
8391 // Arithmetic conversions.
8392 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8393 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8394 if (ConvertRHS)
8395 Kind = PrepareScalarCast(RHS, LHSType);
8396 return Compatible;
8397 }
8398
8399 // Conversions to normal pointers.
8400 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8401 // U* -> T*
8402 if (isa<PointerType>(RHSType)) {
8403 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8404 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8405 if (AddrSpaceL != AddrSpaceR)
8406 Kind = CK_AddressSpaceConversion;
8407 else if (Context.hasCvrSimilarType(RHSType, LHSType))
8408 Kind = CK_NoOp;
8409 else
8410 Kind = CK_BitCast;
8411 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8412 }
8413
8414 // int -> T*
8415 if (RHSType->isIntegerType()) {
8416 Kind = CK_IntegralToPointer; // FIXME: null?
8417 return IntToPointer;
8418 }
8419
8420 // C pointers are not compatible with ObjC object pointers,
8421 // with two exceptions:
8422 if (isa<ObjCObjectPointerType>(RHSType)) {
8423 // - conversions to void*
8424 if (LHSPointer->getPointeeType()->isVoidType()) {
8425 Kind = CK_BitCast;
8426 return Compatible;
8427 }
8428
8429 // - conversions from 'Class' to the redefinition type
8430 if (RHSType->isObjCClassType() &&
8431 Context.hasSameType(LHSType,
8432 Context.getObjCClassRedefinitionType())) {
8433 Kind = CK_BitCast;
8434 return Compatible;
8435 }
8436
8437 Kind = CK_BitCast;
8438 return IncompatiblePointer;
8439 }
8440
8441 // U^ -> void*
8442 if (RHSType->getAs<BlockPointerType>()) {
8443 if (LHSPointer->getPointeeType()->isVoidType()) {
8444 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8445 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8446 ->getPointeeType()
8447 .getAddressSpace();
8448 Kind =
8449 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8450 return Compatible;
8451 }
8452 }
8453
8454 return Incompatible;
8455 }
8456
8457 // Conversions to block pointers.
8458 if (isa<BlockPointerType>(LHSType)) {
8459 // U^ -> T^
8460 if (RHSType->isBlockPointerType()) {
8461 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8462 ->getPointeeType()
8463 .getAddressSpace();
8464 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8465 ->getPointeeType()
8466 .getAddressSpace();
8467 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8468 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8469 }
8470
8471 // int or null -> T^
8472 if (RHSType->isIntegerType()) {
8473 Kind = CK_IntegralToPointer; // FIXME: null
8474 return IntToBlockPointer;
8475 }
8476
8477 // id -> T^
8478 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8479 Kind = CK_AnyPointerToBlockPointerCast;
8480 return Compatible;
8481 }
8482
8483 // void* -> T^
8484 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8485 if (RHSPT->getPointeeType()->isVoidType()) {
8486 Kind = CK_AnyPointerToBlockPointerCast;
8487 return Compatible;
8488 }
8489
8490 return Incompatible;
8491 }
8492
8493 // Conversions to Objective-C pointers.
8494 if (isa<ObjCObjectPointerType>(LHSType)) {
8495 // A* -> B*
8496 if (RHSType->isObjCObjectPointerType()) {
8497 Kind = CK_BitCast;
8498 Sema::AssignConvertType result =
8499 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8500 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8501 result == Compatible &&
8502 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8503 result = IncompatibleObjCWeakRef;
8504 return result;
8505 }
8506
8507 // int or null -> A*
8508 if (RHSType->isIntegerType()) {
8509 Kind = CK_IntegralToPointer; // FIXME: null
8510 return IntToPointer;
8511 }
8512
8513 // In general, C pointers are not compatible with ObjC object pointers,
8514 // with two exceptions:
8515 if (isa<PointerType>(RHSType)) {
8516 Kind = CK_CPointerToObjCPointerCast;
8517
8518 // - conversions from 'void*'
8519 if (RHSType->isVoidPointerType()) {
8520 return Compatible;
8521 }
8522
8523 // - conversions to 'Class' from its redefinition type
8524 if (LHSType->isObjCClassType() &&
8525 Context.hasSameType(RHSType,
8526 Context.getObjCClassRedefinitionType())) {
8527 return Compatible;
8528 }
8529
8530 return IncompatiblePointer;
8531 }
8532
8533 // Only under strict condition T^ is compatible with an Objective-C pointer.
8534 if (RHSType->isBlockPointerType() &&
8535 LHSType->isBlockCompatibleObjCPointerType(Context)) {
8536 if (ConvertRHS)
8537 maybeExtendBlockObject(RHS);
8538 Kind = CK_BlockPointerToObjCPointerCast;
8539 return Compatible;
8540 }
8541
8542 return Incompatible;
8543 }
8544
8545 // Conversions from pointers that are not covered by the above.
8546 if (isa<PointerType>(RHSType)) {
8547 // T* -> _Bool
8548 if (LHSType == Context.BoolTy) {
8549 Kind = CK_PointerToBoolean;
8550 return Compatible;
8551 }
8552
8553 // T* -> int
8554 if (LHSType->isIntegerType()) {
8555 Kind = CK_PointerToIntegral;
8556 return PointerToInt;
8557 }
8558
8559 return Incompatible;
8560 }
8561
8562 // Conversions from Objective-C pointers that are not covered by the above.
8563 if (isa<ObjCObjectPointerType>(RHSType)) {
8564 // T* -> _Bool
8565 if (LHSType == Context.BoolTy) {
8566 Kind = CK_PointerToBoolean;
8567 return Compatible;
8568 }
8569
8570 // T* -> int
8571 if (LHSType->isIntegerType()) {
8572 Kind = CK_PointerToIntegral;
8573 return PointerToInt;
8574 }
8575
8576 return Incompatible;
8577 }
8578
8579 // struct A -> struct B
8580 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8581 if (Context.typesAreCompatible(LHSType, RHSType)) {
8582 Kind = CK_NoOp;
8583 return Compatible;
8584 }
8585 }
8586
8587 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8588 Kind = CK_IntToOCLSampler;
8589 return Compatible;
8590 }
8591
8592 return Incompatible;
8593 }
8594
8595 /// Constructs a transparent union from an expression that is
8596 /// used to initialize the transparent union.
8597 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8598 ExprResult &EResult, QualType UnionType,
8599 FieldDecl *Field) {
8600 // Build an initializer list that designates the appropriate member
8601 // of the transparent union.
8602 Expr *E = EResult.get();
8603 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8604 E, SourceLocation());
8605 Initializer->setType(UnionType);
8606 Initializer->setInitializedFieldInUnion(Field);
8607
8608 // Build a compound literal constructing a value of the transparent
8609 // union type from this initializer list.
8610 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8611 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8612 VK_RValue, Initializer, false);
8613 }
8614
8615 Sema::AssignConvertType
8616 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8617 ExprResult &RHS) {
8618 QualType RHSType = RHS.get()->getType();
8619
8620 // If the ArgType is a Union type, we want to handle a potential
8621 // transparent_union GCC extension.
8622 const RecordType *UT = ArgType->getAsUnionType();
8623 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8624 return Incompatible;
8625
8626 // The field to initialize within the transparent union.
8627 RecordDecl *UD = UT->getDecl();
8628 FieldDecl *InitField = nullptr;
8629 // It's compatible if the expression matches any of the fields.
8630 for (auto *it : UD->fields()) {
8631 if (it->getType()->isPointerType()) {
8632 // If the transparent union contains a pointer type, we allow:
8633 // 1) void pointer
8634 // 2) null pointer constant
8635 if (RHSType->isPointerType())
8636 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8637 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8638 InitField = it;
8639 break;
8640 }
8641
8642 if (RHS.get()->isNullPointerConstant(Context,
8643 Expr::NPC_ValueDependentIsNull)) {
8644 RHS = ImpCastExprToType(RHS.get(), it->getType(),
8645 CK_NullToPointer);
8646 InitField = it;
8647 break;
8648 }
8649 }
8650
8651 CastKind Kind;
8652 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8653 == Compatible) {
8654 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8655 InitField = it;
8656 break;
8657 }
8658 }
8659
8660 if (!InitField)
8661 return Incompatible;
8662
8663 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8664 return Compatible;
8665 }
8666
8667 Sema::AssignConvertType
8668 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8669 bool Diagnose,
8670 bool DiagnoseCFAudited,
8671 bool ConvertRHS) {
8672 // We need to be able to tell the caller whether we diagnosed a problem, if
8673 // they ask us to issue diagnostics.
8674 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8675
8676 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8677 // we can't avoid *all* modifications at the moment, so we need some somewhere
8678 // to put the updated value.
8679 ExprResult LocalRHS = CallerRHS;
8680 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8681
8682 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8683 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8684 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8685 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8686 Diag(RHS.get()->getExprLoc(),
8687 diag::warn_noderef_to_dereferenceable_pointer)
8688 << RHS.get()->getSourceRange();
8689 }
8690 }
8691 }
8692
8693 if (getLangOpts().CPlusPlus) {
8694 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8695 // C++ 5.17p3: If the left operand is not of class type, the
8696 // expression is implicitly converted (C++ 4) to the
8697 // cv-unqualified type of the left operand.
8698 QualType RHSType = RHS.get()->getType();
8699 if (Diagnose) {
8700 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8701 AA_Assigning);
8702 } else {
8703 ImplicitConversionSequence ICS =
8704 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8705 /*SuppressUserConversions=*/false,
8706 /*AllowExplicit=*/false,
8707 /*InOverloadResolution=*/false,
8708 /*CStyle=*/false,
8709 /*AllowObjCWritebackConversion=*/false);
8710 if (ICS.isFailure())
8711 return Incompatible;
8712 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8713 ICS, AA_Assigning);
8714 }
8715 if (RHS.isInvalid())
8716 return Incompatible;
8717 Sema::AssignConvertType result = Compatible;
8718 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8719 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8720 result = IncompatibleObjCWeakRef;
8721 return result;
8722 }
8723
8724 // FIXME: Currently, we fall through and treat C++ classes like C
8725 // structures.
8726 // FIXME: We also fall through for atomics; not sure what should
8727 // happen there, though.
8728 } else if (RHS.get()->getType() == Context.OverloadTy) {
8729 // As a set of extensions to C, we support overloading on functions. These
8730 // functions need to be resolved here.
8731 DeclAccessPair DAP;
8732 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8733 RHS.get(), LHSType, /*Complain=*/false, DAP))
8734 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8735 else
8736 return Incompatible;
8737 }
8738
8739 // C99 6.5.16.1p1: the left operand is a pointer and the right is
8740 // a null pointer constant.
8741 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8742 LHSType->isBlockPointerType()) &&
8743 RHS.get()->isNullPointerConstant(Context,
8744 Expr::NPC_ValueDependentIsNull)) {
8745 if (Diagnose || ConvertRHS) {
8746 CastKind Kind;
8747 CXXCastPath Path;
8748 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8749 /*IgnoreBaseAccess=*/false, Diagnose);
8750 if (ConvertRHS)
8751 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8752 }
8753 return Compatible;
8754 }
8755
8756 // OpenCL queue_t type assignment.
8757 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8758 Context, Expr::NPC_ValueDependentIsNull)) {
8759 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8760 return Compatible;
8761 }
8762
8763 // This check seems unnatural, however it is necessary to ensure the proper
8764 // conversion of functions/arrays. If the conversion were done for all
8765 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8766 // expressions that suppress this implicit conversion (&, sizeof).
8767 //
8768 // Suppress this for references: C++ 8.5.3p5.
8769 if (!LHSType->isReferenceType()) {
8770 // FIXME: We potentially allocate here even if ConvertRHS is false.
8771 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8772 if (RHS.isInvalid())
8773 return Incompatible;
8774 }
8775 CastKind Kind;
8776 Sema::AssignConvertType result =
8777 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8778
8779 // C99 6.5.16.1p2: The value of the right operand is converted to the
8780 // type of the assignment expression.
8781 // CheckAssignmentConstraints allows the left-hand side to be a reference,
8782 // so that we can use references in built-in functions even in C.
8783 // The getNonReferenceType() call makes sure that the resulting expression
8784 // does not have reference type.
8785 if (result != Incompatible && RHS.get()->getType() != LHSType) {
8786 QualType Ty = LHSType.getNonLValueExprType(Context);
8787 Expr *E = RHS.get();
8788
8789 // Check for various Objective-C errors. If we are not reporting
8790 // diagnostics and just checking for errors, e.g., during overload
8791 // resolution, return Incompatible to indicate the failure.
8792 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8793 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8794 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8795 if (!Diagnose)
8796 return Incompatible;
8797 }
8798 if (getLangOpts().ObjC &&
8799 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8800 E->getType(), E, Diagnose) ||
8801 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8802 if (!Diagnose)
8803 return Incompatible;
8804 // Replace the expression with a corrected version and continue so we
8805 // can find further errors.
8806 RHS = E;
8807 return Compatible;
8808 }
8809
8810 if (ConvertRHS)
8811 RHS = ImpCastExprToType(E, Ty, Kind);
8812 }
8813
8814 return result;
8815 }
8816
8817 namespace {
8818 /// The original operand to an operator, prior to the application of the usual
8819 /// arithmetic conversions and converting the arguments of a builtin operator
8820 /// candidate.
8821 struct OriginalOperand {
8822 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8823 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8824 Op = MTE->getSubExpr();
8825 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8826 Op = BTE->getSubExpr();
8827 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8828 Orig = ICE->getSubExprAsWritten();
8829 Conversion = ICE->getConversionFunction();
8830 }
8831 }
8832
8833 QualType getType() const { return Orig->getType(); }
8834
8835 Expr *Orig;
8836 NamedDecl *Conversion;
8837 };
8838 }
8839
8840 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8841 ExprResult &RHS) {
8842 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8843
8844 Diag(Loc, diag::err_typecheck_invalid_operands)
8845 << OrigLHS.getType() << OrigRHS.getType()
8846 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8847
8848 // If a user-defined conversion was applied to either of the operands prior
8849 // to applying the built-in operator rules, tell the user about it.
8850 if (OrigLHS.Conversion) {
8851 Diag(OrigLHS.Conversion->getLocation(),
8852 diag::note_typecheck_invalid_operands_converted)
8853 << 0 << LHS.get()->getType();
8854 }
8855 if (OrigRHS.Conversion) {
8856 Diag(OrigRHS.Conversion->getLocation(),
8857 diag::note_typecheck_invalid_operands_converted)
8858 << 1 << RHS.get()->getType();
8859 }
8860
8861 return QualType();
8862 }
8863
8864 // Diagnose cases where a scalar was implicitly converted to a vector and
8865 // diagnose the underlying types. Otherwise, diagnose the error
8866 // as invalid vector logical operands for non-C++ cases.
8867 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8868 ExprResult &RHS) {
8869 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8870 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8871
8872 bool LHSNatVec = LHSType->isVectorType();
8873 bool RHSNatVec = RHSType->isVectorType();
8874
8875 if (!(LHSNatVec && RHSNatVec)) {
8876 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8877 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8878 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8879 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8880 << Vector->getSourceRange();
8881 return QualType();
8882 }
8883
8884 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8885 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8886 << RHS.get()->getSourceRange();
8887
8888 return QualType();
8889 }
8890
8891 /// Try to convert a value of non-vector type to a vector type by converting
8892 /// the type to the element type of the vector and then performing a splat.
8893 /// If the language is OpenCL, we only use conversions that promote scalar
8894 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8895 /// for float->int.
8896 ///
8897 /// OpenCL V2.0 6.2.6.p2:
8898 /// An error shall occur if any scalar operand type has greater rank
8899 /// than the type of the vector element.
8900 ///
8901 /// \param scalar - if non-null, actually perform the conversions
8902 /// \return true if the operation fails (but without diagnosing the failure)
8903 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8904 QualType scalarTy,
8905 QualType vectorEltTy,
8906 QualType vectorTy,
8907 unsigned &DiagID) {
8908 // The conversion to apply to the scalar before splatting it,
8909 // if necessary.
8910 CastKind scalarCast = CK_NoOp;
8911
8912 if (vectorEltTy->isIntegralType(S.Context)) {
8913 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8914 (scalarTy->isIntegerType() &&
8915 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8916 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8917 return true;
8918 }
8919 if (!scalarTy->isIntegralType(S.Context))
8920 return true;
8921 scalarCast = CK_IntegralCast;
8922 } else if (vectorEltTy->isRealFloatingType()) {
8923 if (scalarTy->isRealFloatingType()) {
8924 if (S.getLangOpts().OpenCL &&
8925 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8926 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8927 return true;
8928 }
8929 scalarCast = CK_FloatingCast;
8930 }
8931 else if (scalarTy->isIntegralType(S.Context))
8932 scalarCast = CK_IntegralToFloating;
8933 else
8934 return true;
8935 } else {
8936 return true;
8937 }
8938
8939 // Adjust scalar if desired.
8940 if (scalar) {
8941 if (scalarCast != CK_NoOp)
8942 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8943 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8944 }
8945 return false;
8946 }
8947
8948 /// Convert vector E to a vector with the same number of elements but different
8949 /// element type.
8950 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8951 const auto *VecTy = E->getType()->getAs<VectorType>();
8952 assert(VecTy && "Expression E must be a vector");
8953 QualType NewVecTy = S.Context.getVectorType(ElementType,
8954 VecTy->getNumElements(),
8955 VecTy->getVectorKind());
8956
8957 // Look through the implicit cast. Return the subexpression if its type is
8958 // NewVecTy.
8959 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8960 if (ICE->getSubExpr()->getType() == NewVecTy)
8961 return ICE->getSubExpr();
8962
8963 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8964 return S.ImpCastExprToType(E, NewVecTy, Cast);
8965 }
8966
8967 /// Test if a (constant) integer Int can be casted to another integer type
8968 /// IntTy without losing precision.
8969 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8970 QualType OtherIntTy) {
8971 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8972
8973 // Reject cases where the value of the Int is unknown as that would
8974 // possibly cause truncation, but accept cases where the scalar can be
8975 // demoted without loss of precision.
8976 Expr::EvalResult EVResult;
8977 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8978 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8979 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8980 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8981
8982 if (CstInt) {
8983 // If the scalar is constant and is of a higher order and has more active
8984 // bits that the vector element type, reject it.
8985 llvm::APSInt Result = EVResult.Val.getInt();
8986 unsigned NumBits = IntSigned
8987 ? (Result.isNegative() ? Result.getMinSignedBits()
8988 : Result.getActiveBits())
8989 : Result.getActiveBits();
8990 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8991 return true;
8992
8993 // If the signedness of the scalar type and the vector element type
8994 // differs and the number of bits is greater than that of the vector
8995 // element reject it.
8996 return (IntSigned != OtherIntSigned &&
8997 NumBits > S.Context.getIntWidth(OtherIntTy));
8998 }
8999
9000 // Reject cases where the value of the scalar is not constant and it's
9001 // order is greater than that of the vector element type.
9002 return (Order < 0);
9003 }
9004
9005 /// Test if a (constant) integer Int can be casted to floating point type
9006 /// FloatTy without losing precision.
9007 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9008 QualType FloatTy) {
9009 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9010
9011 // Determine if the integer constant can be expressed as a floating point
9012 // number of the appropriate type.
9013 Expr::EvalResult EVResult;
9014 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9015
9016 uint64_t Bits = 0;
9017 if (CstInt) {
9018 // Reject constants that would be truncated if they were converted to
9019 // the floating point type. Test by simple to/from conversion.
9020 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9021 // could be avoided if there was a convertFromAPInt method
9022 // which could signal back if implicit truncation occurred.
9023 llvm::APSInt Result = EVResult.Val.getInt();
9024 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9025 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9026 llvm::APFloat::rmTowardZero);
9027 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9028 !IntTy->hasSignedIntegerRepresentation());
9029 bool Ignored = false;
9030 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9031 &Ignored);
9032 if (Result != ConvertBack)
9033 return true;
9034 } else {
9035 // Reject types that cannot be fully encoded into the mantissa of
9036 // the float.
9037 Bits = S.Context.getTypeSize(IntTy);
9038 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9039 S.Context.getFloatTypeSemantics(FloatTy));
9040 if (Bits > FloatPrec)
9041 return true;
9042 }
9043
9044 return false;
9045 }
9046
9047 /// Attempt to convert and splat Scalar into a vector whose types matches
9048 /// Vector following GCC conversion rules. The rule is that implicit
9049 /// conversion can occur when Scalar can be casted to match Vector's element
9050 /// type without causing truncation of Scalar.
9051 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9052 ExprResult *Vector) {
9053 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9054 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9055 const VectorType *VT = VectorTy->getAs<VectorType>();
9056
9057 assert(!isa<ExtVectorType>(VT) &&
9058 "ExtVectorTypes should not be handled here!");
9059
9060 QualType VectorEltTy = VT->getElementType();
9061
9062 // Reject cases where the vector element type or the scalar element type are
9063 // not integral or floating point types.
9064 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9065 return true;
9066
9067 // The conversion to apply to the scalar before splatting it,
9068 // if necessary.
9069 CastKind ScalarCast = CK_NoOp;
9070
9071 // Accept cases where the vector elements are integers and the scalar is
9072 // an integer.
9073 // FIXME: Notionally if the scalar was a floating point value with a precise
9074 // integral representation, we could cast it to an appropriate integer
9075 // type and then perform the rest of the checks here. GCC will perform
9076 // this conversion in some cases as determined by the input language.
9077 // We should accept it on a language independent basis.
9078 if (VectorEltTy->isIntegralType(S.Context) &&
9079 ScalarTy->isIntegralType(S.Context) &&
9080 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9081
9082 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9083 return true;
9084
9085 ScalarCast = CK_IntegralCast;
9086 } else if (VectorEltTy->isIntegralType(S.Context) &&
9087 ScalarTy->isRealFloatingType()) {
9088 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9089 ScalarCast = CK_FloatingToIntegral;
9090 else
9091 return true;
9092 } else if (VectorEltTy->isRealFloatingType()) {
9093 if (ScalarTy->isRealFloatingType()) {
9094
9095 // Reject cases where the scalar type is not a constant and has a higher
9096 // Order than the vector element type.
9097 llvm::APFloat Result(0.0);
9098 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
9099 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9100 if (!CstScalar && Order < 0)
9101 return true;
9102
9103 // If the scalar cannot be safely casted to the vector element type,
9104 // reject it.
9105 if (CstScalar) {
9106 bool Truncated = false;
9107 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9108 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9109 if (Truncated)
9110 return true;
9111 }
9112
9113 ScalarCast = CK_FloatingCast;
9114 } else if (ScalarTy->isIntegralType(S.Context)) {
9115 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9116 return true;
9117
9118 ScalarCast = CK_IntegralToFloating;
9119 } else
9120 return true;
9121 }
9122
9123 // Adjust scalar if desired.
9124 if (Scalar) {
9125 if (ScalarCast != CK_NoOp)
9126 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9127 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9128 }
9129 return false;
9130 }
9131
9132 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9133 SourceLocation Loc, bool IsCompAssign,
9134 bool AllowBothBool,
9135 bool AllowBoolConversions) {
9136 if (!IsCompAssign) {
9137 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9138 if (LHS.isInvalid())
9139 return QualType();
9140 }
9141 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9142 if (RHS.isInvalid())
9143 return QualType();
9144
9145 // For conversion purposes, we ignore any qualifiers.
9146 // For example, "const float" and "float" are equivalent.
9147 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9148 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9149
9150 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9151 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9152 assert(LHSVecType || RHSVecType);
9153
9154 // AltiVec-style "vector bool op vector bool" combinations are allowed
9155 // for some operators but not others.
9156 if (!AllowBothBool &&
9157 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9158 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9159 return InvalidOperands(Loc, LHS, RHS);
9160
9161 // If the vector types are identical, return.
9162 if (Context.hasSameType(LHSType, RHSType))
9163 return LHSType;
9164
9165 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9166 if (LHSVecType && RHSVecType &&
9167 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9168 if (isa<ExtVectorType>(LHSVecType)) {
9169 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9170 return LHSType;
9171 }
9172
9173 if (!IsCompAssign)
9174 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9175 return RHSType;
9176 }
9177
9178 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9179 // can be mixed, with the result being the non-bool type. The non-bool
9180 // operand must have integer element type.
9181 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9182 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9183 (Context.getTypeSize(LHSVecType->getElementType()) ==
9184 Context.getTypeSize(RHSVecType->getElementType()))) {
9185 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9186 LHSVecType->getElementType()->isIntegerType() &&
9187 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9188 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9189 return LHSType;
9190 }
9191 if (!IsCompAssign &&
9192 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9193 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9194 RHSVecType->getElementType()->isIntegerType()) {
9195 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9196 return RHSType;
9197 }
9198 }
9199
9200 // If there's a vector type and a scalar, try to convert the scalar to
9201 // the vector element type and splat.
9202 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9203 if (!RHSVecType) {
9204 if (isa<ExtVectorType>(LHSVecType)) {
9205 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9206 LHSVecType->getElementType(), LHSType,
9207 DiagID))
9208 return LHSType;
9209 } else {
9210 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9211 return LHSType;
9212 }
9213 }
9214 if (!LHSVecType) {
9215 if (isa<ExtVectorType>(RHSVecType)) {
9216 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9217 LHSType, RHSVecType->getElementType(),
9218 RHSType, DiagID))
9219 return RHSType;
9220 } else {
9221 if (LHS.get()->getValueKind() == VK_LValue ||
9222 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9223 return RHSType;
9224 }
9225 }
9226
9227 // FIXME: The code below also handles conversion between vectors and
9228 // non-scalars, we should break this down into fine grained specific checks
9229 // and emit proper diagnostics.
9230 QualType VecType = LHSVecType ? LHSType : RHSType;
9231 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9232 QualType OtherType = LHSVecType ? RHSType : LHSType;
9233 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9234 if (isLaxVectorConversion(OtherType, VecType)) {
9235 // If we're allowing lax vector conversions, only the total (data) size
9236 // needs to be the same. For non compound assignment, if one of the types is
9237 // scalar, the result is always the vector type.
9238 if (!IsCompAssign) {
9239 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9240 return VecType;
9241 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9242 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9243 // type. Note that this is already done by non-compound assignments in
9244 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9245 // <1 x T> -> T. The result is also a vector type.
9246 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9247 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9248 ExprResult *RHSExpr = &RHS;
9249 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9250 return VecType;
9251 }
9252 }
9253
9254 // Okay, the expression is invalid.
9255
9256 // If there's a non-vector, non-real operand, diagnose that.
9257 if ((!RHSVecType && !RHSType->isRealType()) ||
9258 (!LHSVecType && !LHSType->isRealType())) {
9259 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9260 << LHSType << RHSType
9261 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9262 return QualType();
9263 }
9264
9265 // OpenCL V1.1 6.2.6.p1:
9266 // If the operands are of more than one vector type, then an error shall
9267 // occur. Implicit conversions between vector types are not permitted, per
9268 // section 6.2.1.
9269 if (getLangOpts().OpenCL &&
9270 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9271 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9272 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9273 << RHSType;
9274 return QualType();
9275 }
9276
9277
9278 // If there is a vector type that is not a ExtVector and a scalar, we reach
9279 // this point if scalar could not be converted to the vector's element type
9280 // without truncation.
9281 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9282 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9283 QualType Scalar = LHSVecType ? RHSType : LHSType;
9284 QualType Vector = LHSVecType ? LHSType : RHSType;
9285 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9286 Diag(Loc,
9287 diag::err_typecheck_vector_not_convertable_implict_truncation)
9288 << ScalarOrVector << Scalar << Vector;
9289
9290 return QualType();
9291 }
9292
9293 // Otherwise, use the generic diagnostic.
9294 Diag(Loc, DiagID)
9295 << LHSType << RHSType
9296 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9297 return QualType();
9298 }
9299
9300 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9301 // expression. These are mainly cases where the null pointer is used as an
9302 // integer instead of a pointer.
9303 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9304 SourceLocation Loc, bool IsCompare) {
9305 // The canonical way to check for a GNU null is with isNullPointerConstant,
9306 // but we use a bit of a hack here for speed; this is a relatively
9307 // hot path, and isNullPointerConstant is slow.
9308 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9309 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9310
9311 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9312
9313 // Avoid analyzing cases where the result will either be invalid (and
9314 // diagnosed as such) or entirely valid and not something to warn about.
9315 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9316 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9317 return;
9318
9319 // Comparison operations would not make sense with a null pointer no matter
9320 // what the other expression is.
9321 if (!IsCompare) {
9322 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9323 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9324 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9325 return;
9326 }
9327
9328 // The rest of the operations only make sense with a null pointer
9329 // if the other expression is a pointer.
9330 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9331 NonNullType->canDecayToPointerType())
9332 return;
9333
9334 S.Diag(Loc, diag::warn_null_in_comparison_operation)
9335 << LHSNull /* LHS is NULL */ << NonNullType
9336 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9337 }
9338
9339 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9340 SourceLocation Loc) {
9341 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9342 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9343 if (!LUE || !RUE)
9344 return;
9345 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9346 RUE->getKind() != UETT_SizeOf)
9347 return;
9348
9349 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9350 QualType LHSTy = LHSArg->getType();
9351 QualType RHSTy;
9352
9353 if (RUE->isArgumentType())
9354 RHSTy = RUE->getArgumentType();
9355 else
9356 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9357
9358 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9359 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9360 return;
9361
9362 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9363 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9364 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9365 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9366 << LHSArgDecl;
9367 }
9368 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9369 QualType ArrayElemTy = ArrayTy->getElementType();
9370 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9371 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9372 ArrayElemTy->isCharType() ||
9373 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9374 return;
9375 S.Diag(Loc, diag::warn_division_sizeof_array)
9376 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9377 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9378 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9379 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9380 << LHSArgDecl;
9381 }
9382
9383 S.Diag(Loc, diag::note_precedence_silence) << RHS;
9384 }
9385 }
9386
9387 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9388 ExprResult &RHS,
9389 SourceLocation Loc, bool IsDiv) {
9390 // Check for division/remainder by zero.
9391 Expr::EvalResult RHSValue;
9392 if (!RHS.get()->isValueDependent() &&
9393 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9394 RHSValue.Val.getInt() == 0)
9395 S.DiagRuntimeBehavior(Loc, RHS.get(),
9396 S.PDiag(diag::warn_remainder_division_by_zero)
9397 << IsDiv << RHS.get()->getSourceRange());
9398 }
9399
9400 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9401 SourceLocation Loc,
9402 bool IsCompAssign, bool IsDiv) {
9403 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9404
9405 if (LHS.get()->getType()->isVectorType() ||
9406 RHS.get()->getType()->isVectorType())
9407 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9408 /*AllowBothBool*/getLangOpts().AltiVec,
9409 /*AllowBoolConversions*/false);
9410
9411 QualType compType = UsualArithmeticConversions(
9412 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9413 if (LHS.isInvalid() || RHS.isInvalid())
9414 return QualType();
9415
9416
9417 if (compType.isNull() || !compType->isArithmeticType())
9418 return InvalidOperands(Loc, LHS, RHS);
9419 if (IsDiv) {
9420 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9421 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9422 }
9423 return compType;
9424 }
9425
9426 QualType Sema::CheckRemainderOperands(
9427 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9428 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9429
9430 if (LHS.get()->getType()->isVectorType() ||
9431 RHS.get()->getType()->isVectorType()) {
9432 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9433 RHS.get()->getType()->hasIntegerRepresentation())
9434 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9435 /*AllowBothBool*/getLangOpts().AltiVec,
9436 /*AllowBoolConversions*/false);
9437 return InvalidOperands(Loc, LHS, RHS);
9438 }
9439
9440 QualType compType = UsualArithmeticConversions(
9441 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9442 if (LHS.isInvalid() || RHS.isInvalid())
9443 return QualType();
9444
9445 if (compType.isNull() || !compType->isIntegerType())
9446 return InvalidOperands(Loc, LHS, RHS);
9447 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9448 return compType;
9449 }
9450
9451 /// Diagnose invalid arithmetic on two void pointers.
9452 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9453 Expr *LHSExpr, Expr *RHSExpr) {
9454 S.Diag(Loc, S.getLangOpts().CPlusPlus
9455 ? diag::err_typecheck_pointer_arith_void_type
9456 : diag::ext_gnu_void_ptr)
9457 << 1 /* two pointers */ << LHSExpr->getSourceRange()
9458 << RHSExpr->getSourceRange();
9459 }
9460
9461 /// Diagnose invalid arithmetic on a void pointer.
9462 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9463 Expr *Pointer) {
9464 S.Diag(Loc, S.getLangOpts().CPlusPlus
9465 ? diag::err_typecheck_pointer_arith_void_type
9466 : diag::ext_gnu_void_ptr)
9467 << 0 /* one pointer */ << Pointer->getSourceRange();
9468 }
9469
9470 /// Diagnose invalid arithmetic on a null pointer.
9471 ///
9472 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9473 /// idiom, which we recognize as a GNU extension.
9474 ///
9475 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9476 Expr *Pointer, bool IsGNUIdiom) {
9477 if (IsGNUIdiom)
9478 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9479 << Pointer->getSourceRange();
9480 else
9481 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9482 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9483 }
9484
9485 /// Diagnose invalid arithmetic on two function pointers.
9486 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9487 Expr *LHS, Expr *RHS) {
9488 assert(LHS->getType()->isAnyPointerType());
9489 assert(RHS->getType()->isAnyPointerType());
9490 S.Diag(Loc, S.getLangOpts().CPlusPlus
9491 ? diag::err_typecheck_pointer_arith_function_type
9492 : diag::ext_gnu_ptr_func_arith)
9493 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9494 // We only show the second type if it differs from the first.
9495 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9496 RHS->getType())
9497 << RHS->getType()->getPointeeType()
9498 << LHS->getSourceRange() << RHS->getSourceRange();
9499 }
9500
9501 /// Diagnose invalid arithmetic on a function pointer.
9502 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9503 Expr *Pointer) {
9504 assert(Pointer->getType()->isAnyPointerType());
9505 S.Diag(Loc, S.getLangOpts().CPlusPlus
9506 ? diag::err_typecheck_pointer_arith_function_type
9507 : diag::ext_gnu_ptr_func_arith)
9508 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9509 << 0 /* one pointer, so only one type */
9510 << Pointer->getSourceRange();
9511 }
9512
9513 /// Emit error if Operand is incomplete pointer type
9514 ///
9515 /// \returns True if pointer has incomplete type
9516 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9517 Expr *Operand) {
9518 QualType ResType = Operand->getType();
9519 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9520 ResType = ResAtomicType->getValueType();
9521
9522 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9523 QualType PointeeTy = ResType->getPointeeType();
9524 return S.RequireCompleteType(Loc, PointeeTy,
9525 diag::err_typecheck_arithmetic_incomplete_type,
9526 PointeeTy, Operand->getSourceRange());
9527 }
9528
9529 /// Check the validity of an arithmetic pointer operand.
9530 ///
9531 /// If the operand has pointer type, this code will check for pointer types
9532 /// which are invalid in arithmetic operations. These will be diagnosed
9533 /// appropriately, including whether or not the use is supported as an
9534 /// extension.
9535 ///
9536 /// \returns True when the operand is valid to use (even if as an extension).
9537 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9538 Expr *Operand) {
9539 QualType ResType = Operand->getType();
9540 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9541 ResType = ResAtomicType->getValueType();
9542
9543 if (!ResType->isAnyPointerType()) return true;
9544
9545 QualType PointeeTy = ResType->getPointeeType();
9546 if (PointeeTy->isVoidType()) {
9547 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9548 return !S.getLangOpts().CPlusPlus;
9549 }
9550 if (PointeeTy->isFunctionType()) {
9551 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9552 return !S.getLangOpts().CPlusPlus;
9553 }
9554
9555 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9556
9557 return true;
9558 }
9559
9560 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9561 /// operands.
9562 ///
9563 /// This routine will diagnose any invalid arithmetic on pointer operands much
9564 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9565 /// for emitting a single diagnostic even for operations where both LHS and RHS
9566 /// are (potentially problematic) pointers.
9567 ///
9568 /// \returns True when the operand is valid to use (even if as an extension).
9569 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9570 Expr *LHSExpr, Expr *RHSExpr) {
9571 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9572 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9573 if (!isLHSPointer && !isRHSPointer) return true;
9574
9575 QualType LHSPointeeTy, RHSPointeeTy;
9576 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9577 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9578
9579 // if both are pointers check if operation is valid wrt address spaces
9580 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9581 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9582 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9583 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9584 S.Diag(Loc,
9585 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9586 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9587 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9588 return false;
9589 }
9590 }
9591
9592 // Check for arithmetic on pointers to incomplete types.
9593 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9594 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9595 if (isLHSVoidPtr || isRHSVoidPtr) {
9596 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9597 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9598 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9599
9600 return !S.getLangOpts().CPlusPlus;
9601 }
9602
9603 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9604 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9605 if (isLHSFuncPtr || isRHSFuncPtr) {
9606 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9607 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9608 RHSExpr);
9609 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9610
9611 return !S.getLangOpts().CPlusPlus;
9612 }
9613
9614 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9615 return false;
9616 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9617 return false;
9618
9619 return true;
9620 }
9621
9622 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9623 /// literal.
9624 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9625 Expr *LHSExpr, Expr *RHSExpr) {
9626 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9627 Expr* IndexExpr = RHSExpr;
9628 if (!StrExpr) {
9629 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9630 IndexExpr = LHSExpr;
9631 }
9632
9633 bool IsStringPlusInt = StrExpr &&
9634 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9635 if (!IsStringPlusInt || IndexExpr->isValueDependent())
9636 return;
9637
9638 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9639 Self.Diag(OpLoc, diag::warn_string_plus_int)
9640 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9641
9642 // Only print a fixit for "str" + int, not for int + "str".
9643 if (IndexExpr == RHSExpr) {
9644 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9645 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9646 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9647 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9648 << FixItHint::CreateInsertion(EndLoc, "]");
9649 } else
9650 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9651 }
9652
9653 /// Emit a warning when adding a char literal to a string.
9654 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9655 Expr *LHSExpr, Expr *RHSExpr) {
9656 const Expr *StringRefExpr = LHSExpr;
9657 const CharacterLiteral *CharExpr =
9658 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9659
9660 if (!CharExpr) {
9661 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9662 StringRefExpr = RHSExpr;
9663 }
9664
9665 if (!CharExpr || !StringRefExpr)
9666 return;
9667
9668 const QualType StringType = StringRefExpr->getType();
9669
9670 // Return if not a PointerType.
9671 if (!StringType->isAnyPointerType())
9672 return;
9673
9674 // Return if not a CharacterType.
9675 if (!StringType->getPointeeType()->isAnyCharacterType())
9676 return;
9677
9678 ASTContext &Ctx = Self.getASTContext();
9679 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9680
9681 const QualType CharType = CharExpr->getType();
9682 if (!CharType->isAnyCharacterType() &&
9683 CharType->isIntegerType() &&
9684 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9685 Self.Diag(OpLoc, diag::warn_string_plus_char)
9686 << DiagRange << Ctx.CharTy;
9687 } else {
9688 Self.Diag(OpLoc, diag::warn_string_plus_char)
9689 << DiagRange << CharExpr->getType();
9690 }
9691
9692 // Only print a fixit for str + char, not for char + str.
9693 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9694 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9695 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9696 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9697 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9698 << FixItHint::CreateInsertion(EndLoc, "]");
9699 } else {
9700 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9701 }
9702 }
9703
9704 /// Emit error when two pointers are incompatible.
9705 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9706 Expr *LHSExpr, Expr *RHSExpr) {
9707 assert(LHSExpr->getType()->isAnyPointerType());
9708 assert(RHSExpr->getType()->isAnyPointerType());
9709 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9710 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9711 << RHSExpr->getSourceRange();
9712 }
9713
9714 // C99 6.5.6
9715 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9716 SourceLocation Loc, BinaryOperatorKind Opc,
9717 QualType* CompLHSTy) {
9718 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9719
9720 if (LHS.get()->getType()->isVectorType() ||
9721 RHS.get()->getType()->isVectorType()) {
9722 QualType compType = CheckVectorOperands(
9723 LHS, RHS, Loc, CompLHSTy,
9724 /*AllowBothBool*/getLangOpts().AltiVec,
9725 /*AllowBoolConversions*/getLangOpts().ZVector);
9726 if (CompLHSTy) *CompLHSTy = compType;
9727 return compType;
9728 }
9729
9730 QualType compType = UsualArithmeticConversions(
9731 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9732 if (LHS.isInvalid() || RHS.isInvalid())
9733 return QualType();
9734
9735 // Diagnose "string literal" '+' int and string '+' "char literal".
9736 if (Opc == BO_Add) {
9737 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9738 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9739 }
9740
9741 // handle the common case first (both operands are arithmetic).
9742 if (!compType.isNull() && compType->isArithmeticType()) {
9743 if (CompLHSTy) *CompLHSTy = compType;
9744 return compType;
9745 }
9746
9747 // Type-checking. Ultimately the pointer's going to be in PExp;
9748 // note that we bias towards the LHS being the pointer.
9749 Expr *PExp = LHS.get(), *IExp = RHS.get();
9750
9751 bool isObjCPointer;
9752 if (PExp->getType()->isPointerType()) {
9753 isObjCPointer = false;
9754 } else if (PExp->getType()->isObjCObjectPointerType()) {
9755 isObjCPointer = true;
9756 } else {
9757 std::swap(PExp, IExp);
9758 if (PExp->getType()->isPointerType()) {
9759 isObjCPointer = false;
9760 } else if (PExp->getType()->isObjCObjectPointerType()) {
9761 isObjCPointer = true;
9762 } else {
9763 return InvalidOperands(Loc, LHS, RHS);
9764 }
9765 }
9766 assert(PExp->getType()->isAnyPointerType());
9767
9768 if (!IExp->getType()->isIntegerType())
9769 return InvalidOperands(Loc, LHS, RHS);
9770
9771 // Adding to a null pointer results in undefined behavior.
9772 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9773 Context, Expr::NPC_ValueDependentIsNotNull)) {
9774 // In C++ adding zero to a null pointer is defined.
9775 Expr::EvalResult KnownVal;
9776 if (!getLangOpts().CPlusPlus ||
9777 (!IExp->isValueDependent() &&
9778 (!IExp->EvaluateAsInt(KnownVal, Context) ||
9779 KnownVal.Val.getInt() != 0))) {
9780 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9781 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9782 Context, BO_Add, PExp, IExp);
9783 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9784 }
9785 }
9786
9787 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9788 return QualType();
9789
9790 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9791 return QualType();
9792
9793 // Check array bounds for pointer arithemtic
9794 CheckArrayAccess(PExp, IExp);
9795
9796 if (CompLHSTy) {
9797 QualType LHSTy = Context.isPromotableBitField(LHS.get());
9798 if (LHSTy.isNull()) {
9799 LHSTy = LHS.get()->getType();
9800 if (LHSTy->isPromotableIntegerType())
9801 LHSTy = Context.getPromotedIntegerType(LHSTy);
9802 }
9803 *CompLHSTy = LHSTy;
9804 }
9805
9806 return PExp->getType();
9807 }
9808
9809 // C99 6.5.6
9810 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9811 SourceLocation Loc,
9812 QualType* CompLHSTy) {
9813 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9814
9815 if (LHS.get()->getType()->isVectorType() ||
9816 RHS.get()->getType()->isVectorType()) {
9817 QualType compType = CheckVectorOperands(
9818 LHS, RHS, Loc, CompLHSTy,
9819 /*AllowBothBool*/getLangOpts().AltiVec,
9820 /*AllowBoolConversions*/getLangOpts().ZVector);
9821 if (CompLHSTy) *CompLHSTy = compType;
9822 return compType;
9823 }
9824
9825 QualType compType = UsualArithmeticConversions(
9826 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9827 if (LHS.isInvalid() || RHS.isInvalid())
9828 return QualType();
9829
9830 // Enforce type constraints: C99 6.5.6p3.
9831
9832 // Handle the common case first (both operands are arithmetic).
9833 if (!compType.isNull() && compType->isArithmeticType()) {
9834 if (CompLHSTy) *CompLHSTy = compType;
9835 return compType;
9836 }
9837
9838 // Either ptr - int or ptr - ptr.
9839 if (LHS.get()->getType()->isAnyPointerType()) {
9840 QualType lpointee = LHS.get()->getType()->getPointeeType();
9841
9842 // Diagnose bad cases where we step over interface counts.
9843 if (LHS.get()->getType()->isObjCObjectPointerType() &&
9844 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9845 return QualType();
9846
9847 // The result type of a pointer-int computation is the pointer type.
9848 if (RHS.get()->getType()->isIntegerType()) {
9849 // Subtracting from a null pointer should produce a warning.
9850 // The last argument to the diagnose call says this doesn't match the
9851 // GNU int-to-pointer idiom.
9852 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9853 Expr::NPC_ValueDependentIsNotNull)) {
9854 // In C++ adding zero to a null pointer is defined.
9855 Expr::EvalResult KnownVal;
9856 if (!getLangOpts().CPlusPlus ||
9857 (!RHS.get()->isValueDependent() &&
9858 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9859 KnownVal.Val.getInt() != 0))) {
9860 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9861 }
9862 }
9863
9864 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9865 return QualType();
9866
9867 // Check array bounds for pointer arithemtic
9868 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9869 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9870
9871 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9872 return LHS.get()->getType();
9873 }
9874
9875 // Handle pointer-pointer subtractions.
9876 if (const PointerType *RHSPTy
9877 = RHS.get()->getType()->getAs<PointerType>()) {
9878 QualType rpointee = RHSPTy->getPointeeType();
9879
9880 if (getLangOpts().CPlusPlus) {
9881 // Pointee types must be the same: C++ [expr.add]
9882 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9883 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9884 }
9885 } else {
9886 // Pointee types must be compatible C99 6.5.6p3
9887 if (!Context.typesAreCompatible(
9888 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9889 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9890 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9891 return QualType();
9892 }
9893 }
9894
9895 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9896 LHS.get(), RHS.get()))
9897 return QualType();
9898
9899 // FIXME: Add warnings for nullptr - ptr.
9900
9901 // The pointee type may have zero size. As an extension, a structure or
9902 // union may have zero size or an array may have zero length. In this
9903 // case subtraction does not make sense.
9904 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9905 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9906 if (ElementSize.isZero()) {
9907 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9908 << rpointee.getUnqualifiedType()
9909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9910 }
9911 }
9912
9913 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9914 return Context.getPointerDiffType();
9915 }
9916 }
9917
9918 return InvalidOperands(Loc, LHS, RHS);
9919 }
9920
9921 static bool isScopedEnumerationType(QualType T) {
9922 if (const EnumType *ET = T->getAs<EnumType>())
9923 return ET->getDecl()->isScoped();
9924 return false;
9925 }
9926
9927 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9928 SourceLocation Loc, BinaryOperatorKind Opc,
9929 QualType LHSType) {
9930 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9931 // so skip remaining warnings as we don't want to modify values within Sema.
9932 if (S.getLangOpts().OpenCL)
9933 return;
9934
9935 // Check right/shifter operand
9936 Expr::EvalResult RHSResult;
9937 if (RHS.get()->isValueDependent() ||
9938 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9939 return;
9940 llvm::APSInt Right = RHSResult.Val.getInt();
9941
9942 if (Right.isNegative()) {
9943 S.DiagRuntimeBehavior(Loc, RHS.get(),
9944 S.PDiag(diag::warn_shift_negative)
9945 << RHS.get()->getSourceRange());
9946 return;
9947 }
9948 llvm::APInt LeftBits(Right.getBitWidth(),
9949 S.Context.getTypeSize(LHS.get()->getType()));
9950 if (Right.uge(LeftBits)) {
9951 S.DiagRuntimeBehavior(Loc, RHS.get(),
9952 S.PDiag(diag::warn_shift_gt_typewidth)
9953 << RHS.get()->getSourceRange());
9954 return;
9955 }
9956 if (Opc != BO_Shl)
9957 return;
9958
9959 // When left shifting an ICE which is signed, we can check for overflow which
9960 // according to C++ standards prior to C++2a has undefined behavior
9961 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9962 // more than the maximum value representable in the result type, so never
9963 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9964 // expression is still probably a bug.)
9965 Expr::EvalResult LHSResult;
9966 if (LHS.get()->isValueDependent() ||
9967 LHSType->hasUnsignedIntegerRepresentation() ||
9968 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9969 return;
9970 llvm::APSInt Left = LHSResult.Val.getInt();
9971
9972 // If LHS does not have a signed type and non-negative value
9973 // then, the behavior is undefined before C++2a. Warn about it.
9974 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9975 !S.getLangOpts().CPlusPlus2a) {
9976 S.DiagRuntimeBehavior(Loc, LHS.get(),
9977 S.PDiag(diag::warn_shift_lhs_negative)
9978 << LHS.get()->getSourceRange());
9979 return;
9980 }
9981
9982 llvm::APInt ResultBits =
9983 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9984 if (LeftBits.uge(ResultBits))
9985 return;
9986 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9987 Result = Result.shl(Right);
9988
9989 // Print the bit representation of the signed integer as an unsigned
9990 // hexadecimal number.
9991 SmallString<40> HexResult;
9992 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9993
9994 // If we are only missing a sign bit, this is less likely to result in actual
9995 // bugs -- if the result is cast back to an unsigned type, it will have the
9996 // expected value. Thus we place this behind a different warning that can be
9997 // turned off separately if needed.
9998 if (LeftBits == ResultBits - 1) {
9999 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10000 << HexResult << LHSType
10001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10002 return;
10003 }
10004
10005 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10006 << HexResult.str() << Result.getMinSignedBits() << LHSType
10007 << Left.getBitWidth() << LHS.get()->getSourceRange()
10008 << RHS.get()->getSourceRange();
10009 }
10010
10011 /// Return the resulting type when a vector is shifted
10012 /// by a scalar or vector shift amount.
10013 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10014 SourceLocation Loc, bool IsCompAssign) {
10015 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10016 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10017 !LHS.get()->getType()->isVectorType()) {
10018 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10019 << RHS.get()->getType() << LHS.get()->getType()
10020 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10021 return QualType();
10022 }
10023
10024 if (!IsCompAssign) {
10025 LHS = S.UsualUnaryConversions(LHS.get());
10026 if (LHS.isInvalid()) return QualType();
10027 }
10028
10029 RHS = S.UsualUnaryConversions(RHS.get());
10030 if (RHS.isInvalid()) return QualType();
10031
10032 QualType LHSType = LHS.get()->getType();
10033 // Note that LHS might be a scalar because the routine calls not only in
10034 // OpenCL case.
10035 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10036 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10037
10038 // Note that RHS might not be a vector.
10039 QualType RHSType = RHS.get()->getType();
10040 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10041 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10042
10043 // The operands need to be integers.
10044 if (!LHSEleType->isIntegerType()) {
10045 S.Diag(Loc, diag::err_typecheck_expect_int)
10046 << LHS.get()->getType() << LHS.get()->getSourceRange();
10047 return QualType();
10048 }
10049
10050 if (!RHSEleType->isIntegerType()) {
10051 S.Diag(Loc, diag::err_typecheck_expect_int)
10052 << RHS.get()->getType() << RHS.get()->getSourceRange();
10053 return QualType();
10054 }
10055
10056 if (!LHSVecTy) {
10057 assert(RHSVecTy);
10058 if (IsCompAssign)
10059 return RHSType;
10060 if (LHSEleType != RHSEleType) {
10061 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10062 LHSEleType = RHSEleType;
10063 }
10064 QualType VecTy =
10065 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10066 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10067 LHSType = VecTy;
10068 } else if (RHSVecTy) {
10069 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10070 // are applied component-wise. So if RHS is a vector, then ensure
10071 // that the number of elements is the same as LHS...
10072 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10073 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10074 << LHS.get()->getType() << RHS.get()->getType()
10075 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10076 return QualType();
10077 }
10078 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10079 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10080 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10081 if (LHSBT != RHSBT &&
10082 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10083 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10084 << LHS.get()->getType() << RHS.get()->getType()
10085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10086 }
10087 }
10088 } else {
10089 // ...else expand RHS to match the number of elements in LHS.
10090 QualType VecTy =
10091 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10092 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10093 }
10094
10095 return LHSType;
10096 }
10097
10098 // C99 6.5.7
10099 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10100 SourceLocation Loc, BinaryOperatorKind Opc,
10101 bool IsCompAssign) {
10102 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10103
10104 // Vector shifts promote their scalar inputs to vector type.
10105 if (LHS.get()->getType()->isVectorType() ||
10106 RHS.get()->getType()->isVectorType()) {
10107 if (LangOpts.ZVector) {
10108 // The shift operators for the z vector extensions work basically
10109 // like general shifts, except that neither the LHS nor the RHS is
10110 // allowed to be a "vector bool".
10111 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10112 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10113 return InvalidOperands(Loc, LHS, RHS);
10114 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10115 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10116 return InvalidOperands(Loc, LHS, RHS);
10117 }
10118 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10119 }
10120
10121 // Shifts don't perform usual arithmetic conversions, they just do integer
10122 // promotions on each operand. C99 6.5.7p3
10123
10124 // For the LHS, do usual unary conversions, but then reset them away
10125 // if this is a compound assignment.
10126 ExprResult OldLHS = LHS;
10127 LHS = UsualUnaryConversions(LHS.get());
10128 if (LHS.isInvalid())
10129 return QualType();
10130 QualType LHSType = LHS.get()->getType();
10131 if (IsCompAssign) LHS = OldLHS;
10132
10133 // The RHS is simpler.
10134 RHS = UsualUnaryConversions(RHS.get());
10135 if (RHS.isInvalid())
10136 return QualType();
10137 QualType RHSType = RHS.get()->getType();
10138
10139 // C99 6.5.7p2: Each of the operands shall have integer type.
10140 if (!LHSType->hasIntegerRepresentation() ||
10141 !RHSType->hasIntegerRepresentation())
10142 return InvalidOperands(Loc, LHS, RHS);
10143
10144 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10145 // hasIntegerRepresentation() above instead of this.
10146 if (isScopedEnumerationType(LHSType) ||
10147 isScopedEnumerationType(RHSType)) {
10148 return InvalidOperands(Loc, LHS, RHS);
10149 }
10150 // Sanity-check shift operands
10151 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10152
10153 // "The type of the result is that of the promoted left operand."
10154 return LHSType;
10155 }
10156
10157 /// Diagnose bad pointer comparisons.
10158 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10159 ExprResult &LHS, ExprResult &RHS,
10160 bool IsError) {
10161 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10162 : diag::ext_typecheck_comparison_of_distinct_pointers)
10163 << LHS.get()->getType() << RHS.get()->getType()
10164 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10165 }
10166
10167 /// Returns false if the pointers are converted to a composite type,
10168 /// true otherwise.
10169 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10170 ExprResult &LHS, ExprResult &RHS) {
10171 // C++ [expr.rel]p2:
10172 // [...] Pointer conversions (4.10) and qualification
10173 // conversions (4.4) are performed on pointer operands (or on
10174 // a pointer operand and a null pointer constant) to bring
10175 // them to their composite pointer type. [...]
10176 //
10177 // C++ [expr.eq]p1 uses the same notion for (in)equality
10178 // comparisons of pointers.
10179
10180 QualType LHSType = LHS.get()->getType();
10181 QualType RHSType = RHS.get()->getType();
10182 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10183 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10184
10185 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10186 if (T.isNull()) {
10187 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10188 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10189 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10190 else
10191 S.InvalidOperands(Loc, LHS, RHS);
10192 return true;
10193 }
10194
10195 return false;
10196 }
10197
10198 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10199 ExprResult &LHS,
10200 ExprResult &RHS,
10201 bool IsError) {
10202 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10203 : diag::ext_typecheck_comparison_of_fptr_to_void)
10204 << LHS.get()->getType() << RHS.get()->getType()
10205 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10206 }
10207
10208 static bool isObjCObjectLiteral(ExprResult &E) {
10209 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10210 case Stmt::ObjCArrayLiteralClass:
10211 case Stmt::ObjCDictionaryLiteralClass:
10212 case Stmt::ObjCStringLiteralClass:
10213 case Stmt::ObjCBoxedExprClass:
10214 return true;
10215 default:
10216 // Note that ObjCBoolLiteral is NOT an object literal!
10217 return false;
10218 }
10219 }
10220
10221 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10222 const ObjCObjectPointerType *Type =
10223 LHS->getType()->getAs<ObjCObjectPointerType>();
10224
10225 // If this is not actually an Objective-C object, bail out.
10226 if (!Type)
10227 return false;
10228
10229 // Get the LHS object's interface type.
10230 QualType InterfaceType = Type->getPointeeType();
10231
10232 // If the RHS isn't an Objective-C object, bail out.
10233 if (!RHS->getType()->isObjCObjectPointerType())
10234 return false;
10235
10236 // Try to find the -isEqual: method.
10237 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10238 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10239 InterfaceType,
10240 /*IsInstance=*/true);
10241 if (!Method) {
10242 if (Type->isObjCIdType()) {
10243 // For 'id', just check the global pool.
10244 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10245 /*receiverId=*/true);
10246 } else {
10247 // Check protocols.
10248 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10249 /*IsInstance=*/true);
10250 }
10251 }
10252
10253 if (!Method)
10254 return false;
10255
10256 QualType T = Method->parameters()[0]->getType();
10257 if (!T->isObjCObjectPointerType())
10258 return false;
10259
10260 QualType R = Method->getReturnType();
10261 if (!R->isScalarType())
10262 return false;
10263
10264 return true;
10265 }
10266
10267 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10268 FromE = FromE->IgnoreParenImpCasts();
10269 switch (FromE->getStmtClass()) {
10270 default:
10271 break;
10272 case Stmt::ObjCStringLiteralClass:
10273 // "string literal"
10274 return LK_String;
10275 case Stmt::ObjCArrayLiteralClass:
10276 // "array literal"
10277 return LK_Array;
10278 case Stmt::ObjCDictionaryLiteralClass:
10279 // "dictionary literal"
10280 return LK_Dictionary;
10281 case Stmt::BlockExprClass:
10282 return LK_Block;
10283 case Stmt::ObjCBoxedExprClass: {
10284 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10285 switch (Inner->getStmtClass()) {
10286 case Stmt::IntegerLiteralClass:
10287 case Stmt::FloatingLiteralClass:
10288 case Stmt::CharacterLiteralClass:
10289 case Stmt::ObjCBoolLiteralExprClass:
10290 case Stmt::CXXBoolLiteralExprClass:
10291 // "numeric literal"
10292 return LK_Numeric;
10293 case Stmt::ImplicitCastExprClass: {
10294 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10295 // Boolean literals can be represented by implicit casts.
10296 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10297 return LK_Numeric;
10298 break;
10299 }
10300 default:
10301 break;
10302 }
10303 return LK_Boxed;
10304 }
10305 }
10306 return LK_None;
10307 }
10308
10309 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10310 ExprResult &LHS, ExprResult &RHS,
10311 BinaryOperator::Opcode Opc){
10312 Expr *Literal;
10313 Expr *Other;
10314 if (isObjCObjectLiteral(LHS)) {
10315 Literal = LHS.get();
10316 Other = RHS.get();
10317 } else {
10318 Literal = RHS.get();
10319 Other = LHS.get();
10320 }
10321
10322 // Don't warn on comparisons against nil.
10323 Other = Other->IgnoreParenCasts();
10324 if (Other->isNullPointerConstant(S.getASTContext(),
10325 Expr::NPC_ValueDependentIsNotNull))
10326 return;
10327
10328 // This should be kept in sync with warn_objc_literal_comparison.
10329 // LK_String should always be after the other literals, since it has its own
10330 // warning flag.
10331 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10332 assert(LiteralKind != Sema::LK_Block);
10333 if (LiteralKind == Sema::LK_None) {
10334 llvm_unreachable("Unknown Objective-C object literal kind");
10335 }
10336
10337 if (LiteralKind == Sema::LK_String)
10338 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10339 << Literal->getSourceRange();
10340 else
10341 S.Diag(Loc, diag::warn_objc_literal_comparison)
10342 << LiteralKind << Literal->getSourceRange();
10343
10344 if (BinaryOperator::isEqualityOp(Opc) &&
10345 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10346 SourceLocation Start = LHS.get()->getBeginLoc();
10347 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10348 CharSourceRange OpRange =
10349 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10350
10351 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10352 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10353 << FixItHint::CreateReplacement(OpRange, " isEqual:")
10354 << FixItHint::CreateInsertion(End, "]");
10355 }
10356 }
10357
10358 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10359 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10360 ExprResult &RHS, SourceLocation Loc,
10361 BinaryOperatorKind Opc) {
10362 // Check that left hand side is !something.
10363 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10364 if (!UO || UO->getOpcode() != UO_LNot) return;
10365
10366 // Only check if the right hand side is non-bool arithmetic type.
10367 if (RHS.get()->isKnownToHaveBooleanValue()) return;
10368
10369 // Make sure that the something in !something is not bool.
10370 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10371 if (SubExpr->isKnownToHaveBooleanValue()) return;
10372
10373 // Emit warning.
10374 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10375 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10376 << Loc << IsBitwiseOp;
10377
10378 // First note suggest !(x < y)
10379 SourceLocation FirstOpen = SubExpr->getBeginLoc();
10380 SourceLocation FirstClose = RHS.get()->getEndLoc();
10381 FirstClose = S.getLocForEndOfToken(FirstClose);
10382 if (FirstClose.isInvalid())
10383 FirstOpen = SourceLocation();
10384 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10385 << IsBitwiseOp
10386 << FixItHint::CreateInsertion(FirstOpen, "(")
10387 << FixItHint::CreateInsertion(FirstClose, ")");
10388
10389 // Second note suggests (!x) < y
10390 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10391 SourceLocation SecondClose = LHS.get()->getEndLoc();
10392 SecondClose = S.getLocForEndOfToken(SecondClose);
10393 if (SecondClose.isInvalid())
10394 SecondOpen = SourceLocation();
10395 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10396 << FixItHint::CreateInsertion(SecondOpen, "(")
10397 << FixItHint::CreateInsertion(SecondClose, ")");
10398 }
10399
10400 // Returns true if E refers to a non-weak array.
10401 static bool checkForArray(const Expr *E) {
10402 const ValueDecl *D = nullptr;
10403 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10404 D = DR->getDecl();
10405 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10406 if (Mem->isImplicitAccess())
10407 D = Mem->getMemberDecl();
10408 }
10409 if (!D)
10410 return false;
10411 return D->getType()->isArrayType() && !D->isWeak();
10412 }
10413
10414 /// Diagnose some forms of syntactically-obvious tautological comparison.
10415 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10416 Expr *LHS, Expr *RHS,
10417 BinaryOperatorKind Opc) {
10418 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10419 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10420
10421 QualType LHSType = LHS->getType();
10422 QualType RHSType = RHS->getType();
10423 if (LHSType->hasFloatingRepresentation() ||
10424 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10425 S.inTemplateInstantiation())
10426 return;
10427
10428 // Comparisons between two array types are ill-formed for operator<=>, so
10429 // we shouldn't emit any additional warnings about it.
10430 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10431 return;
10432
10433 // For non-floating point types, check for self-comparisons of the form
10434 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10435 // often indicate logic errors in the program.
10436 //
10437 // NOTE: Don't warn about comparison expressions resulting from macro
10438 // expansion. Also don't warn about comparisons which are only self
10439 // comparisons within a template instantiation. The warnings should catch
10440 // obvious cases in the definition of the template anyways. The idea is to
10441 // warn when the typed comparison operator will always evaluate to the same
10442 // result.
10443
10444 // Used for indexing into %select in warn_comparison_always
10445 enum {
10446 AlwaysConstant,
10447 AlwaysTrue,
10448 AlwaysFalse,
10449 AlwaysEqual, // std::strong_ordering::equal from operator<=>
10450 };
10451
10452 // C++2a [depr.array.comp]:
10453 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10454 // operands of array type are deprecated.
10455 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10456 RHSStripped->getType()->isArrayType()) {
10457 S.Diag(Loc, diag::warn_depr_array_comparison)
10458 << LHS->getSourceRange() << RHS->getSourceRange()
10459 << LHSStripped->getType() << RHSStripped->getType();
10460 // Carry on to produce the tautological comparison warning, if this
10461 // expression is potentially-evaluated, we can resolve the array to a
10462 // non-weak declaration, and so on.
10463 }
10464
10465 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10466 if (Expr::isSameComparisonOperand(LHS, RHS)) {
10467 unsigned Result;
10468 switch (Opc) {
10469 case BO_EQ:
10470 case BO_LE:
10471 case BO_GE:
10472 Result = AlwaysTrue;
10473 break;
10474 case BO_NE:
10475 case BO_LT:
10476 case BO_GT:
10477 Result = AlwaysFalse;
10478 break;
10479 case BO_Cmp:
10480 Result = AlwaysEqual;
10481 break;
10482 default:
10483 Result = AlwaysConstant;
10484 break;
10485 }
10486 S.DiagRuntimeBehavior(Loc, nullptr,
10487 S.PDiag(diag::warn_comparison_always)
10488 << 0 /*self-comparison*/
10489 << Result);
10490 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10491 // What is it always going to evaluate to?
10492 unsigned Result;
10493 switch (Opc) {
10494 case BO_EQ: // e.g. array1 == array2
10495 Result = AlwaysFalse;
10496 break;
10497 case BO_NE: // e.g. array1 != array2
10498 Result = AlwaysTrue;
10499 break;
10500 default: // e.g. array1 <= array2
10501 // The best we can say is 'a constant'
10502 Result = AlwaysConstant;
10503 break;
10504 }
10505 S.DiagRuntimeBehavior(Loc, nullptr,
10506 S.PDiag(diag::warn_comparison_always)
10507 << 1 /*array comparison*/
10508 << Result);
10509 }
10510 }
10511
10512 if (isa<CastExpr>(LHSStripped))
10513 LHSStripped = LHSStripped->IgnoreParenCasts();
10514 if (isa<CastExpr>(RHSStripped))
10515 RHSStripped = RHSStripped->IgnoreParenCasts();
10516
10517 // Warn about comparisons against a string constant (unless the other
10518 // operand is null); the user probably wants string comparison function.
10519 Expr *LiteralString = nullptr;
10520 Expr *LiteralStringStripped = nullptr;
10521 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10522 !RHSStripped->isNullPointerConstant(S.Context,
10523 Expr::NPC_ValueDependentIsNull)) {
10524 LiteralString = LHS;
10525 LiteralStringStripped = LHSStripped;
10526 } else if ((isa<StringLiteral>(RHSStripped) ||
10527 isa<ObjCEncodeExpr>(RHSStripped)) &&
10528 !LHSStripped->isNullPointerConstant(S.Context,
10529 Expr::NPC_ValueDependentIsNull)) {
10530 LiteralString = RHS;
10531 LiteralStringStripped = RHSStripped;
10532 }
10533
10534 if (LiteralString) {
10535 S.DiagRuntimeBehavior(Loc, nullptr,
10536 S.PDiag(diag::warn_stringcompare)
10537 << isa<ObjCEncodeExpr>(LiteralStringStripped)
10538 << LiteralString->getSourceRange());
10539 }
10540 }
10541
10542 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10543 switch (CK) {
10544 default: {
10545 #ifndef NDEBUG
10546 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10547 << "\n";
10548 #endif
10549 llvm_unreachable("unhandled cast kind");
10550 }
10551 case CK_UserDefinedConversion:
10552 return ICK_Identity;
10553 case CK_LValueToRValue:
10554 return ICK_Lvalue_To_Rvalue;
10555 case CK_ArrayToPointerDecay:
10556 return ICK_Array_To_Pointer;
10557 case CK_FunctionToPointerDecay:
10558 return ICK_Function_To_Pointer;
10559 case CK_IntegralCast:
10560 return ICK_Integral_Conversion;
10561 case CK_FloatingCast:
10562 return ICK_Floating_Conversion;
10563 case CK_IntegralToFloating:
10564 case CK_FloatingToIntegral:
10565 return ICK_Floating_Integral;
10566 case CK_IntegralComplexCast:
10567 case CK_FloatingComplexCast:
10568 case CK_FloatingComplexToIntegralComplex:
10569 case CK_IntegralComplexToFloatingComplex:
10570 return ICK_Complex_Conversion;
10571 case CK_FloatingComplexToReal:
10572 case CK_FloatingRealToComplex:
10573 case CK_IntegralComplexToReal:
10574 case CK_IntegralRealToComplex:
10575 return ICK_Complex_Real;
10576 }
10577 }
10578
10579 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10580 QualType FromType,
10581 SourceLocation Loc) {
10582 // Check for a narrowing implicit conversion.
10583 StandardConversionSequence SCS;
10584 SCS.setAsIdentityConversion();
10585 SCS.setToType(0, FromType);
10586 SCS.setToType(1, ToType);
10587 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10588 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10589
10590 APValue PreNarrowingValue;
10591 QualType PreNarrowingType;
10592 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10593 PreNarrowingType,
10594 /*IgnoreFloatToIntegralConversion*/ true)) {
10595 case NK_Dependent_Narrowing:
10596 // Implicit conversion to a narrower type, but the expression is
10597 // value-dependent so we can't tell whether it's actually narrowing.
10598 case NK_Not_Narrowing:
10599 return false;
10600
10601 case NK_Constant_Narrowing:
10602 // Implicit conversion to a narrower type, and the value is not a constant
10603 // expression.
10604 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10605 << /*Constant*/ 1
10606 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10607 return true;
10608
10609 case NK_Variable_Narrowing:
10610 // Implicit conversion to a narrower type, and the value is not a constant
10611 // expression.
10612 case NK_Type_Narrowing:
10613 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10614 << /*Constant*/ 0 << FromType << ToType;
10615 // TODO: It's not a constant expression, but what if the user intended it
10616 // to be? Can we produce notes to help them figure out why it isn't?
10617 return true;
10618 }
10619 llvm_unreachable("unhandled case in switch");
10620 }
10621
10622 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10623 ExprResult &LHS,
10624 ExprResult &RHS,
10625 SourceLocation Loc) {
10626 QualType LHSType = LHS.get()->getType();
10627 QualType RHSType = RHS.get()->getType();
10628 // Dig out the original argument type and expression before implicit casts
10629 // were applied. These are the types/expressions we need to check the
10630 // [expr.spaceship] requirements against.
10631 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10632 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10633 QualType LHSStrippedType = LHSStripped.get()->getType();
10634 QualType RHSStrippedType = RHSStripped.get()->getType();
10635
10636 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10637 // other is not, the program is ill-formed.
10638 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10639 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10640 return QualType();
10641 }
10642
10643 // FIXME: Consider combining this with checkEnumArithmeticConversions.
10644 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10645 RHSStrippedType->isEnumeralType();
10646 if (NumEnumArgs == 1) {
10647 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10648 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10649 if (OtherTy->hasFloatingRepresentation()) {
10650 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10651 return QualType();
10652 }
10653 }
10654 if (NumEnumArgs == 2) {
10655 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10656 // type E, the operator yields the result of converting the operands
10657 // to the underlying type of E and applying <=> to the converted operands.
10658 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10659 S.InvalidOperands(Loc, LHS, RHS);
10660 return QualType();
10661 }
10662 QualType IntType =
10663 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10664 assert(IntType->isArithmeticType());
10665
10666 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10667 // promote the boolean type, and all other promotable integer types, to
10668 // avoid this.
10669 if (IntType->isPromotableIntegerType())
10670 IntType = S.Context.getPromotedIntegerType(IntType);
10671
10672 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10673 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10674 LHSType = RHSType = IntType;
10675 }
10676
10677 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10678 // usual arithmetic conversions are applied to the operands.
10679 QualType Type =
10680 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10681 if (LHS.isInvalid() || RHS.isInvalid())
10682 return QualType();
10683 if (Type.isNull())
10684 return S.InvalidOperands(Loc, LHS, RHS);
10685
10686 Optional<ComparisonCategoryType> CCT =
10687 getComparisonCategoryForBuiltinCmp(Type);
10688 if (!CCT)
10689 return S.InvalidOperands(Loc, LHS, RHS);
10690
10691 bool HasNarrowing = checkThreeWayNarrowingConversion(
10692 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10693 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10694 RHS.get()->getBeginLoc());
10695 if (HasNarrowing)
10696 return QualType();
10697
10698 assert(!Type.isNull() && "composite type for <=> has not been set");
10699
10700 return S.CheckComparisonCategoryType(
10701 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
10702 }
10703
10704 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10705 ExprResult &RHS,
10706 SourceLocation Loc,
10707 BinaryOperatorKind Opc) {
10708 if (Opc == BO_Cmp)
10709 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10710
10711 // C99 6.5.8p3 / C99 6.5.9p4
10712 QualType Type =
10713 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10714 if (LHS.isInvalid() || RHS.isInvalid())
10715 return QualType();
10716 if (Type.isNull())
10717 return S.InvalidOperands(Loc, LHS, RHS);
10718 assert(Type->isArithmeticType() || Type->isEnumeralType());
10719
10720 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10721 return S.InvalidOperands(Loc, LHS, RHS);
10722
10723 // Check for comparisons of floating point operands using != and ==.
10724 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10725 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10726
10727 // The result of comparisons is 'bool' in C++, 'int' in C.
10728 return S.Context.getLogicalOperationType();
10729 }
10730
10731 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10732 if (!NullE.get()->getType()->isAnyPointerType())
10733 return;
10734 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10735 if (!E.get()->getType()->isAnyPointerType() &&
10736 E.get()->isNullPointerConstant(Context,
10737 Expr::NPC_ValueDependentIsNotNull) ==
10738 Expr::NPCK_ZeroExpression) {
10739 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10740 if (CL->getValue() == 0)
10741 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10742 << NullValue
10743 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10744 NullValue ? "NULL" : "(void *)0");
10745 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10746 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10747 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10748 if (T == Context.CharTy)
10749 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10750 << NullValue
10751 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10752 NullValue ? "NULL" : "(void *)0");
10753 }
10754 }
10755 }
10756
10757 // C99 6.5.8, C++ [expr.rel]
10758 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10759 SourceLocation Loc,
10760 BinaryOperatorKind Opc) {
10761 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10762 bool IsThreeWay = Opc == BO_Cmp;
10763 bool IsOrdered = IsRelational || IsThreeWay;
10764 auto IsAnyPointerType = [](ExprResult E) {
10765 QualType Ty = E.get()->getType();
10766 return Ty->isPointerType() || Ty->isMemberPointerType();
10767 };
10768
10769 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10770 // type, array-to-pointer, ..., conversions are performed on both operands to
10771 // bring them to their composite type.
10772 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10773 // any type-related checks.
10774 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10775 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10776 if (LHS.isInvalid())
10777 return QualType();
10778 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10779 if (RHS.isInvalid())
10780 return QualType();
10781 } else {
10782 LHS = DefaultLvalueConversion(LHS.get());
10783 if (LHS.isInvalid())
10784 return QualType();
10785 RHS = DefaultLvalueConversion(RHS.get());
10786 if (RHS.isInvalid())
10787 return QualType();
10788 }
10789
10790 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10791 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10792 CheckPtrComparisonWithNullChar(LHS, RHS);
10793 CheckPtrComparisonWithNullChar(RHS, LHS);
10794 }
10795
10796 // Handle vector comparisons separately.
10797 if (LHS.get()->getType()->isVectorType() ||
10798 RHS.get()->getType()->isVectorType())
10799 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10800
10801 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10802 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10803
10804 QualType LHSType = LHS.get()->getType();
10805 QualType RHSType = RHS.get()->getType();
10806 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10807 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10808 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10809
10810 const Expr::NullPointerConstantKind LHSNullKind =
10811 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10812 const Expr::NullPointerConstantKind RHSNullKind =
10813 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10814 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10815 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10816
10817 auto computeResultTy = [&]() {
10818 if (Opc != BO_Cmp)
10819 return Context.getLogicalOperationType();
10820 assert(getLangOpts().CPlusPlus);
10821 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10822
10823 QualType CompositeTy = LHS.get()->getType();
10824 assert(!CompositeTy->isReferenceType());
10825
10826 Optional<ComparisonCategoryType> CCT =
10827 getComparisonCategoryForBuiltinCmp(CompositeTy);
10828 if (!CCT)
10829 return InvalidOperands(Loc, LHS, RHS);
10830
10831 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
10832 // P0946R0: Comparisons between a null pointer constant and an object
10833 // pointer result in std::strong_equality, which is ill-formed under
10834 // P1959R0.
10835 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
10836 << (LHSIsNull ? LHS.get()->getSourceRange()
10837 : RHS.get()->getSourceRange());
10838 return QualType();
10839 }
10840
10841 return CheckComparisonCategoryType(
10842 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
10843 };
10844
10845 if (!IsOrdered && LHSIsNull != RHSIsNull) {
10846 bool IsEquality = Opc == BO_EQ;
10847 if (RHSIsNull)
10848 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10849 RHS.get()->getSourceRange());
10850 else
10851 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10852 LHS.get()->getSourceRange());
10853 }
10854
10855 if ((LHSType->isIntegerType() && !LHSIsNull) ||
10856 (RHSType->isIntegerType() && !RHSIsNull)) {
10857 // Skip normal pointer conversion checks in this case; we have better
10858 // diagnostics for this below.
10859 } else if (getLangOpts().CPlusPlus) {
10860 // Equality comparison of a function pointer to a void pointer is invalid,
10861 // but we allow it as an extension.
10862 // FIXME: If we really want to allow this, should it be part of composite
10863 // pointer type computation so it works in conditionals too?
10864 if (!IsOrdered &&
10865 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10866 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10867 // This is a gcc extension compatibility comparison.
10868 // In a SFINAE context, we treat this as a hard error to maintain
10869 // conformance with the C++ standard.
10870 diagnoseFunctionPointerToVoidComparison(
10871 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10872
10873 if (isSFINAEContext())
10874 return QualType();
10875
10876 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10877 return computeResultTy();
10878 }
10879
10880 // C++ [expr.eq]p2:
10881 // If at least one operand is a pointer [...] bring them to their
10882 // composite pointer type.
10883 // C++ [expr.spaceship]p6
10884 // If at least one of the operands is of pointer type, [...] bring them
10885 // to their composite pointer type.
10886 // C++ [expr.rel]p2:
10887 // If both operands are pointers, [...] bring them to their composite
10888 // pointer type.
10889 // For <=>, the only valid non-pointer types are arrays and functions, and
10890 // we already decayed those, so this is really the same as the relational
10891 // comparison rule.
10892 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10893 (IsOrdered ? 2 : 1) &&
10894 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10895 RHSType->isObjCObjectPointerType()))) {
10896 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10897 return QualType();
10898 return computeResultTy();
10899 }
10900 } else if (LHSType->isPointerType() &&
10901 RHSType->isPointerType()) { // C99 6.5.8p2
10902 // All of the following pointer-related warnings are GCC extensions, except
10903 // when handling null pointer constants.
10904 QualType LCanPointeeTy =
10905 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10906 QualType RCanPointeeTy =
10907 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10908
10909 // C99 6.5.9p2 and C99 6.5.8p2
10910 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10911 RCanPointeeTy.getUnqualifiedType())) {
10912 // Valid unless a relational comparison of function pointers
10913 if (IsRelational && LCanPointeeTy->isFunctionType()) {
10914 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10915 << LHSType << RHSType << LHS.get()->getSourceRange()
10916 << RHS.get()->getSourceRange();
10917 }
10918 } else if (!IsRelational &&
10919 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10920 // Valid unless comparison between non-null pointer and function pointer
10921 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10922 && !LHSIsNull && !RHSIsNull)
10923 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10924 /*isError*/false);
10925 } else {
10926 // Invalid
10927 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10928 }
10929 if (LCanPointeeTy != RCanPointeeTy) {
10930 // Treat NULL constant as a special case in OpenCL.
10931 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10932 const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10933 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10934 Diag(Loc,
10935 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10936 << LHSType << RHSType << 0 /* comparison */
10937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10938 }
10939 }
10940 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10941 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10942 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10943 : CK_BitCast;
10944 if (LHSIsNull && !RHSIsNull)
10945 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10946 else
10947 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10948 }
10949 return computeResultTy();
10950 }
10951
10952 if (getLangOpts().CPlusPlus) {
10953 // C++ [expr.eq]p4:
10954 // Two operands of type std::nullptr_t or one operand of type
10955 // std::nullptr_t and the other a null pointer constant compare equal.
10956 if (!IsOrdered && LHSIsNull && RHSIsNull) {
10957 if (LHSType->isNullPtrType()) {
10958 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10959 return computeResultTy();
10960 }
10961 if (RHSType->isNullPtrType()) {
10962 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10963 return computeResultTy();
10964 }
10965 }
10966
10967 // Comparison of Objective-C pointers and block pointers against nullptr_t.
10968 // These aren't covered by the composite pointer type rules.
10969 if (!IsOrdered && RHSType->isNullPtrType() &&
10970 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10971 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10972 return computeResultTy();
10973 }
10974 if (!IsOrdered && LHSType->isNullPtrType() &&
10975 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10976 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10977 return computeResultTy();
10978 }
10979
10980 if (IsRelational &&
10981 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10982 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10983 // HACK: Relational comparison of nullptr_t against a pointer type is
10984 // invalid per DR583, but we allow it within std::less<> and friends,
10985 // since otherwise common uses of it break.
10986 // FIXME: Consider removing this hack once LWG fixes std::less<> and
10987 // friends to have std::nullptr_t overload candidates.
10988 DeclContext *DC = CurContext;
10989 if (isa<FunctionDecl>(DC))
10990 DC = DC->getParent();
10991 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10992 if (CTSD->isInStdNamespace() &&
10993 llvm::StringSwitch<bool>(CTSD->getName())
10994 .Cases("less", "less_equal", "greater", "greater_equal", true)
10995 .Default(false)) {
10996 if (RHSType->isNullPtrType())
10997 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10998 else
10999 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11000 return computeResultTy();
11001 }
11002 }
11003 }
11004
11005 // C++ [expr.eq]p2:
11006 // If at least one operand is a pointer to member, [...] bring them to
11007 // their composite pointer type.
11008 if (!IsOrdered &&
11009 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11010 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11011 return QualType();
11012 else
11013 return computeResultTy();
11014 }
11015 }
11016
11017 // Handle block pointer types.
11018 if (!IsOrdered && LHSType->isBlockPointerType() &&
11019 RHSType->isBlockPointerType()) {
11020 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11021 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11022
11023 if (!LHSIsNull && !RHSIsNull &&
11024 !Context.typesAreCompatible(lpointee, rpointee)) {
11025 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11026 << LHSType << RHSType << LHS.get()->getSourceRange()
11027 << RHS.get()->getSourceRange();
11028 }
11029 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11030 return computeResultTy();
11031 }
11032
11033 // Allow block pointers to be compared with null pointer constants.
11034 if (!IsOrdered
11035 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11036 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11037 if (!LHSIsNull && !RHSIsNull) {
11038 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11039 ->getPointeeType()->isVoidType())
11040 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11041 ->getPointeeType()->isVoidType())))
11042 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11043 << LHSType << RHSType << LHS.get()->getSourceRange()
11044 << RHS.get()->getSourceRange();
11045 }
11046 if (LHSIsNull && !RHSIsNull)
11047 LHS = ImpCastExprToType(LHS.get(), RHSType,
11048 RHSType->isPointerType() ? CK_BitCast
11049 : CK_AnyPointerToBlockPointerCast);
11050 else
11051 RHS = ImpCastExprToType(RHS.get(), LHSType,
11052 LHSType->isPointerType() ? CK_BitCast
11053 : CK_AnyPointerToBlockPointerCast);
11054 return computeResultTy();
11055 }
11056
11057 if (LHSType->isObjCObjectPointerType() ||
11058 RHSType->isObjCObjectPointerType()) {
11059 const PointerType *LPT = LHSType->getAs<PointerType>();
11060 const PointerType *RPT = RHSType->getAs<PointerType>();
11061 if (LPT || RPT) {
11062 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11063 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11064
11065 if (!LPtrToVoid && !RPtrToVoid &&
11066 !Context.typesAreCompatible(LHSType, RHSType)) {
11067 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11068 /*isError*/false);
11069 }
11070 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11071 // the RHS, but we have test coverage for this behavior.
11072 // FIXME: Consider using convertPointersToCompositeType in C++.
11073 if (LHSIsNull && !RHSIsNull) {
11074 Expr *E = LHS.get();
11075 if (getLangOpts().ObjCAutoRefCount)
11076 CheckObjCConversion(SourceRange(), RHSType, E,
11077 CCK_ImplicitConversion);
11078 LHS = ImpCastExprToType(E, RHSType,
11079 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11080 }
11081 else {
11082 Expr *E = RHS.get();
11083 if (getLangOpts().ObjCAutoRefCount)
11084 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11085 /*Diagnose=*/true,
11086 /*DiagnoseCFAudited=*/false, Opc);
11087 RHS = ImpCastExprToType(E, LHSType,
11088 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11089 }
11090 return computeResultTy();
11091 }
11092 if (LHSType->isObjCObjectPointerType() &&
11093 RHSType->isObjCObjectPointerType()) {
11094 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11095 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11096 /*isError*/false);
11097 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11098 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11099
11100 if (LHSIsNull && !RHSIsNull)
11101 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11102 else
11103 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11104 return computeResultTy();
11105 }
11106
11107 if (!IsOrdered && LHSType->isBlockPointerType() &&
11108 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11109 LHS = ImpCastExprToType(LHS.get(), RHSType,
11110 CK_BlockPointerToObjCPointerCast);
11111 return computeResultTy();
11112 } else if (!IsOrdered &&
11113 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11114 RHSType->isBlockPointerType()) {
11115 RHS = ImpCastExprToType(RHS.get(), LHSType,
11116 CK_BlockPointerToObjCPointerCast);
11117 return computeResultTy();
11118 }
11119 }
11120 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11121 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11122 unsigned DiagID = 0;
11123 bool isError = false;
11124 if (LangOpts.DebuggerSupport) {
11125 // Under a debugger, allow the comparison of pointers to integers,
11126 // since users tend to want to compare addresses.
11127 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11128 (RHSIsNull && RHSType->isIntegerType())) {
11129 if (IsOrdered) {
11130 isError = getLangOpts().CPlusPlus;
11131 DiagID =
11132 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11133 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11134 }
11135 } else if (getLangOpts().CPlusPlus) {
11136 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11137 isError = true;
11138 } else if (IsOrdered)
11139 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11140 else
11141 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11142
11143 if (DiagID) {
11144 Diag(Loc, DiagID)
11145 << LHSType << RHSType << LHS.get()->getSourceRange()
11146 << RHS.get()->getSourceRange();
11147 if (isError)
11148 return QualType();
11149 }
11150
11151 if (LHSType->isIntegerType())
11152 LHS = ImpCastExprToType(LHS.get(), RHSType,
11153 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11154 else
11155 RHS = ImpCastExprToType(RHS.get(), LHSType,
11156 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11157 return computeResultTy();
11158 }
11159
11160 // Handle block pointers.
11161 if (!IsOrdered && RHSIsNull
11162 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11163 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11164 return computeResultTy();
11165 }
11166 if (!IsOrdered && LHSIsNull
11167 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11168 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11169 return computeResultTy();
11170 }
11171
11172 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11173 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11174 return computeResultTy();
11175 }
11176
11177 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11178 return computeResultTy();
11179 }
11180
11181 if (LHSIsNull && RHSType->isQueueT()) {
11182 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11183 return computeResultTy();
11184 }
11185
11186 if (LHSType->isQueueT() && RHSIsNull) {
11187 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11188 return computeResultTy();
11189 }
11190 }
11191
11192 return InvalidOperands(Loc, LHS, RHS);
11193 }
11194
11195 // Return a signed ext_vector_type that is of identical size and number of
11196 // elements. For floating point vectors, return an integer type of identical
11197 // size and number of elements. In the non ext_vector_type case, search from
11198 // the largest type to the smallest type to avoid cases where long long == long,
11199 // where long gets picked over long long.
11200 QualType Sema::GetSignedVectorType(QualType V) {
11201 const VectorType *VTy = V->castAs<VectorType>();
11202 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11203
11204 if (isa<ExtVectorType>(VTy)) {
11205 if (TypeSize == Context.getTypeSize(Context.CharTy))
11206 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11207 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11208 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11209 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11210 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11211 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11212 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11213 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11214 "Unhandled vector element size in vector compare");
11215 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11216 }
11217
11218 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11219 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11220 VectorType::GenericVector);
11221 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11222 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11223 VectorType::GenericVector);
11224 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11225 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11226 VectorType::GenericVector);
11227 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11228 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11229 VectorType::GenericVector);
11230 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11231 "Unhandled vector element size in vector compare");
11232 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11233 VectorType::GenericVector);
11234 }
11235
11236 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11237 /// operates on extended vector types. Instead of producing an IntTy result,
11238 /// like a scalar comparison, a vector comparison produces a vector of integer
11239 /// types.
11240 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11241 SourceLocation Loc,
11242 BinaryOperatorKind Opc) {
11243 if (Opc == BO_Cmp) {
11244 Diag(Loc, diag::err_three_way_vector_comparison);
11245 return QualType();
11246 }
11247
11248 // Check to make sure we're operating on vectors of the same type and width,
11249 // Allowing one side to be a scalar of element type.
11250 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11251 /*AllowBothBool*/true,
11252 /*AllowBoolConversions*/getLangOpts().ZVector);
11253 if (vType.isNull())
11254 return vType;
11255
11256 QualType LHSType = LHS.get()->getType();
11257
11258 // If AltiVec, the comparison results in a numeric type, i.e.
11259 // bool for C++, int for C
11260 if (getLangOpts().AltiVec &&
11261 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11262 return Context.getLogicalOperationType();
11263
11264 // For non-floating point types, check for self-comparisons of the form
11265 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11266 // often indicate logic errors in the program.
11267 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11268
11269 // Check for comparisons of floating point operands using != and ==.
11270 if (BinaryOperator::isEqualityOp(Opc) &&
11271 LHSType->hasFloatingRepresentation()) {
11272 assert(RHS.get()->getType()->hasFloatingRepresentation());
11273 CheckFloatComparison(Loc, LHS.get(), RHS.get());
11274 }
11275
11276 // Return a signed type for the vector.
11277 return GetSignedVectorType(vType);
11278 }
11279
11280 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11281 const ExprResult &XorRHS,
11282 const SourceLocation Loc) {
11283 // Do not diagnose macros.
11284 if (Loc.isMacroID())
11285 return;
11286
11287 bool Negative = false;
11288 bool ExplicitPlus = false;
11289 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11290 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11291
11292 if (!LHSInt)
11293 return;
11294 if (!RHSInt) {
11295 // Check negative literals.
11296 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11297 UnaryOperatorKind Opc = UO->getOpcode();
11298 if (Opc != UO_Minus && Opc != UO_Plus)
11299 return;
11300 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11301 if (!RHSInt)
11302 return;
11303 Negative = (Opc == UO_Minus);
11304 ExplicitPlus = !Negative;
11305 } else {
11306 return;
11307 }
11308 }
11309
11310 const llvm::APInt &LeftSideValue = LHSInt->getValue();
11311 llvm::APInt RightSideValue = RHSInt->getValue();
11312 if (LeftSideValue != 2 && LeftSideValue != 10)
11313 return;
11314
11315 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11316 return;
11317
11318 CharSourceRange ExprRange = CharSourceRange::getCharRange(
11319 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11320 llvm::StringRef ExprStr =
11321 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11322
11323 CharSourceRange XorRange =
11324 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11325 llvm::StringRef XorStr =
11326 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11327 // Do not diagnose if xor keyword/macro is used.
11328 if (XorStr == "xor")
11329 return;
11330
11331 std::string LHSStr = Lexer::getSourceText(
11332 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11333 S.getSourceManager(), S.getLangOpts());
11334 std::string RHSStr = Lexer::getSourceText(
11335 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11336 S.getSourceManager(), S.getLangOpts());
11337
11338 if (Negative) {
11339 RightSideValue = -RightSideValue;
11340 RHSStr = "-" + RHSStr;
11341 } else if (ExplicitPlus) {
11342 RHSStr = "+" + RHSStr;
11343 }
11344
11345 StringRef LHSStrRef = LHSStr;
11346 StringRef RHSStrRef = RHSStr;
11347 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11348 // literals.
11349 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11350 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11351 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11352 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11353 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11354 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11355 LHSStrRef.find('\'') != StringRef::npos ||
11356 RHSStrRef.find('\'') != StringRef::npos)
11357 return;
11358
11359 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11360 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11361 int64_t RightSideIntValue = RightSideValue.getSExtValue();
11362 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11363 std::string SuggestedExpr = "1 << " + RHSStr;
11364 bool Overflow = false;
11365 llvm::APInt One = (LeftSideValue - 1);
11366 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11367 if (Overflow) {
11368 if (RightSideIntValue < 64)
11369 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11370 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11371 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11372 else if (RightSideIntValue == 64)
11373 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11374 else
11375 return;
11376 } else {
11377 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11378 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11379 << PowValue.toString(10, true)
11380 << FixItHint::CreateReplacement(
11381 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11382 }
11383
11384 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11385 } else if (LeftSideValue == 10) {
11386 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11387 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11388 << ExprStr << XorValue.toString(10, true) << SuggestedValue
11389 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11390 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11391 }
11392 }
11393
11394 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11395 SourceLocation Loc) {
11396 // Ensure that either both operands are of the same vector type, or
11397 // one operand is of a vector type and the other is of its element type.
11398 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11399 /*AllowBothBool*/true,
11400 /*AllowBoolConversions*/false);
11401 if (vType.isNull())
11402 return InvalidOperands(Loc, LHS, RHS);
11403 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11404 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11405 return InvalidOperands(Loc, LHS, RHS);
11406 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11407 // usage of the logical operators && and || with vectors in C. This
11408 // check could be notionally dropped.
11409 if (!getLangOpts().CPlusPlus &&
11410 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11411 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11412
11413 return GetSignedVectorType(LHS.get()->getType());
11414 }
11415
11416 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11417 SourceLocation Loc,
11418 BinaryOperatorKind Opc) {
11419 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11420
11421 bool IsCompAssign =
11422 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11423
11424 if (LHS.get()->getType()->isVectorType() ||
11425 RHS.get()->getType()->isVectorType()) {
11426 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11427 RHS.get()->getType()->hasIntegerRepresentation())
11428 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11429 /*AllowBothBool*/true,
11430 /*AllowBoolConversions*/getLangOpts().ZVector);
11431 return InvalidOperands(Loc, LHS, RHS);
11432 }
11433
11434 if (Opc == BO_And)
11435 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11436
11437 if (LHS.get()->getType()->hasFloatingRepresentation() ||
11438 RHS.get()->getType()->hasFloatingRepresentation())
11439 return InvalidOperands(Loc, LHS, RHS);
11440
11441 ExprResult LHSResult = LHS, RHSResult = RHS;
11442 QualType compType = UsualArithmeticConversions(
11443 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11444 if (LHSResult.isInvalid() || RHSResult.isInvalid())
11445 return QualType();
11446 LHS = LHSResult.get();
11447 RHS = RHSResult.get();
11448
11449 if (Opc == BO_Xor)
11450 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11451
11452 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11453 return compType;
11454 return InvalidOperands(Loc, LHS, RHS);
11455 }
11456
11457 // C99 6.5.[13,14]
11458 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11459 SourceLocation Loc,
11460 BinaryOperatorKind Opc) {
11461 // Check vector operands differently.
11462 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11463 return CheckVectorLogicalOperands(LHS, RHS, Loc);
11464
11465 bool EnumConstantInBoolContext = false;
11466 for (const ExprResult &HS : {LHS, RHS}) {
11467 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11468 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11469 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11470 EnumConstantInBoolContext = true;
11471 }
11472 }
11473
11474 if (EnumConstantInBoolContext)
11475 Diag(Loc, diag::warn_enum_constant_in_bool_context);
11476
11477 // Diagnose cases where the user write a logical and/or but probably meant a
11478 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
11479 // is a constant.
11480 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11481 !LHS.get()->getType()->isBooleanType() &&
11482 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11483 // Don't warn in macros or template instantiations.
11484 !Loc.isMacroID() && !inTemplateInstantiation()) {
11485 // If the RHS can be constant folded, and if it constant folds to something
11486 // that isn't 0 or 1 (which indicate a potential logical operation that
11487 // happened to fold to true/false) then warn.
11488 // Parens on the RHS are ignored.
11489 Expr::EvalResult EVResult;
11490 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11491 llvm::APSInt Result = EVResult.Val.getInt();
11492 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11493 !RHS.get()->getExprLoc().isMacroID()) ||
11494 (Result != 0 && Result != 1)) {
11495 Diag(Loc, diag::warn_logical_instead_of_bitwise)
11496 << RHS.get()->getSourceRange()
11497 << (Opc == BO_LAnd ? "&&" : "||");
11498 // Suggest replacing the logical operator with the bitwise version
11499 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11500 << (Opc == BO_LAnd ? "&" : "|")
11501 << FixItHint::CreateReplacement(SourceRange(
11502 Loc, getLocForEndOfToken(Loc)),
11503 Opc == BO_LAnd ? "&" : "|");
11504 if (Opc == BO_LAnd)
11505 // Suggest replacing "Foo() && kNonZero" with "Foo()"
11506 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11507 << FixItHint::CreateRemoval(
11508 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11509 RHS.get()->getEndLoc()));
11510 }
11511 }
11512 }
11513
11514 if (!Context.getLangOpts().CPlusPlus) {
11515 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11516 // not operate on the built-in scalar and vector float types.
11517 if (Context.getLangOpts().OpenCL &&
11518 Context.getLangOpts().OpenCLVersion < 120) {
11519 if (LHS.get()->getType()->isFloatingType() ||
11520 RHS.get()->getType()->isFloatingType())
11521 return InvalidOperands(Loc, LHS, RHS);
11522 }
11523
11524 LHS = UsualUnaryConversions(LHS.get());
11525 if (LHS.isInvalid())
11526 return QualType();
11527
11528 RHS = UsualUnaryConversions(RHS.get());
11529 if (RHS.isInvalid())
11530 return QualType();
11531
11532 if (!LHS.get()->getType()->isScalarType() ||
11533 !RHS.get()->getType()->isScalarType())
11534 return InvalidOperands(Loc, LHS, RHS);
11535
11536 return Context.IntTy;
11537 }
11538
11539 // The following is safe because we only use this method for
11540 // non-overloadable operands.
11541
11542 // C++ [expr.log.and]p1
11543 // C++ [expr.log.or]p1
11544 // The operands are both contextually converted to type bool.
11545 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11546 if (LHSRes.isInvalid())
11547 return InvalidOperands(Loc, LHS, RHS);
11548 LHS = LHSRes;
11549
11550 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11551 if (RHSRes.isInvalid())
11552 return InvalidOperands(Loc, LHS, RHS);
11553 RHS = RHSRes;
11554
11555 // C++ [expr.log.and]p2
11556 // C++ [expr.log.or]p2
11557 // The result is a bool.
11558 return Context.BoolTy;
11559 }
11560
11561 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11562 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11563 if (!ME) return false;
11564 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11565 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11566 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11567 if (!Base) return false;
11568 return Base->getMethodDecl() != nullptr;
11569 }
11570
11571 /// Is the given expression (which must be 'const') a reference to a
11572 /// variable which was originally non-const, but which has become
11573 /// 'const' due to being captured within a block?
11574 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11575 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11576 assert(E->isLValue() && E->getType().isConstQualified());
11577 E = E->IgnoreParens();
11578
11579 // Must be a reference to a declaration from an enclosing scope.
11580 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11581 if (!DRE) return NCCK_None;
11582 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11583
11584 // The declaration must be a variable which is not declared 'const'.
11585 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11586 if (!var) return NCCK_None;
11587 if (var->getType().isConstQualified()) return NCCK_None;
11588 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11589
11590 // Decide whether the first capture was for a block or a lambda.
11591 DeclContext *DC = S.CurContext, *Prev = nullptr;
11592 // Decide whether the first capture was for a block or a lambda.
11593 while (DC) {
11594 // For init-capture, it is possible that the variable belongs to the
11595 // template pattern of the current context.
11596 if (auto *FD = dyn_cast<FunctionDecl>(DC))
11597 if (var->isInitCapture() &&
11598 FD->getTemplateInstantiationPattern() == var->getDeclContext())
11599 break;
11600 if (DC == var->getDeclContext())
11601 break;
11602 Prev = DC;
11603 DC = DC->getParent();
11604 }
11605 // Unless we have an init-capture, we've gone one step too far.
11606 if (!var->isInitCapture())
11607 DC = Prev;
11608 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11609 }
11610
11611 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11612 Ty = Ty.getNonReferenceType();
11613 if (IsDereference && Ty->isPointerType())
11614 Ty = Ty->getPointeeType();
11615 return !Ty.isConstQualified();
11616 }
11617
11618 // Update err_typecheck_assign_const and note_typecheck_assign_const
11619 // when this enum is changed.
11620 enum {
11621 ConstFunction,
11622 ConstVariable,
11623 ConstMember,
11624 ConstMethod,
11625 NestedConstMember,
11626 ConstUnknown, // Keep as last element
11627 };
11628
11629 /// Emit the "read-only variable not assignable" error and print notes to give
11630 /// more information about why the variable is not assignable, such as pointing
11631 /// to the declaration of a const variable, showing that a method is const, or
11632 /// that the function is returning a const reference.
11633 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11634 SourceLocation Loc) {
11635 SourceRange ExprRange = E->getSourceRange();
11636
11637 // Only emit one error on the first const found. All other consts will emit
11638 // a note to the error.
11639 bool DiagnosticEmitted = false;
11640
11641 // Track if the current expression is the result of a dereference, and if the
11642 // next checked expression is the result of a dereference.
11643 bool IsDereference = false;
11644 bool NextIsDereference = false;
11645
11646 // Loop to process MemberExpr chains.
11647 while (true) {
11648 IsDereference = NextIsDereference;
11649
11650 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11651 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11652 NextIsDereference = ME->isArrow();
11653 const ValueDecl *VD = ME->getMemberDecl();
11654 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11655 // Mutable fields can be modified even if the class is const.
11656 if (Field->isMutable()) {
11657 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11658 break;
11659 }
11660
11661 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11662 if (!DiagnosticEmitted) {
11663 S.Diag(Loc, diag::err_typecheck_assign_const)
11664 << ExprRange << ConstMember << false /*static*/ << Field
11665 << Field->getType();
11666 DiagnosticEmitted = true;
11667 }
11668 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11669 << ConstMember << false /*static*/ << Field << Field->getType()
11670 << Field->getSourceRange();
11671 }
11672 E = ME->getBase();
11673 continue;
11674 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11675 if (VDecl->getType().isConstQualified()) {
11676 if (!DiagnosticEmitted) {
11677 S.Diag(Loc, diag::err_typecheck_assign_const)
11678 << ExprRange << ConstMember << true /*static*/ << VDecl
11679 << VDecl->getType();
11680 DiagnosticEmitted = true;
11681 }
11682 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11683 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11684 << VDecl->getSourceRange();
11685 }
11686 // Static fields do not inherit constness from parents.
11687 break;
11688 }
11689 break; // End MemberExpr
11690 } else if (const ArraySubscriptExpr *ASE =
11691 dyn_cast<ArraySubscriptExpr>(E)) {
11692 E = ASE->getBase()->IgnoreParenImpCasts();
11693 continue;
11694 } else if (const ExtVectorElementExpr *EVE =
11695 dyn_cast<ExtVectorElementExpr>(E)) {
11696 E = EVE->getBase()->IgnoreParenImpCasts();
11697 continue;
11698 }
11699 break;
11700 }
11701
11702 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11703 // Function calls
11704 const FunctionDecl *FD = CE->getDirectCallee();
11705 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11706 if (!DiagnosticEmitted) {
11707 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11708 << ConstFunction << FD;
11709 DiagnosticEmitted = true;
11710 }
11711 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11712 diag::note_typecheck_assign_const)
11713 << ConstFunction << FD << FD->getReturnType()
11714 << FD->getReturnTypeSourceRange();
11715 }
11716 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11717 // Point to variable declaration.
11718 if (const ValueDecl *VD = DRE->getDecl()) {
11719 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11720 if (!DiagnosticEmitted) {
11721 S.Diag(Loc, diag::err_typecheck_assign_const)
11722 << ExprRange << ConstVariable << VD << VD->getType();
11723 DiagnosticEmitted = true;
11724 }
11725 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11726 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11727 }
11728 }
11729 } else if (isa<CXXThisExpr>(E)) {
11730 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11731 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11732 if (MD->isConst()) {
11733 if (!DiagnosticEmitted) {
11734 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11735 << ConstMethod << MD;
11736 DiagnosticEmitted = true;
11737 }
11738 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11739 << ConstMethod << MD << MD->getSourceRange();
11740 }
11741 }
11742 }
11743 }
11744
11745 if (DiagnosticEmitted)
11746 return;
11747
11748 // Can't determine a more specific message, so display the generic error.
11749 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11750 }
11751
11752 enum OriginalExprKind {
11753 OEK_Variable,
11754 OEK_Member,
11755 OEK_LValue
11756 };
11757
11758 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11759 const RecordType *Ty,
11760 SourceLocation Loc, SourceRange Range,
11761 OriginalExprKind OEK,
11762 bool &DiagnosticEmitted) {
11763 std::vector<const RecordType *> RecordTypeList;
11764 RecordTypeList.push_back(Ty);
11765 unsigned NextToCheckIndex = 0;
11766 // We walk the record hierarchy breadth-first to ensure that we print
11767 // diagnostics in field nesting order.
11768 while (RecordTypeList.size() > NextToCheckIndex) {
11769 bool IsNested = NextToCheckIndex > 0;
11770 for (const FieldDecl *Field :
11771 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11772 // First, check every field for constness.
11773 QualType FieldTy = Field->getType();
11774 if (FieldTy.isConstQualified()) {
11775 if (!DiagnosticEmitted) {
11776 S.Diag(Loc, diag::err_typecheck_assign_const)
11777 << Range << NestedConstMember << OEK << VD
11778 << IsNested << Field;
11779 DiagnosticEmitted = true;
11780 }
11781 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11782 << NestedConstMember << IsNested << Field
11783 << FieldTy << Field->getSourceRange();
11784 }
11785
11786 // Then we append it to the list to check next in order.
11787 FieldTy = FieldTy.getCanonicalType();
11788 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11789 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11790 RecordTypeList.push_back(FieldRecTy);
11791 }
11792 }
11793 ++NextToCheckIndex;
11794 }
11795 }
11796
11797 /// Emit an error for the case where a record we are trying to assign to has a
11798 /// const-qualified field somewhere in its hierarchy.
11799 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11800 SourceLocation Loc) {
11801 QualType Ty = E->getType();
11802 assert(Ty->isRecordType() && "lvalue was not record?");
11803 SourceRange Range = E->getSourceRange();
11804 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11805 bool DiagEmitted = false;
11806
11807 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11808 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11809 Range, OEK_Member, DiagEmitted);
11810 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11811 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11812 Range, OEK_Variable, DiagEmitted);
11813 else
11814 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11815 Range, OEK_LValue, DiagEmitted);
11816 if (!DiagEmitted)
11817 DiagnoseConstAssignment(S, E, Loc);
11818 }
11819
11820 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11821 /// emit an error and return true. If so, return false.
11822 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11823 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11824
11825 S.CheckShadowingDeclModification(E, Loc);
11826
11827 SourceLocation OrigLoc = Loc;
11828 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11829 &Loc);
11830 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11831 IsLV = Expr::MLV_InvalidMessageExpression;
11832 if (IsLV == Expr::MLV_Valid)
11833 return false;
11834
11835 unsigned DiagID = 0;
11836 bool NeedType = false;
11837 switch (IsLV) { // C99 6.5.16p2
11838 case Expr::MLV_ConstQualified:
11839 // Use a specialized diagnostic when we're assigning to an object
11840 // from an enclosing function or block.
11841 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11842 if (NCCK == NCCK_Block)
11843 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11844 else
11845 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11846 break;
11847 }
11848
11849 // In ARC, use some specialized diagnostics for occasions where we
11850 // infer 'const'. These are always pseudo-strong variables.
11851 if (S.getLangOpts().ObjCAutoRefCount) {
11852 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11853 if (declRef && isa<VarDecl>(declRef->getDecl())) {
11854 VarDecl *var = cast<VarDecl>(declRef->getDecl());
11855
11856 // Use the normal diagnostic if it's pseudo-__strong but the
11857 // user actually wrote 'const'.
11858 if (var->isARCPseudoStrong() &&
11859 (!var->getTypeSourceInfo() ||
11860 !var->getTypeSourceInfo()->getType().isConstQualified())) {
11861 // There are three pseudo-strong cases:
11862 // - self
11863 ObjCMethodDecl *method = S.getCurMethodDecl();
11864 if (method && var == method->getSelfDecl()) {
11865 DiagID = method->isClassMethod()
11866 ? diag::err_typecheck_arc_assign_self_class_method
11867 : diag::err_typecheck_arc_assign_self;
11868
11869 // - Objective-C externally_retained attribute.
11870 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11871 isa<ParmVarDecl>(var)) {
11872 DiagID = diag::err_typecheck_arc_assign_externally_retained;
11873
11874 // - fast enumeration variables
11875 } else {
11876 DiagID = diag::err_typecheck_arr_assign_enumeration;
11877 }
11878
11879 SourceRange Assign;
11880 if (Loc != OrigLoc)
11881 Assign = SourceRange(OrigLoc, OrigLoc);
11882 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11883 // We need to preserve the AST regardless, so migration tool
11884 // can do its job.
11885 return false;
11886 }
11887 }
11888 }
11889
11890 // If none of the special cases above are triggered, then this is a
11891 // simple const assignment.
11892 if (DiagID == 0) {
11893 DiagnoseConstAssignment(S, E, Loc);
11894 return true;
11895 }
11896
11897 break;
11898 case Expr::MLV_ConstAddrSpace:
11899 DiagnoseConstAssignment(S, E, Loc);
11900 return true;
11901 case Expr::MLV_ConstQualifiedField:
11902 DiagnoseRecursiveConstFields(S, E, Loc);
11903 return true;
11904 case Expr::MLV_ArrayType:
11905 case Expr::MLV_ArrayTemporary:
11906 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11907 NeedType = true;
11908 break;
11909 case Expr::MLV_NotObjectType:
11910 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11911 NeedType = true;
11912 break;
11913 case Expr::MLV_LValueCast:
11914 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11915 break;
11916 case Expr::MLV_Valid:
11917 llvm_unreachable("did not take early return for MLV_Valid");
11918 case Expr::MLV_InvalidExpression:
11919 case Expr::MLV_MemberFunction:
11920 case Expr::MLV_ClassTemporary:
11921 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11922 break;
11923 case Expr::MLV_IncompleteType:
11924 case Expr::MLV_IncompleteVoidType:
11925 return S.RequireCompleteType(Loc, E->getType(),
11926 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11927 case Expr::MLV_DuplicateVectorComponents:
11928 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11929 break;
11930 case Expr::MLV_NoSetterProperty:
11931 llvm_unreachable("readonly properties should be processed differently");
11932 case Expr::MLV_InvalidMessageExpression:
11933 DiagID = diag::err_readonly_message_assignment;
11934 break;
11935 case Expr::MLV_SubObjCPropertySetting:
11936 DiagID = diag::err_no_subobject_property_setting;
11937 break;
11938 }
11939
11940 SourceRange Assign;
11941 if (Loc != OrigLoc)
11942 Assign = SourceRange(OrigLoc, OrigLoc);
11943 if (NeedType)
11944 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11945 else
11946 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11947 return true;
11948 }
11949
11950 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11951 SourceLocation Loc,
11952 Sema &Sema) {
11953 if (Sema.inTemplateInstantiation())
11954 return;
11955 if (Sema.isUnevaluatedContext())
11956 return;
11957 if (Loc.isInvalid() || Loc.isMacroID())
11958 return;
11959 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11960 return;
11961
11962 // C / C++ fields
11963 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11964 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11965 if (ML && MR) {
11966 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11967 return;
11968 const ValueDecl *LHSDecl =
11969 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11970 const ValueDecl *RHSDecl =
11971 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11972 if (LHSDecl != RHSDecl)
11973 return;
11974 if (LHSDecl->getType().isVolatileQualified())
11975 return;
11976 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11977 if (RefTy->getPointeeType().isVolatileQualified())
11978 return;
11979
11980 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11981 }
11982
11983 // Objective-C instance variables
11984 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11985 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11986 if (OL && OR && OL->getDecl() == OR->getDecl()) {
11987 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11988 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11989 if (RL && RR && RL->getDecl() == RR->getDecl())
11990 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11991 }
11992 }
11993
11994 // C99 6.5.16.1
11995 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11996 SourceLocation Loc,
11997 QualType CompoundType) {
11998 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11999
12000 // Verify that LHS is a modifiable lvalue, and emit error if not.
12001 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12002 return QualType();
12003
12004 QualType LHSType = LHSExpr->getType();
12005 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12006 CompoundType;
12007 // OpenCL v1.2 s6.1.1.1 p2:
12008 // The half data type can only be used to declare a pointer to a buffer that
12009 // contains half values
12010 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12011 LHSType->isHalfType()) {
12012 Diag(Loc, diag::err_opencl_half_load_store) << 1
12013 << LHSType.getUnqualifiedType();
12014 return QualType();
12015 }
12016
12017 AssignConvertType ConvTy;
12018 if (CompoundType.isNull()) {
12019 Expr *RHSCheck = RHS.get();
12020
12021 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12022
12023 QualType LHSTy(LHSType);
12024 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12025 if (RHS.isInvalid())
12026 return QualType();
12027 // Special case of NSObject attributes on c-style pointer types.
12028 if (ConvTy == IncompatiblePointer &&
12029 ((Context.isObjCNSObjectType(LHSType) &&
12030 RHSType->isObjCObjectPointerType()) ||
12031 (Context.isObjCNSObjectType(RHSType) &&
12032 LHSType->isObjCObjectPointerType())))
12033 ConvTy = Compatible;
12034
12035 if (ConvTy == Compatible &&
12036 LHSType->isObjCObjectType())
12037 Diag(Loc, diag::err_objc_object_assignment)
12038 << LHSType;
12039
12040 // If the RHS is a unary plus or minus, check to see if they = and + are
12041 // right next to each other. If so, the user may have typo'd "x =+ 4"
12042 // instead of "x += 4".
12043 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12044 RHSCheck = ICE->getSubExpr();
12045 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12046 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12047 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12048 // Only if the two operators are exactly adjacent.
12049 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12050 // And there is a space or other character before the subexpr of the
12051 // unary +/-. We don't want to warn on "x=-1".
12052 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12053 UO->getSubExpr()->getBeginLoc().isFileID()) {
12054 Diag(Loc, diag::warn_not_compound_assign)
12055 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12056 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12057 }
12058 }
12059
12060 if (ConvTy == Compatible) {
12061 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12062 // Warn about retain cycles where a block captures the LHS, but
12063 // not if the LHS is a simple variable into which the block is
12064 // being stored...unless that variable can be captured by reference!
12065 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12066 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12067 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12068 checkRetainCycles(LHSExpr, RHS.get());
12069 }
12070
12071 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12072 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12073 // It is safe to assign a weak reference into a strong variable.
12074 // Although this code can still have problems:
12075 // id x = self.weakProp;
12076 // id y = self.weakProp;
12077 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12078 // paths through the function. This should be revisited if
12079 // -Wrepeated-use-of-weak is made flow-sensitive.
12080 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12081 // variable, which will be valid for the current autorelease scope.
12082 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12083 RHS.get()->getBeginLoc()))
12084 getCurFunction()->markSafeWeakUse(RHS.get());
12085
12086 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12087 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12088 }
12089 }
12090 } else {
12091 // Compound assignment "x += y"
12092 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12093 }
12094
12095 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12096 RHS.get(), AA_Assigning))
12097 return QualType();
12098
12099 CheckForNullPointerDereference(*this, LHSExpr);
12100
12101 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12102 if (CompoundType.isNull()) {
12103 // C++2a [expr.ass]p5:
12104 // A simple-assignment whose left operand is of a volatile-qualified
12105 // type is deprecated unless the assignment is either a discarded-value
12106 // expression or an unevaluated operand
12107 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12108 } else {
12109 // C++2a [expr.ass]p6:
12110 // [Compound-assignment] expressions are deprecated if E1 has
12111 // volatile-qualified type
12112 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12113 }
12114 }
12115
12116 // C99 6.5.16p3: The type of an assignment expression is the type of the
12117 // left operand unless the left operand has qualified type, in which case
12118 // it is the unqualified version of the type of the left operand.
12119 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12120 // is converted to the type of the assignment expression (above).
12121 // C++ 5.17p1: the type of the assignment expression is that of its left
12122 // operand.
12123 return (getLangOpts().CPlusPlus
12124 ? LHSType : LHSType.getUnqualifiedType());
12125 }
12126
12127 // Only ignore explicit casts to void.
12128 static bool IgnoreCommaOperand(const Expr *E) {
12129 E = E->IgnoreParens();
12130
12131 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12132 if (CE->getCastKind() == CK_ToVoid) {
12133 return true;
12134 }
12135
12136 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12137 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12138 CE->getSubExpr()->getType()->isDependentType()) {
12139 return true;
12140 }
12141 }
12142
12143 return false;
12144 }
12145
12146 // Look for instances where it is likely the comma operator is confused with
12147 // another operator. There is a whitelist of acceptable expressions for the
12148 // left hand side of the comma operator, otherwise emit a warning.
12149 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12150 // No warnings in macros
12151 if (Loc.isMacroID())
12152 return;
12153
12154 // Don't warn in template instantiations.
12155 if (inTemplateInstantiation())
12156 return;
12157
12158 // Scope isn't fine-grained enough to whitelist the specific cases, so
12159 // instead, skip more than needed, then call back into here with the
12160 // CommaVisitor in SemaStmt.cpp.
12161 // The whitelisted locations are the initialization and increment portions
12162 // of a for loop. The additional checks are on the condition of
12163 // if statements, do/while loops, and for loops.
12164 // Differences in scope flags for C89 mode requires the extra logic.
12165 const unsigned ForIncrementFlags =
12166 getLangOpts().C99 || getLangOpts().CPlusPlus
12167 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12168 : Scope::ContinueScope | Scope::BreakScope;
12169 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12170 const unsigned ScopeFlags = getCurScope()->getFlags();
12171 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12172 (ScopeFlags & ForInitFlags) == ForInitFlags)
12173 return;
12174
12175 // If there are multiple comma operators used together, get the RHS of the
12176 // of the comma operator as the LHS.
12177 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12178 if (BO->getOpcode() != BO_Comma)
12179 break;
12180 LHS = BO->getRHS();
12181 }
12182
12183 // Only allow some expressions on LHS to not warn.
12184 if (IgnoreCommaOperand(LHS))
12185 return;
12186
12187 Diag(Loc, diag::warn_comma_operator);
12188 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12189 << LHS->getSourceRange()
12190 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12191 LangOpts.CPlusPlus ? "static_cast<void>("
12192 : "(void)(")
12193 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12194 ")");
12195 }
12196
12197 // C99 6.5.17
12198 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12199 SourceLocation Loc) {
12200 LHS = S.CheckPlaceholderExpr(LHS.get());
12201 RHS = S.CheckPlaceholderExpr(RHS.get());
12202 if (LHS.isInvalid() || RHS.isInvalid())
12203 return QualType();
12204
12205 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12206 // operands, but not unary promotions.
12207 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12208
12209 // So we treat the LHS as a ignored value, and in C++ we allow the
12210 // containing site to determine what should be done with the RHS.
12211 LHS = S.IgnoredValueConversions(LHS.get());
12212 if (LHS.isInvalid())
12213 return QualType();
12214
12215 S.DiagnoseUnusedExprResult(LHS.get());
12216
12217 if (!S.getLangOpts().CPlusPlus) {
12218 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12219 if (RHS.isInvalid())
12220 return QualType();
12221 if (!RHS.get()->getType()->isVoidType())
12222 S.RequireCompleteType(Loc, RHS.get()->getType(),
12223 diag::err_incomplete_type);
12224 }
12225
12226 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12227 S.DiagnoseCommaOperator(LHS.get(), Loc);
12228
12229 return RHS.get()->getType();
12230 }
12231
12232 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12233 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12234 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12235 ExprValueKind &VK,
12236 ExprObjectKind &OK,
12237 SourceLocation OpLoc,
12238 bool IsInc, bool IsPrefix) {
12239 if (Op->isTypeDependent())
12240 return S.Context.DependentTy;
12241
12242 QualType ResType = Op->getType();
12243 // Atomic types can be used for increment / decrement where the non-atomic
12244 // versions can, so ignore the _Atomic() specifier for the purpose of
12245 // checking.
12246 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12247 ResType = ResAtomicType->getValueType();
12248
12249 assert(!ResType.isNull() && "no type for increment/decrement expression");
12250
12251 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12252 // Decrement of bool is not allowed.
12253 if (!IsInc) {
12254 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12255 return QualType();
12256 }
12257 // Increment of bool sets it to true, but is deprecated.
12258 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12259 : diag::warn_increment_bool)
12260 << Op->getSourceRange();
12261 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12262 // Error on enum increments and decrements in C++ mode
12263 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12264 return QualType();
12265 } else if (ResType->isRealType()) {
12266 // OK!
12267 } else if (ResType->isPointerType()) {
12268 // C99 6.5.2.4p2, 6.5.6p2
12269 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12270 return QualType();
12271 } else if (ResType->isObjCObjectPointerType()) {
12272 // On modern runtimes, ObjC pointer arithmetic is forbidden.
12273 // Otherwise, we just need a complete type.
12274 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12275 checkArithmeticOnObjCPointer(S, OpLoc, Op))
12276 return QualType();
12277 } else if (ResType->isAnyComplexType()) {
12278 // C99 does not support ++/-- on complex types, we allow as an extension.
12279 S.Diag(OpLoc, diag::ext_integer_increment_complex)
12280 << ResType << Op->getSourceRange();
12281 } else if (ResType->isPlaceholderType()) {
12282 ExprResult PR = S.CheckPlaceholderExpr(Op);
12283 if (PR.isInvalid()) return QualType();
12284 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12285 IsInc, IsPrefix);
12286 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12287 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12288 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12289 (ResType->castAs<VectorType>()->getVectorKind() !=
12290 VectorType::AltiVecBool)) {
12291 // The z vector extensions allow ++ and -- for non-bool vectors.
12292 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12293 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12294 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12295 } else {
12296 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12297 << ResType << int(IsInc) << Op->getSourceRange();
12298 return QualType();
12299 }
12300 // At this point, we know we have a real, complex or pointer type.
12301 // Now make sure the operand is a modifiable lvalue.
12302 if (CheckForModifiableLvalue(Op, OpLoc, S))
12303 return QualType();
12304 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12305 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12306 // An operand with volatile-qualified type is deprecated
12307 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12308 << IsInc << ResType;
12309 }
12310 // In C++, a prefix increment is the same type as the operand. Otherwise
12311 // (in C or with postfix), the increment is the unqualified type of the
12312 // operand.
12313 if (IsPrefix && S.getLangOpts().CPlusPlus) {
12314 VK = VK_LValue;
12315 OK = Op->getObjectKind();
12316 return ResType;
12317 } else {
12318 VK = VK_RValue;
12319 return ResType.getUnqualifiedType();
12320 }
12321 }
12322
12323
12324 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12325 /// This routine allows us to typecheck complex/recursive expressions
12326 /// where the declaration is needed for type checking. We only need to
12327 /// handle cases when the expression references a function designator
12328 /// or is an lvalue. Here are some examples:
12329 /// - &(x) => x
12330 /// - &*****f => f for f a function designator.
12331 /// - &s.xx => s
12332 /// - &s.zz[1].yy -> s, if zz is an array
12333 /// - *(x + 1) -> x, if x is an array
12334 /// - &"123"[2] -> 0
12335 /// - & __real__ x -> x
12336 static ValueDecl *getPrimaryDecl(Expr *E) {
12337 switch (E->getStmtClass()) {
12338 case Stmt::DeclRefExprClass:
12339 return cast<DeclRefExpr>(E)->getDecl();
12340 case Stmt::MemberExprClass:
12341 // If this is an arrow operator, the address is an offset from
12342 // the base's value, so the object the base refers to is
12343 // irrelevant.
12344 if (cast<MemberExpr>(E)->isArrow())
12345 return nullptr;
12346 // Otherwise, the expression refers to a part of the base
12347 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12348 case Stmt::ArraySubscriptExprClass: {
12349 // FIXME: This code shouldn't be necessary! We should catch the implicit
12350 // promotion of register arrays earlier.
12351 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12352 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12353 if (ICE->getSubExpr()->getType()->isArrayType())
12354 return getPrimaryDecl(ICE->getSubExpr());
12355 }
12356 return nullptr;
12357 }
12358 case Stmt::UnaryOperatorClass: {
12359 UnaryOperator *UO = cast<UnaryOperator>(E);
12360
12361 switch(UO->getOpcode()) {
12362 case UO_Real:
12363 case UO_Imag:
12364 case UO_Extension:
12365 return getPrimaryDecl(UO->getSubExpr());
12366 default:
12367 return nullptr;
12368 }
12369 }
12370 case Stmt::ParenExprClass:
12371 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12372 case Stmt::ImplicitCastExprClass:
12373 // If the result of an implicit cast is an l-value, we care about
12374 // the sub-expression; otherwise, the result here doesn't matter.
12375 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12376 default:
12377 return nullptr;
12378 }
12379 }
12380
12381 namespace {
12382 enum {
12383 AO_Bit_Field = 0,
12384 AO_Vector_Element = 1,
12385 AO_Property_Expansion = 2,
12386 AO_Register_Variable = 3,
12387 AO_No_Error = 4
12388 };
12389 }
12390 /// Diagnose invalid operand for address of operations.
12391 ///
12392 /// \param Type The type of operand which cannot have its address taken.
12393 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12394 Expr *E, unsigned Type) {
12395 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12396 }
12397
12398 /// CheckAddressOfOperand - The operand of & must be either a function
12399 /// designator or an lvalue designating an object. If it is an lvalue, the
12400 /// object cannot be declared with storage class register or be a bit field.
12401 /// Note: The usual conversions are *not* applied to the operand of the &
12402 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12403 /// In C++, the operand might be an overloaded function name, in which case
12404 /// we allow the '&' but retain the overloaded-function type.
12405 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12406 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12407 if (PTy->getKind() == BuiltinType::Overload) {
12408 Expr *E = OrigOp.get()->IgnoreParens();
12409 if (!isa<OverloadExpr>(E)) {
12410 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12411 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12412 << OrigOp.get()->getSourceRange();
12413 return QualType();
12414 }
12415
12416 OverloadExpr *Ovl = cast<OverloadExpr>(E);
12417 if (isa<UnresolvedMemberExpr>(Ovl))
12418 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12419 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12420 << OrigOp.get()->getSourceRange();
12421 return QualType();
12422 }
12423
12424 return Context.OverloadTy;
12425 }
12426
12427 if (PTy->getKind() == BuiltinType::UnknownAny)
12428 return Context.UnknownAnyTy;
12429
12430 if (PTy->getKind() == BuiltinType::BoundMember) {
12431 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12432 << OrigOp.get()->getSourceRange();
12433 return QualType();
12434 }
12435
12436 OrigOp = CheckPlaceholderExpr(OrigOp.get());
12437 if (OrigOp.isInvalid()) return QualType();
12438 }
12439
12440 if (OrigOp.get()->isTypeDependent())
12441 return Context.DependentTy;
12442
12443 assert(!OrigOp.get()->getType()->isPlaceholderType());
12444
12445 // Make sure to ignore parentheses in subsequent checks
12446 Expr *op = OrigOp.get()->IgnoreParens();
12447
12448 // In OpenCL captures for blocks called as lambda functions
12449 // are located in the private address space. Blocks used in
12450 // enqueue_kernel can be located in a different address space
12451 // depending on a vendor implementation. Thus preventing
12452 // taking an address of the capture to avoid invalid AS casts.
12453 if (LangOpts.OpenCL) {
12454 auto* VarRef = dyn_cast<DeclRefExpr>(op);
12455 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12456 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12457 return QualType();
12458 }
12459 }
12460
12461 if (getLangOpts().C99) {
12462 // Implement C99-only parts of addressof rules.
12463 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12464 if (uOp->getOpcode() == UO_Deref)
12465 // Per C99 6.5.3.2, the address of a deref always returns a valid result
12466 // (assuming the deref expression is valid).
12467 return uOp->getSubExpr()->getType();
12468 }
12469 // Technically, there should be a check for array subscript
12470 // expressions here, but the result of one is always an lvalue anyway.
12471 }
12472 ValueDecl *dcl = getPrimaryDecl(op);
12473
12474 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12475 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12476 op->getBeginLoc()))
12477 return QualType();
12478
12479 Expr::LValueClassification lval = op->ClassifyLValue(Context);
12480 unsigned AddressOfError = AO_No_Error;
12481
12482 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12483 bool sfinae = (bool)isSFINAEContext();
12484 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12485 : diag::ext_typecheck_addrof_temporary)
12486 << op->getType() << op->getSourceRange();
12487 if (sfinae)
12488 return QualType();
12489 // Materialize the temporary as an lvalue so that we can take its address.
12490 OrigOp = op =
12491 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12492 } else if (isa<ObjCSelectorExpr>(op)) {
12493 return Context.getPointerType(op->getType());
12494 } else if (lval == Expr::LV_MemberFunction) {
12495 // If it's an instance method, make a member pointer.
12496 // The expression must have exactly the form &A::foo.
12497
12498 // If the underlying expression isn't a decl ref, give up.
12499 if (!isa<DeclRefExpr>(op)) {
12500 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12501 << OrigOp.get()->getSourceRange();
12502 return QualType();
12503 }
12504 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12505 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12506
12507 // The id-expression was parenthesized.
12508 if (OrigOp.get() != DRE) {
12509 Diag(OpLoc, diag::err_parens_pointer_member_function)
12510 << OrigOp.get()->getSourceRange();
12511
12512 // The method was named without a qualifier.
12513 } else if (!DRE->getQualifier()) {
12514 if (MD->getParent()->getName().empty())
12515 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12516 << op->getSourceRange();
12517 else {
12518 SmallString<32> Str;
12519 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12520 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12521 << op->getSourceRange()
12522 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12523 }
12524 }
12525
12526 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12527 if (isa<CXXDestructorDecl>(MD))
12528 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12529
12530 QualType MPTy = Context.getMemberPointerType(
12531 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12532 // Under the MS ABI, lock down the inheritance model now.
12533 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12534 (void)isCompleteType(OpLoc, MPTy);
12535 return MPTy;
12536 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12537 // C99 6.5.3.2p1
12538 // The operand must be either an l-value or a function designator
12539 if (!op->getType()->isFunctionType()) {
12540 // Use a special diagnostic for loads from property references.
12541 if (isa<PseudoObjectExpr>(op)) {
12542 AddressOfError = AO_Property_Expansion;
12543 } else {
12544 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12545 << op->getType() << op->getSourceRange();
12546 return QualType();
12547 }
12548 }
12549 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12550 // The operand cannot be a bit-field
12551 AddressOfError = AO_Bit_Field;
12552 } else if (op->getObjectKind() == OK_VectorComponent) {
12553 // The operand cannot be an element of a vector
12554 AddressOfError = AO_Vector_Element;
12555 } else if (dcl) { // C99 6.5.3.2p1
12556 // We have an lvalue with a decl. Make sure the decl is not declared
12557 // with the register storage-class specifier.
12558 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12559 // in C++ it is not error to take address of a register
12560 // variable (c++03 7.1.1P3)
12561 if (vd->getStorageClass() == SC_Register &&
12562 !getLangOpts().CPlusPlus) {
12563 AddressOfError = AO_Register_Variable;
12564 }
12565 } else if (isa<MSPropertyDecl>(dcl)) {
12566 AddressOfError = AO_Property_Expansion;
12567 } else if (isa<FunctionTemplateDecl>(dcl)) {
12568 return Context.OverloadTy;
12569 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12570 // Okay: we can take the address of a field.
12571 // Could be a pointer to member, though, if there is an explicit
12572 // scope qualifier for the class.
12573 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12574 DeclContext *Ctx = dcl->getDeclContext();
12575 if (Ctx && Ctx->isRecord()) {
12576 if (dcl->getType()->isReferenceType()) {
12577 Diag(OpLoc,
12578 diag::err_cannot_form_pointer_to_member_of_reference_type)
12579 << dcl->getDeclName() << dcl->getType();
12580 return QualType();
12581 }
12582
12583 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12584 Ctx = Ctx->getParent();
12585
12586 QualType MPTy = Context.getMemberPointerType(
12587 op->getType(),
12588 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12589 // Under the MS ABI, lock down the inheritance model now.
12590 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12591 (void)isCompleteType(OpLoc, MPTy);
12592 return MPTy;
12593 }
12594 }
12595 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12596 !isa<BindingDecl>(dcl))
12597 llvm_unreachable("Unknown/unexpected decl type");
12598 }
12599
12600 if (AddressOfError != AO_No_Error) {
12601 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12602 return QualType();
12603 }
12604
12605 if (lval == Expr::LV_IncompleteVoidType) {
12606 // Taking the address of a void variable is technically illegal, but we
12607 // allow it in cases which are otherwise valid.
12608 // Example: "extern void x; void* y = &x;".
12609 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12610 }
12611
12612 // If the operand has type "type", the result has type "pointer to type".
12613 if (op->getType()->isObjCObjectType())
12614 return Context.getObjCObjectPointerType(op->getType());
12615
12616 CheckAddressOfPackedMember(op);
12617
12618 return Context.getPointerType(op->getType());
12619 }
12620
12621 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12622 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12623 if (!DRE)
12624 return;
12625 const Decl *D = DRE->getDecl();
12626 if (!D)
12627 return;
12628 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12629 if (!Param)
12630 return;
12631 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12632 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12633 return;
12634 if (FunctionScopeInfo *FD = S.getCurFunction())
12635 if (!FD->ModifiedNonNullParams.count(Param))
12636 FD->ModifiedNonNullParams.insert(Param);
12637 }
12638
12639 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12640 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12641 SourceLocation OpLoc) {
12642 if (Op->isTypeDependent())
12643 return S.Context.DependentTy;
12644
12645 ExprResult ConvResult = S.UsualUnaryConversions(Op);
12646 if (ConvResult.isInvalid())
12647 return QualType();
12648 Op = ConvResult.get();
12649 QualType OpTy = Op->getType();
12650 QualType Result;
12651
12652 if (isa<CXXReinterpretCastExpr>(Op)) {
12653 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12654 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12655 Op->getSourceRange());
12656 }
12657
12658 if (const PointerType *PT = OpTy->getAs<PointerType>())
12659 {
12660 Result = PT->getPointeeType();
12661 }
12662 else if (const ObjCObjectPointerType *OPT =
12663 OpTy->getAs<ObjCObjectPointerType>())
12664 Result = OPT->getPointeeType();
12665 else {
12666 ExprResult PR = S.CheckPlaceholderExpr(Op);
12667 if (PR.isInvalid()) return QualType();
12668 if (PR.get() != Op)
12669 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12670 }
12671
12672 if (Result.isNull()) {
12673 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12674 << OpTy << Op->getSourceRange();
12675 return QualType();
12676 }
12677
12678 // Note that per both C89 and C99, indirection is always legal, even if Result
12679 // is an incomplete type or void. It would be possible to warn about
12680 // dereferencing a void pointer, but it's completely well-defined, and such a
12681 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12682 // for pointers to 'void' but is fine for any other pointer type:
12683 //
12684 // C++ [expr.unary.op]p1:
12685 // [...] the expression to which [the unary * operator] is applied shall
12686 // be a pointer to an object type, or a pointer to a function type
12687 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12688 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12689 << OpTy << Op->getSourceRange();
12690
12691 // Dereferences are usually l-values...
12692 VK = VK_LValue;
12693
12694 // ...except that certain expressions are never l-values in C.
12695 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12696 VK = VK_RValue;
12697
12698 return Result;
12699 }
12700
12701 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12702 BinaryOperatorKind Opc;
12703 switch (Kind) {
12704 default: llvm_unreachable("Unknown binop!");
12705 case tok::periodstar: Opc = BO_PtrMemD; break;
12706 case tok::arrowstar: Opc = BO_PtrMemI; break;
12707 case tok::star: Opc = BO_Mul; break;
12708 case tok::slash: Opc = BO_Div; break;
12709 case tok::percent: Opc = BO_Rem; break;
12710 case tok::plus: Opc = BO_Add; break;
12711 case tok::minus: Opc = BO_Sub; break;
12712 case tok::lessless: Opc = BO_Shl; break;
12713 case tok::greatergreater: Opc = BO_Shr; break;
12714 case tok::lessequal: Opc = BO_LE; break;
12715 case tok::less: Opc = BO_LT; break;
12716 case tok::greaterequal: Opc = BO_GE; break;
12717 case tok::greater: Opc = BO_GT; break;
12718 case tok::exclaimequal: Opc = BO_NE; break;
12719 case tok::equalequal: Opc = BO_EQ; break;
12720 case tok::spaceship: Opc = BO_Cmp; break;
12721 case tok::amp: Opc = BO_And; break;
12722 case tok::caret: Opc = BO_Xor; break;
12723 case tok::pipe: Opc = BO_Or; break;
12724 case tok::ampamp: Opc = BO_LAnd; break;
12725 case tok::pipepipe: Opc = BO_LOr; break;
12726 case tok::equal: Opc = BO_Assign; break;
12727 case tok::starequal: Opc = BO_MulAssign; break;
12728 case tok::slashequal: Opc = BO_DivAssign; break;
12729 case tok::percentequal: Opc = BO_RemAssign; break;
12730 case tok::plusequal: Opc = BO_AddAssign; break;
12731 case tok::minusequal: Opc = BO_SubAssign; break;
12732 case tok::lesslessequal: Opc = BO_ShlAssign; break;
12733 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12734 case tok::ampequal: Opc = BO_AndAssign; break;
12735 case tok::caretequal: Opc = BO_XorAssign; break;
12736 case tok::pipeequal: Opc = BO_OrAssign; break;
12737 case tok::comma: Opc = BO_Comma; break;
12738 }
12739 return Opc;
12740 }
12741
12742 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12743 tok::TokenKind Kind) {
12744 UnaryOperatorKind Opc;
12745 switch (Kind) {
12746 default: llvm_unreachable("Unknown unary op!");
12747 case tok::plusplus: Opc = UO_PreInc; break;
12748 case tok::minusminus: Opc = UO_PreDec; break;
12749 case tok::amp: Opc = UO_AddrOf; break;
12750 case tok::star: Opc = UO_Deref; break;
12751 case tok::plus: Opc = UO_Plus; break;
12752 case tok::minus: Opc = UO_Minus; break;
12753 case tok::tilde: Opc = UO_Not; break;
12754 case tok::exclaim: Opc = UO_LNot; break;
12755 case tok::kw___real: Opc = UO_Real; break;
12756 case tok::kw___imag: Opc = UO_Imag; break;
12757 case tok::kw___extension__: Opc = UO_Extension; break;
12758 }
12759 return Opc;
12760 }
12761
12762 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12763 /// This warning suppressed in the event of macro expansions.
12764 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12765 SourceLocation OpLoc, bool IsBuiltin) {
12766 if (S.inTemplateInstantiation())
12767 return;
12768 if (S.isUnevaluatedContext())
12769 return;
12770 if (OpLoc.isInvalid() || OpLoc.isMacroID())
12771 return;
12772 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12773 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12774 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12775 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12776 if (!LHSDeclRef || !RHSDeclRef ||
12777 LHSDeclRef->getLocation().isMacroID() ||
12778 RHSDeclRef->getLocation().isMacroID())
12779 return;
12780 const ValueDecl *LHSDecl =
12781 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12782 const ValueDecl *RHSDecl =
12783 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12784 if (LHSDecl != RHSDecl)
12785 return;
12786 if (LHSDecl->getType().isVolatileQualified())
12787 return;
12788 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12789 if (RefTy->getPointeeType().isVolatileQualified())
12790 return;
12791
12792 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12793 : diag::warn_self_assignment_overloaded)
12794 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12795 << RHSExpr->getSourceRange();
12796 }
12797
12798 /// Check if a bitwise-& is performed on an Objective-C pointer. This
12799 /// is usually indicative of introspection within the Objective-C pointer.
12800 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12801 SourceLocation OpLoc) {
12802 if (!S.getLangOpts().ObjC)
12803 return;
12804
12805 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12806 const Expr *LHS = L.get();
12807 const Expr *RHS = R.get();
12808
12809 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12810 ObjCPointerExpr = LHS;
12811 OtherExpr = RHS;
12812 }
12813 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12814 ObjCPointerExpr = RHS;
12815 OtherExpr = LHS;
12816 }
12817
12818 // This warning is deliberately made very specific to reduce false
12819 // positives with logic that uses '&' for hashing. This logic mainly
12820 // looks for code trying to introspect into tagged pointers, which
12821 // code should generally never do.
12822 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12823 unsigned Diag = diag::warn_objc_pointer_masking;
12824 // Determine if we are introspecting the result of performSelectorXXX.
12825 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12826 // Special case messages to -performSelector and friends, which
12827 // can return non-pointer values boxed in a pointer value.
12828 // Some clients may wish to silence warnings in this subcase.
12829 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12830 Selector S = ME->getSelector();
12831 StringRef SelArg0 = S.getNameForSlot(0);
12832 if (SelArg0.startswith("performSelector"))
12833 Diag = diag::warn_objc_pointer_masking_performSelector;
12834 }
12835
12836 S.Diag(OpLoc, Diag)
12837 << ObjCPointerExpr->getSourceRange();
12838 }
12839 }
12840
12841 static NamedDecl *getDeclFromExpr(Expr *E) {
12842 if (!E)
12843 return nullptr;
12844 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12845 return DRE->getDecl();
12846 if (auto *ME = dyn_cast<MemberExpr>(E))
12847 return ME->getMemberDecl();
12848 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12849 return IRE->getDecl();
12850 return nullptr;
12851 }
12852
12853 // This helper function promotes a binary operator's operands (which are of a
12854 // half vector type) to a vector of floats and then truncates the result to
12855 // a vector of either half or short.
12856 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12857 BinaryOperatorKind Opc, QualType ResultTy,
12858 ExprValueKind VK, ExprObjectKind OK,
12859 bool IsCompAssign, SourceLocation OpLoc,
12860 FPOptions FPFeatures) {
12861 auto &Context = S.getASTContext();
12862 assert((isVector(ResultTy, Context.HalfTy) ||
12863 isVector(ResultTy, Context.ShortTy)) &&
12864 "Result must be a vector of half or short");
12865 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12866 isVector(RHS.get()->getType(), Context.HalfTy) &&
12867 "both operands expected to be a half vector");
12868
12869 RHS = convertVector(RHS.get(), Context.FloatTy, S);
12870 QualType BinOpResTy = RHS.get()->getType();
12871
12872 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12873 // change BinOpResTy to a vector of ints.
12874 if (isVector(ResultTy, Context.ShortTy))
12875 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12876
12877 if (IsCompAssign)
12878 return new (Context) CompoundAssignOperator(
12879 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12880 OpLoc, FPFeatures);
12881
12882 LHS = convertVector(LHS.get(), Context.FloatTy, S);
12883 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12884 VK, OK, OpLoc, FPFeatures);
12885 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12886 }
12887
12888 static std::pair<ExprResult, ExprResult>
12889 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12890 Expr *RHSExpr) {
12891 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12892 if (!S.getLangOpts().CPlusPlus) {
12893 // C cannot handle TypoExpr nodes on either side of a binop because it
12894 // doesn't handle dependent types properly, so make sure any TypoExprs have
12895 // been dealt with before checking the operands.
12896 LHS = S.CorrectDelayedTyposInExpr(LHS);
12897 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12898 if (Opc != BO_Assign)
12899 return ExprResult(E);
12900 // Avoid correcting the RHS to the same Expr as the LHS.
12901 Decl *D = getDeclFromExpr(E);
12902 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12903 });
12904 }
12905 return std::make_pair(LHS, RHS);
12906 }
12907
12908 /// Returns true if conversion between vectors of halfs and vectors of floats
12909 /// is needed.
12910 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12911 QualType SrcType) {
12912 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12913 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12914 isVector(SrcType, Ctx.HalfTy);
12915 }
12916
12917 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12918 /// operator @p Opc at location @c TokLoc. This routine only supports
12919 /// built-in operations; ActOnBinOp handles overloaded operators.
12920 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12921 BinaryOperatorKind Opc,
12922 Expr *LHSExpr, Expr *RHSExpr) {
12923 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12924 // The syntax only allows initializer lists on the RHS of assignment,
12925 // so we don't need to worry about accepting invalid code for
12926 // non-assignment operators.
12927 // C++11 5.17p9:
12928 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12929 // of x = {} is x = T().
12930 InitializationKind Kind = InitializationKind::CreateDirectList(
12931 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12932 InitializedEntity Entity =
12933 InitializedEntity::InitializeTemporary(LHSExpr->getType());
12934 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12935 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12936 if (Init.isInvalid())
12937 return Init;
12938 RHSExpr = Init.get();
12939 }
12940
12941 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12942 QualType ResultTy; // Result type of the binary operator.
12943 // The following two variables are used for compound assignment operators
12944 QualType CompLHSTy; // Type of LHS after promotions for computation
12945 QualType CompResultTy; // Type of computation result
12946 ExprValueKind VK = VK_RValue;
12947 ExprObjectKind OK = OK_Ordinary;
12948 bool ConvertHalfVec = false;
12949
12950 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12951 if (!LHS.isUsable() || !RHS.isUsable())
12952 return ExprError();
12953
12954 if (getLangOpts().OpenCL) {
12955 QualType LHSTy = LHSExpr->getType();
12956 QualType RHSTy = RHSExpr->getType();
12957 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12958 // the ATOMIC_VAR_INIT macro.
12959 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12960 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12961 if (BO_Assign == Opc)
12962 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12963 else
12964 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12965 return ExprError();
12966 }
12967
12968 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12969 // only with a builtin functions and therefore should be disallowed here.
12970 if (LHSTy->isImageType() || RHSTy->isImageType() ||
12971 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12972 LHSTy->isPipeType() || RHSTy->isPipeType() ||
12973 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12974 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12975 return ExprError();
12976 }
12977 }
12978
12979 // Diagnose operations on the unsupported types for OpenMP device compilation.
12980 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12981 if (Opc != BO_Assign && Opc != BO_Comma) {
12982 checkOpenMPDeviceExpr(LHSExpr);
12983 checkOpenMPDeviceExpr(RHSExpr);
12984 }
12985 }
12986
12987 switch (Opc) {
12988 case BO_Assign:
12989 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12990 if (getLangOpts().CPlusPlus &&
12991 LHS.get()->getObjectKind() != OK_ObjCProperty) {
12992 VK = LHS.get()->getValueKind();
12993 OK = LHS.get()->getObjectKind();
12994 }
12995 if (!ResultTy.isNull()) {
12996 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12997 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12998
12999 // Avoid copying a block to the heap if the block is assigned to a local
13000 // auto variable that is declared in the same scope as the block. This
13001 // optimization is unsafe if the local variable is declared in an outer
13002 // scope. For example:
13003 //
13004 // BlockTy b;
13005 // {
13006 // b = ^{...};
13007 // }
13008 // // It is unsafe to invoke the block here if it wasn't copied to the
13009 // // heap.
13010 // b();
13011
13012 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13013 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13014 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13015 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13016 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13017
13018 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13019 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13020 NTCUC_Assignment, NTCUK_Copy);
13021 }
13022 RecordModifiableNonNullParam(*this, LHS.get());
13023 break;
13024 case BO_PtrMemD:
13025 case BO_PtrMemI:
13026 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13027 Opc == BO_PtrMemI);
13028 break;
13029 case BO_Mul:
13030 case BO_Div:
13031 ConvertHalfVec = true;
13032 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13033 Opc == BO_Div);
13034 break;
13035 case BO_Rem:
13036 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13037 break;
13038 case BO_Add:
13039 ConvertHalfVec = true;
13040 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13041 break;
13042 case BO_Sub:
13043 ConvertHalfVec = true;
13044 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13045 break;
13046 case BO_Shl:
13047 case BO_Shr:
13048 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13049 break;
13050 case BO_LE:
13051 case BO_LT:
13052 case BO_GE:
13053 case BO_GT:
13054 ConvertHalfVec = true;
13055 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13056 break;
13057 case BO_EQ:
13058 case BO_NE:
13059 ConvertHalfVec = true;
13060 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13061 break;
13062 case BO_Cmp:
13063 ConvertHalfVec = true;
13064 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13065 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13066 break;
13067 case BO_And:
13068 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13069 LLVM_FALLTHROUGH;
13070 case BO_Xor:
13071 case BO_Or:
13072 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13073 break;
13074 case BO_LAnd:
13075 case BO_LOr:
13076 ConvertHalfVec = true;
13077 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13078 break;
13079 case BO_MulAssign:
13080 case BO_DivAssign:
13081 ConvertHalfVec = true;
13082 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13083 Opc == BO_DivAssign);
13084 CompLHSTy = CompResultTy;
13085 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13086 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13087 break;
13088 case BO_RemAssign:
13089 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13090 CompLHSTy = CompResultTy;
13091 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13092 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13093 break;
13094 case BO_AddAssign:
13095 ConvertHalfVec = true;
13096 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13097 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13098 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13099 break;
13100 case BO_SubAssign:
13101 ConvertHalfVec = true;
13102 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13103 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13104 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13105 break;
13106 case BO_ShlAssign:
13107 case BO_ShrAssign:
13108 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13109 CompLHSTy = CompResultTy;
13110 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13111 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13112 break;
13113 case BO_AndAssign:
13114 case BO_OrAssign: // fallthrough
13115 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13116 LLVM_FALLTHROUGH;
13117 case BO_XorAssign:
13118 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13119 CompLHSTy = CompResultTy;
13120 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13121 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13122 break;
13123 case BO_Comma:
13124 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13125 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13126 VK = RHS.get()->getValueKind();
13127 OK = RHS.get()->getObjectKind();
13128 }
13129 break;
13130 }
13131 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13132 return ExprError();
13133
13134 if (ResultTy->isRealFloatingType() &&
13135 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13136 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13137 // Mark the current function as usng floating point constrained intrinsics
13138 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13139 F->setUsesFPIntrin(true);
13140 }
13141
13142 // Some of the binary operations require promoting operands of half vector to
13143 // float vectors and truncating the result back to half vector. For now, we do
13144 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13145 // arm64).
13146 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13147 isVector(LHS.get()->getType(), Context.HalfTy) &&
13148 "both sides are half vectors or neither sides are");
13149 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13150 LHS.get()->getType());
13151
13152 // Check for array bounds violations for both sides of the BinaryOperator
13153 CheckArrayAccess(LHS.get());
13154 CheckArrayAccess(RHS.get());
13155
13156 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13157 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13158 &Context.Idents.get("object_setClass"),
13159 SourceLocation(), LookupOrdinaryName);
13160 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13161 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13162 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13163 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13164 "object_setClass(")
13165 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13166 ",")
13167 << FixItHint::CreateInsertion(RHSLocEnd, ")");
13168 }
13169 else
13170 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13171 }
13172 else if (const ObjCIvarRefExpr *OIRE =
13173 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13174 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13175
13176 // Opc is not a compound assignment if CompResultTy is null.
13177 if (CompResultTy.isNull()) {
13178 if (ConvertHalfVec)
13179 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13180 OpLoc, FPFeatures);
13181 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13182 OK, OpLoc, FPFeatures);
13183 }
13184
13185 // Handle compound assignments.
13186 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13187 OK_ObjCProperty) {
13188 VK = VK_LValue;
13189 OK = LHS.get()->getObjectKind();
13190 }
13191
13192 if (ConvertHalfVec)
13193 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13194 OpLoc, FPFeatures);
13195
13196 return new (Context) CompoundAssignOperator(
13197 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13198 OpLoc, FPFeatures);
13199 }
13200
13201 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13202 /// operators are mixed in a way that suggests that the programmer forgot that
13203 /// comparison operators have higher precedence. The most typical example of
13204 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13205 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13206 SourceLocation OpLoc, Expr *LHSExpr,
13207 Expr *RHSExpr) {
13208 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13209 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13210
13211 // Check that one of the sides is a comparison operator and the other isn't.
13212 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13213 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13214 if (isLeftComp == isRightComp)
13215 return;
13216
13217 // Bitwise operations are sometimes used as eager logical ops.
13218 // Don't diagnose this.
13219 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13220 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13221 if (isLeftBitwise || isRightBitwise)
13222 return;
13223
13224 SourceRange DiagRange = isLeftComp
13225 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13226 : SourceRange(OpLoc, RHSExpr->getEndLoc());
13227 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13228 SourceRange ParensRange =
13229 isLeftComp
13230 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13231 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13232
13233 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13234 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13235 SuggestParentheses(Self, OpLoc,
13236 Self.PDiag(diag::note_precedence_silence) << OpStr,
13237 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13238 SuggestParentheses(Self, OpLoc,
13239 Self.PDiag(diag::note_precedence_bitwise_first)
13240 << BinaryOperator::getOpcodeStr(Opc),
13241 ParensRange);
13242 }
13243
13244 /// It accepts a '&&' expr that is inside a '||' one.
13245 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13246 /// in parentheses.
13247 static void
13248 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13249 BinaryOperator *Bop) {
13250 assert(Bop->getOpcode() == BO_LAnd);
13251 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13252 << Bop->getSourceRange() << OpLoc;
13253 SuggestParentheses(Self, Bop->getOperatorLoc(),
13254 Self.PDiag(diag::note_precedence_silence)
13255 << Bop->getOpcodeStr(),
13256 Bop->getSourceRange());
13257 }
13258
13259 /// Returns true if the given expression can be evaluated as a constant
13260 /// 'true'.
13261 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13262 bool Res;
13263 return !E->isValueDependent() &&
13264 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13265 }
13266
13267 /// Returns true if the given expression can be evaluated as a constant
13268 /// 'false'.
13269 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13270 bool Res;
13271 return !E->isValueDependent() &&
13272 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13273 }
13274
13275 /// Look for '&&' in the left hand of a '||' expr.
13276 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13277 Expr *LHSExpr, Expr *RHSExpr) {
13278 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13279 if (Bop->getOpcode() == BO_LAnd) {
13280 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13281 if (EvaluatesAsFalse(S, RHSExpr))
13282 return;
13283 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13284 if (!EvaluatesAsTrue(S, Bop->getLHS()))
13285 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13286 } else if (Bop->getOpcode() == BO_LOr) {
13287 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13288 // If it's "a || b && 1 || c" we didn't warn earlier for
13289 // "a || b && 1", but warn now.
13290 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13291 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13292 }
13293 }
13294 }
13295 }
13296
13297 /// Look for '&&' in the right hand of a '||' expr.
13298 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13299 Expr *LHSExpr, Expr *RHSExpr) {
13300 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13301 if (Bop->getOpcode() == BO_LAnd) {
13302 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13303 if (EvaluatesAsFalse(S, LHSExpr))
13304 return;
13305 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13306 if (!EvaluatesAsTrue(S, Bop->getRHS()))
13307 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13308 }
13309 }
13310 }
13311
13312 /// Look for bitwise op in the left or right hand of a bitwise op with
13313 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13314 /// the '&' expression in parentheses.
13315 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13316 SourceLocation OpLoc, Expr *SubExpr) {
13317 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13318 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13319 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13320 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13321 << Bop->getSourceRange() << OpLoc;
13322 SuggestParentheses(S, Bop->getOperatorLoc(),
13323 S.PDiag(diag::note_precedence_silence)
13324 << Bop->getOpcodeStr(),
13325 Bop->getSourceRange());
13326 }
13327 }
13328 }
13329
13330 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13331 Expr *SubExpr, StringRef Shift) {
13332 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13333 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13334 StringRef Op = Bop->getOpcodeStr();
13335 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13336 << Bop->getSourceRange() << OpLoc << Shift << Op;
13337 SuggestParentheses(S, Bop->getOperatorLoc(),
13338 S.PDiag(diag::note_precedence_silence) << Op,
13339 Bop->getSourceRange());
13340 }
13341 }
13342 }
13343
13344 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13345 Expr *LHSExpr, Expr *RHSExpr) {
13346 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13347 if (!OCE)
13348 return;
13349
13350 FunctionDecl *FD = OCE->getDirectCallee();
13351 if (!FD || !FD->isOverloadedOperator())
13352 return;
13353
13354 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13355 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13356 return;
13357
13358 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13359 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13360 << (Kind == OO_LessLess);
13361 SuggestParentheses(S, OCE->getOperatorLoc(),
13362 S.PDiag(diag::note_precedence_silence)
13363 << (Kind == OO_LessLess ? "<<" : ">>"),
13364 OCE->getSourceRange());
13365 SuggestParentheses(
13366 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13367 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13368 }
13369
13370 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13371 /// precedence.
13372 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13373 SourceLocation OpLoc, Expr *LHSExpr,
13374 Expr *RHSExpr){
13375 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13376 if (BinaryOperator::isBitwiseOp(Opc))
13377 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13378
13379 // Diagnose "arg1 & arg2 | arg3"
13380 if ((Opc == BO_Or || Opc == BO_Xor) &&
13381 !OpLoc.isMacroID()/* Don't warn in macros. */) {
13382 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13383 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13384 }
13385
13386 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13387 // We don't warn for 'assert(a || b && "bad")' since this is safe.
13388 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13389 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13390 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13391 }
13392
13393 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13394 || Opc == BO_Shr) {
13395 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13396 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13397 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13398 }
13399
13400 // Warn on overloaded shift operators and comparisons, such as:
13401 // cout << 5 == 4;
13402 if (BinaryOperator::isComparisonOp(Opc))
13403 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13404 }
13405
13406 // Binary Operators. 'Tok' is the token for the operator.
13407 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13408 tok::TokenKind Kind,
13409 Expr *LHSExpr, Expr *RHSExpr) {
13410 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13411 assert(LHSExpr && "ActOnBinOp(): missing left expression");
13412 assert(RHSExpr && "ActOnBinOp(): missing right expression");
13413
13414 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13415 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13416
13417 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13418 }
13419
13420 /// Build an overloaded binary operator expression in the given scope.
13421 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13422 BinaryOperatorKind Opc,
13423 Expr *LHS, Expr *RHS) {
13424 switch (Opc) {
13425 case BO_Assign:
13426 case BO_DivAssign:
13427 case BO_RemAssign:
13428 case BO_SubAssign:
13429 case BO_AndAssign:
13430 case BO_OrAssign:
13431 case BO_XorAssign:
13432 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13433 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13434 break;
13435 default:
13436 break;
13437 }
13438
13439 // Find all of the overloaded operators visible from this
13440 // point. We perform both an operator-name lookup from the local
13441 // scope and an argument-dependent lookup based on the types of
13442 // the arguments.
13443 UnresolvedSet<16> Functions;
13444 OverloadedOperatorKind OverOp
13445 = BinaryOperator::getOverloadedOperator(Opc);
13446 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13447 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13448 RHS->getType(), Functions);
13449
13450 // In C++20 onwards, we may have a second operator to look up.
13451 if (S.getLangOpts().CPlusPlus2a) {
13452 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13453 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13454 RHS->getType(), Functions);
13455 }
13456
13457 // Build the (potentially-overloaded, potentially-dependent)
13458 // binary operation.
13459 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13460 }
13461
13462 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13463 BinaryOperatorKind Opc,
13464 Expr *LHSExpr, Expr *RHSExpr) {
13465 ExprResult LHS, RHS;
13466 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13467 if (!LHS.isUsable() || !RHS.isUsable())
13468 return ExprError();
13469 LHSExpr = LHS.get();
13470 RHSExpr = RHS.get();
13471
13472 // We want to end up calling one of checkPseudoObjectAssignment
13473 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13474 // both expressions are overloadable or either is type-dependent),
13475 // or CreateBuiltinBinOp (in any other case). We also want to get
13476 // any placeholder types out of the way.
13477
13478 // Handle pseudo-objects in the LHS.
13479 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13480 // Assignments with a pseudo-object l-value need special analysis.
13481 if (pty->getKind() == BuiltinType::PseudoObject &&
13482 BinaryOperator::isAssignmentOp(Opc))
13483 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13484
13485 // Don't resolve overloads if the other type is overloadable.
13486 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13487 // We can't actually test that if we still have a placeholder,
13488 // though. Fortunately, none of the exceptions we see in that
13489 // code below are valid when the LHS is an overload set. Note
13490 // that an overload set can be dependently-typed, but it never
13491 // instantiates to having an overloadable type.
13492 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13493 if (resolvedRHS.isInvalid()) return ExprError();
13494 RHSExpr = resolvedRHS.get();
13495
13496 if (RHSExpr->isTypeDependent() ||
13497 RHSExpr->getType()->isOverloadableType())
13498 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13499 }
13500
13501 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13502 // template, diagnose the missing 'template' keyword instead of diagnosing
13503 // an invalid use of a bound member function.
13504 //
13505 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13506 // to C++1z [over.over]/1.4, but we already checked for that case above.
13507 if (Opc == BO_LT && inTemplateInstantiation() &&
13508 (pty->getKind() == BuiltinType::BoundMember ||
13509 pty->getKind() == BuiltinType::Overload)) {
13510 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13511 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13512 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13513 return isa<FunctionTemplateDecl>(ND);
13514 })) {
13515 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13516 : OE->getNameLoc(),
13517 diag::err_template_kw_missing)
13518 << OE->getName().getAsString() << "";
13519 return ExprError();
13520 }
13521 }
13522
13523 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13524 if (LHS.isInvalid()) return ExprError();
13525 LHSExpr = LHS.get();
13526 }
13527
13528 // Handle pseudo-objects in the RHS.
13529 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13530 // An overload in the RHS can potentially be resolved by the type
13531 // being assigned to.
13532 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13533 if (getLangOpts().CPlusPlus &&
13534 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13535 LHSExpr->getType()->isOverloadableType()))
13536 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13537
13538 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13539 }
13540
13541 // Don't resolve overloads if the other type is overloadable.
13542 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13543 LHSExpr->getType()->isOverloadableType())
13544 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13545
13546 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13547 if (!resolvedRHS.isUsable()) return ExprError();
13548 RHSExpr = resolvedRHS.get();
13549 }
13550
13551 if (getLangOpts().CPlusPlus) {
13552 // If either expression is type-dependent, always build an
13553 // overloaded op.
13554 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13555 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13556
13557 // Otherwise, build an overloaded op if either expression has an
13558 // overloadable type.
13559 if (LHSExpr->getType()->isOverloadableType() ||
13560 RHSExpr->getType()->isOverloadableType())
13561 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13562 }
13563
13564 // Build a built-in binary operation.
13565 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13566 }
13567
13568 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13569 if (T.isNull() || T->isDependentType())
13570 return false;
13571
13572 if (!T->isPromotableIntegerType())
13573 return true;
13574
13575 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13576 }
13577
13578 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13579 UnaryOperatorKind Opc,
13580 Expr *InputExpr) {
13581 ExprResult Input = InputExpr;
13582 ExprValueKind VK = VK_RValue;
13583 ExprObjectKind OK = OK_Ordinary;
13584 QualType resultType;
13585 bool CanOverflow = false;
13586
13587 bool ConvertHalfVec = false;
13588 if (getLangOpts().OpenCL) {
13589 QualType Ty = InputExpr->getType();
13590 // The only legal unary operation for atomics is '&'.
13591 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13592 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13593 // only with a builtin functions and therefore should be disallowed here.
13594 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13595 || Ty->isBlockPointerType())) {
13596 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13597 << InputExpr->getType()
13598 << Input.get()->getSourceRange());
13599 }
13600 }
13601 // Diagnose operations on the unsupported types for OpenMP device compilation.
13602 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13603 if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13604 UnaryOperator::isArithmeticOp(Opc))
13605 checkOpenMPDeviceExpr(InputExpr);
13606 }
13607
13608 switch (Opc) {
13609 case UO_PreInc:
13610 case UO_PreDec:
13611 case UO_PostInc:
13612 case UO_PostDec:
13613 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13614 OpLoc,
13615 Opc == UO_PreInc ||
13616 Opc == UO_PostInc,
13617 Opc == UO_PreInc ||
13618 Opc == UO_PreDec);
13619 CanOverflow = isOverflowingIntegerType(Context, resultType);
13620 break;
13621 case UO_AddrOf:
13622 resultType = CheckAddressOfOperand(Input, OpLoc);
13623 CheckAddressOfNoDeref(InputExpr);
13624 RecordModifiableNonNullParam(*this, InputExpr);
13625 break;
13626 case UO_Deref: {
13627 Input = DefaultFunctionArrayLvalueConversion(Input.get());
13628 if (Input.isInvalid()) return ExprError();
13629 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13630 break;
13631 }
13632 case UO_Plus:
13633 case UO_Minus:
13634 CanOverflow = Opc == UO_Minus &&
13635 isOverflowingIntegerType(Context, Input.get()->getType());
13636 Input = UsualUnaryConversions(Input.get());
13637 if (Input.isInvalid()) return ExprError();
13638 // Unary plus and minus require promoting an operand of half vector to a
13639 // float vector and truncating the result back to a half vector. For now, we
13640 // do this only when HalfArgsAndReturns is set (that is, when the target is
13641 // arm or arm64).
13642 ConvertHalfVec =
13643 needsConversionOfHalfVec(true, Context, Input.get()->getType());
13644
13645 // If the operand is a half vector, promote it to a float vector.
13646 if (ConvertHalfVec)
13647 Input = convertVector(Input.get(), Context.FloatTy, *this);
13648 resultType = Input.get()->getType();
13649 if (resultType->isDependentType())
13650 break;
13651 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13652 break;
13653 else if (resultType->isVectorType() &&
13654 // The z vector extensions don't allow + or - with bool vectors.
13655 (!Context.getLangOpts().ZVector ||
13656 resultType->castAs<VectorType>()->getVectorKind() !=
13657 VectorType::AltiVecBool))
13658 break;
13659 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13660 Opc == UO_Plus &&
13661 resultType->isPointerType())
13662 break;
13663
13664 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13665 << resultType << Input.get()->getSourceRange());
13666
13667 case UO_Not: // bitwise complement
13668 Input = UsualUnaryConversions(Input.get());
13669 if (Input.isInvalid())
13670 return ExprError();
13671 resultType = Input.get()->getType();
13672 if (resultType->isDependentType())
13673 break;
13674 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13675 if (resultType->isComplexType() || resultType->isComplexIntegerType())
13676 // C99 does not support '~' for complex conjugation.
13677 Diag(OpLoc, diag::ext_integer_complement_complex)
13678 << resultType << Input.get()->getSourceRange();
13679 else if (resultType->hasIntegerRepresentation())
13680 break;
13681 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13682 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13683 // on vector float types.
13684 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13685 if (!T->isIntegerType())
13686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13687 << resultType << Input.get()->getSourceRange());
13688 } else {
13689 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13690 << resultType << Input.get()->getSourceRange());
13691 }
13692 break;
13693
13694 case UO_LNot: // logical negation
13695 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13696 Input = DefaultFunctionArrayLvalueConversion(Input.get());
13697 if (Input.isInvalid()) return ExprError();
13698 resultType = Input.get()->getType();
13699
13700 // Though we still have to promote half FP to float...
13701 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13702 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13703 resultType = Context.FloatTy;
13704 }
13705
13706 if (resultType->isDependentType())
13707 break;
13708 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13709 // C99 6.5.3.3p1: ok, fallthrough;
13710 if (Context.getLangOpts().CPlusPlus) {
13711 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13712 // operand contextually converted to bool.
13713 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13714 ScalarTypeToBooleanCastKind(resultType));
13715 } else if (Context.getLangOpts().OpenCL &&
13716 Context.getLangOpts().OpenCLVersion < 120) {
13717 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13718 // operate on scalar float types.
13719 if (!resultType->isIntegerType() && !resultType->isPointerType())
13720 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13721 << resultType << Input.get()->getSourceRange());
13722 }
13723 } else if (resultType->isExtVectorType()) {
13724 if (Context.getLangOpts().OpenCL &&
13725 Context.getLangOpts().OpenCLVersion < 120 &&
13726 !Context.getLangOpts().OpenCLCPlusPlus) {
13727 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13728 // operate on vector float types.
13729 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13730 if (!T->isIntegerType())
13731 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13732 << resultType << Input.get()->getSourceRange());
13733 }
13734 // Vector logical not returns the signed variant of the operand type.
13735 resultType = GetSignedVectorType(resultType);
13736 break;
13737 } else {
13738 // FIXME: GCC's vector extension permits the usage of '!' with a vector
13739 // type in C++. We should allow that here too.
13740 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13741 << resultType << Input.get()->getSourceRange());
13742 }
13743
13744 // LNot always has type int. C99 6.5.3.3p5.
13745 // In C++, it's bool. C++ 5.3.1p8
13746 resultType = Context.getLogicalOperationType();
13747 break;
13748 case UO_Real:
13749 case UO_Imag:
13750 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13751 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13752 // complex l-values to ordinary l-values and all other values to r-values.
13753 if (Input.isInvalid()) return ExprError();
13754 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13755 if (Input.get()->getValueKind() != VK_RValue &&
13756 Input.get()->getObjectKind() == OK_Ordinary)
13757 VK = Input.get()->getValueKind();
13758 } else if (!getLangOpts().CPlusPlus) {
13759 // In C, a volatile scalar is read by __imag. In C++, it is not.
13760 Input = DefaultLvalueConversion(Input.get());
13761 }
13762 break;
13763 case UO_Extension:
13764 resultType = Input.get()->getType();
13765 VK = Input.get()->getValueKind();
13766 OK = Input.get()->getObjectKind();
13767 break;
13768 case UO_Coawait:
13769 // It's unnecessary to represent the pass-through operator co_await in the
13770 // AST; just return the input expression instead.
13771 assert(!Input.get()->getType()->isDependentType() &&
13772 "the co_await expression must be non-dependant before "
13773 "building operator co_await");
13774 return Input;
13775 }
13776 if (resultType.isNull() || Input.isInvalid())
13777 return ExprError();
13778
13779 // Check for array bounds violations in the operand of the UnaryOperator,
13780 // except for the '*' and '&' operators that have to be handled specially
13781 // by CheckArrayAccess (as there are special cases like &array[arraysize]
13782 // that are explicitly defined as valid by the standard).
13783 if (Opc != UO_AddrOf && Opc != UO_Deref)
13784 CheckArrayAccess(Input.get());
13785
13786 auto *UO = new (Context)
13787 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13788
13789 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13790 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13791 ExprEvalContexts.back().PossibleDerefs.insert(UO);
13792
13793 // Convert the result back to a half vector.
13794 if (ConvertHalfVec)
13795 return convertVector(UO, Context.HalfTy, *this);
13796 return UO;
13797 }
13798
13799 /// Determine whether the given expression is a qualified member
13800 /// access expression, of a form that could be turned into a pointer to member
13801 /// with the address-of operator.
13802 bool Sema::isQualifiedMemberAccess(Expr *E) {
13803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13804 if (!DRE->getQualifier())
13805 return false;
13806
13807 ValueDecl *VD = DRE->getDecl();
13808 if (!VD->isCXXClassMember())
13809 return false;
13810
13811 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13812 return true;
13813 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13814 return Method->isInstance();
13815
13816 return false;
13817 }
13818
13819 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13820 if (!ULE->getQualifier())
13821 return false;
13822
13823 for (NamedDecl *D : ULE->decls()) {
13824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13825 if (Method->isInstance())
13826 return true;
13827 } else {
13828 // Overload set does not contain methods.
13829 break;
13830 }
13831 }
13832
13833 return false;
13834 }
13835
13836 return false;
13837 }
13838
13839 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13840 UnaryOperatorKind Opc, Expr *Input) {
13841 // First things first: handle placeholders so that the
13842 // overloaded-operator check considers the right type.
13843 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13844 // Increment and decrement of pseudo-object references.
13845 if (pty->getKind() == BuiltinType::PseudoObject &&
13846 UnaryOperator::isIncrementDecrementOp(Opc))
13847 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13848
13849 // extension is always a builtin operator.
13850 if (Opc == UO_Extension)
13851 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13852
13853 // & gets special logic for several kinds of placeholder.
13854 // The builtin code knows what to do.
13855 if (Opc == UO_AddrOf &&
13856 (pty->getKind() == BuiltinType::Overload ||
13857 pty->getKind() == BuiltinType::UnknownAny ||
13858 pty->getKind() == BuiltinType::BoundMember))
13859 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13860
13861 // Anything else needs to be handled now.
13862 ExprResult Result = CheckPlaceholderExpr(Input);
13863 if (Result.isInvalid()) return ExprError();
13864 Input = Result.get();
13865 }
13866
13867 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13868 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13869 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13870 // Find all of the overloaded operators visible from this
13871 // point. We perform both an operator-name lookup from the local
13872 // scope and an argument-dependent lookup based on the types of
13873 // the arguments.
13874 UnresolvedSet<16> Functions;
13875 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13876 if (S && OverOp != OO_None)
13877 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13878 Functions);
13879
13880 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13881 }
13882
13883 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13884 }
13885
13886 // Unary Operators. 'Tok' is the token for the operator.
13887 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13888 tok::TokenKind Op, Expr *Input) {
13889 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13890 }
13891
13892 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13893 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13894 LabelDecl *TheDecl) {
13895 TheDecl->markUsed(Context);
13896 // Create the AST node. The address of a label always has type 'void*'.
13897 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13898 Context.getPointerType(Context.VoidTy));
13899 }
13900
13901 void Sema::ActOnStartStmtExpr() {
13902 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13903 }
13904
13905 void Sema::ActOnStmtExprError() {
13906 // Note that function is also called by TreeTransform when leaving a
13907 // StmtExpr scope without rebuilding anything.
13908
13909 DiscardCleanupsInEvaluationContext();
13910 PopExpressionEvaluationContext();
13911 }
13912
13913 ExprResult
13914 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13915 SourceLocation RPLoc) { // "({..})"
13916 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13917 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13918
13919 if (hasAnyUnrecoverableErrorsInThisFunction())
13920 DiscardCleanupsInEvaluationContext();
13921 assert(!Cleanup.exprNeedsCleanups() &&
13922 "cleanups within StmtExpr not correctly bound!");
13923 PopExpressionEvaluationContext();
13924
13925 // FIXME: there are a variety of strange constraints to enforce here, for
13926 // example, it is not possible to goto into a stmt expression apparently.
13927 // More semantic analysis is needed.
13928
13929 // If there are sub-stmts in the compound stmt, take the type of the last one
13930 // as the type of the stmtexpr.
13931 QualType Ty = Context.VoidTy;
13932 bool StmtExprMayBindToTemp = false;
13933 if (!Compound->body_empty()) {
13934 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13935 if (const auto *LastStmt =
13936 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13937 if (const Expr *Value = LastStmt->getExprStmt()) {
13938 StmtExprMayBindToTemp = true;
13939 Ty = Value->getType();
13940 }
13941 }
13942 }
13943
13944 // FIXME: Check that expression type is complete/non-abstract; statement
13945 // expressions are not lvalues.
13946 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13947 if (StmtExprMayBindToTemp)
13948 return MaybeBindToTemporary(ResStmtExpr);
13949 return ResStmtExpr;
13950 }
13951
13952 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13953 if (ER.isInvalid())
13954 return ExprError();
13955
13956 // Do function/array conversion on the last expression, but not
13957 // lvalue-to-rvalue. However, initialize an unqualified type.
13958 ER = DefaultFunctionArrayConversion(ER.get());
13959 if (ER.isInvalid())
13960 return ExprError();
13961 Expr *E = ER.get();
13962
13963 if (E->isTypeDependent())
13964 return E;
13965
13966 // In ARC, if the final expression ends in a consume, splice
13967 // the consume out and bind it later. In the alternate case
13968 // (when dealing with a retainable type), the result
13969 // initialization will create a produce. In both cases the
13970 // result will be +1, and we'll need to balance that out with
13971 // a bind.
13972 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13973 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13974 return Cast->getSubExpr();
13975
13976 // FIXME: Provide a better location for the initialization.
13977 return PerformCopyInitialization(
13978 InitializedEntity::InitializeStmtExprResult(
13979 E->getBeginLoc(), E->getType().getUnqualifiedType()),
13980 SourceLocation(), E);
13981 }
13982
13983 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13984 TypeSourceInfo *TInfo,
13985 ArrayRef<OffsetOfComponent> Components,
13986 SourceLocation RParenLoc) {
13987 QualType ArgTy = TInfo->getType();
13988 bool Dependent = ArgTy->isDependentType();
13989 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13990
13991 // We must have at least one component that refers to the type, and the first
13992 // one is known to be a field designator. Verify that the ArgTy represents
13993 // a struct/union/class.
13994 if (!Dependent && !ArgTy->isRecordType())
13995 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13996 << ArgTy << TypeRange);
13997
13998 // Type must be complete per C99 7.17p3 because a declaring a variable
13999 // with an incomplete type would be ill-formed.
14000 if (!Dependent
14001 && RequireCompleteType(BuiltinLoc, ArgTy,
14002 diag::err_offsetof_incomplete_type, TypeRange))
14003 return ExprError();
14004
14005 bool DidWarnAboutNonPOD = false;
14006 QualType CurrentType = ArgTy;
14007 SmallVector<OffsetOfNode, 4> Comps;
14008 SmallVector<Expr*, 4> Exprs;
14009 for (const OffsetOfComponent &OC : Components) {
14010 if (OC.isBrackets) {
14011 // Offset of an array sub-field. TODO: Should we allow vector elements?
14012 if (!CurrentType->isDependentType()) {
14013 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14014 if(!AT)
14015 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14016 << CurrentType);
14017 CurrentType = AT->getElementType();
14018 } else
14019 CurrentType = Context.DependentTy;
14020
14021 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14022 if (IdxRval.isInvalid())
14023 return ExprError();
14024 Expr *Idx = IdxRval.get();
14025
14026 // The expression must be an integral expression.
14027 // FIXME: An integral constant expression?
14028 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14029 !Idx->getType()->isIntegerType())
14030 return ExprError(
14031 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14032 << Idx->getSourceRange());
14033
14034 // Record this array index.
14035 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14036 Exprs.push_back(Idx);
14037 continue;
14038 }
14039
14040 // Offset of a field.
14041 if (CurrentType->isDependentType()) {
14042 // We have the offset of a field, but we can't look into the dependent
14043 // type. Just record the identifier of the field.
14044 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14045 CurrentType = Context.DependentTy;
14046 continue;
14047 }
14048
14049 // We need to have a complete type to look into.
14050 if (RequireCompleteType(OC.LocStart, CurrentType,
14051 diag::err_offsetof_incomplete_type))
14052 return ExprError();
14053
14054 // Look for the designated field.
14055 const RecordType *RC = CurrentType->getAs<RecordType>();
14056 if (!RC)
14057 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14058 << CurrentType);
14059 RecordDecl *RD = RC->getDecl();
14060
14061 // C++ [lib.support.types]p5:
14062 // The macro offsetof accepts a restricted set of type arguments in this
14063 // International Standard. type shall be a POD structure or a POD union
14064 // (clause 9).
14065 // C++11 [support.types]p4:
14066 // If type is not a standard-layout class (Clause 9), the results are
14067 // undefined.
14068 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14069 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14070 unsigned DiagID =
14071 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14072 : diag::ext_offsetof_non_pod_type;
14073
14074 if (!IsSafe && !DidWarnAboutNonPOD &&
14075 DiagRuntimeBehavior(BuiltinLoc, nullptr,
14076 PDiag(DiagID)
14077 << SourceRange(Components[0].LocStart, OC.LocEnd)
14078 << CurrentType))
14079 DidWarnAboutNonPOD = true;
14080 }
14081
14082 // Look for the field.
14083 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14084 LookupQualifiedName(R, RD);
14085 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14086 IndirectFieldDecl *IndirectMemberDecl = nullptr;
14087 if (!MemberDecl) {
14088 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14089 MemberDecl = IndirectMemberDecl->getAnonField();
14090 }
14091
14092 if (!MemberDecl)
14093 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14094 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14095 OC.LocEnd));
14096
14097 // C99 7.17p3:
14098 // (If the specified member is a bit-field, the behavior is undefined.)
14099 //
14100 // We diagnose this as an error.
14101 if (MemberDecl->isBitField()) {
14102 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14103 << MemberDecl->getDeclName()
14104 << SourceRange(BuiltinLoc, RParenLoc);
14105 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14106 return ExprError();
14107 }
14108
14109 RecordDecl *Parent = MemberDecl->getParent();
14110 if (IndirectMemberDecl)
14111 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14112
14113 // If the member was found in a base class, introduce OffsetOfNodes for
14114 // the base class indirections.
14115 CXXBasePaths Paths;
14116 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14117 Paths)) {
14118 if (Paths.getDetectedVirtual()) {
14119 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14120 << MemberDecl->getDeclName()
14121 << SourceRange(BuiltinLoc, RParenLoc);
14122 return ExprError();
14123 }
14124
14125 CXXBasePath &Path = Paths.front();
14126 for (const CXXBasePathElement &B : Path)
14127 Comps.push_back(OffsetOfNode(B.Base));
14128 }
14129
14130 if (IndirectMemberDecl) {
14131 for (auto *FI : IndirectMemberDecl->chain()) {
14132 assert(isa<FieldDecl>(FI));
14133 Comps.push_back(OffsetOfNode(OC.LocStart,
14134 cast<FieldDecl>(FI), OC.LocEnd));
14135 }
14136 } else
14137 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14138
14139 CurrentType = MemberDecl->getType().getNonReferenceType();
14140 }
14141
14142 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14143 Comps, Exprs, RParenLoc);
14144 }
14145
14146 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14147 SourceLocation BuiltinLoc,
14148 SourceLocation TypeLoc,
14149 ParsedType ParsedArgTy,
14150 ArrayRef<OffsetOfComponent> Components,
14151 SourceLocation RParenLoc) {
14152
14153 TypeSourceInfo *ArgTInfo;
14154 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14155 if (ArgTy.isNull())
14156 return ExprError();
14157
14158 if (!ArgTInfo)
14159 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14160
14161 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14162 }
14163
14164
14165 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14166 Expr *CondExpr,
14167 Expr *LHSExpr, Expr *RHSExpr,
14168 SourceLocation RPLoc) {
14169 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14170
14171 ExprValueKind VK = VK_RValue;
14172 ExprObjectKind OK = OK_Ordinary;
14173 QualType resType;
14174 bool ValueDependent = false;
14175 bool CondIsTrue = false;
14176 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14177 resType = Context.DependentTy;
14178 ValueDependent = true;
14179 } else {
14180 // The conditional expression is required to be a constant expression.
14181 llvm::APSInt condEval(32);
14182 ExprResult CondICE
14183 = VerifyIntegerConstantExpression(CondExpr, &condEval,
14184 diag::err_typecheck_choose_expr_requires_constant, false);
14185 if (CondICE.isInvalid())
14186 return ExprError();
14187 CondExpr = CondICE.get();
14188 CondIsTrue = condEval.getZExtValue();
14189
14190 // If the condition is > zero, then the AST type is the same as the LHSExpr.
14191 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14192
14193 resType = ActiveExpr->getType();
14194 ValueDependent = ActiveExpr->isValueDependent();
14195 VK = ActiveExpr->getValueKind();
14196 OK = ActiveExpr->getObjectKind();
14197 }
14198
14199 return new (Context)
14200 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14201 CondIsTrue, resType->isDependentType(), ValueDependent);
14202 }
14203
14204 //===----------------------------------------------------------------------===//
14205 // Clang Extensions.
14206 //===----------------------------------------------------------------------===//
14207
14208 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14209 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14210 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14211
14212 if (LangOpts.CPlusPlus) {
14213 MangleNumberingContext *MCtx;
14214 Decl *ManglingContextDecl;
14215 std::tie(MCtx, ManglingContextDecl) =
14216 getCurrentMangleNumberContext(Block->getDeclContext());
14217 if (MCtx) {
14218 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14219 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14220 }
14221 }
14222
14223 PushBlockScope(CurScope, Block);
14224 CurContext->addDecl(Block);
14225 if (CurScope)
14226 PushDeclContext(CurScope, Block);
14227 else
14228 CurContext = Block;
14229
14230 getCurBlock()->HasImplicitReturnType = true;
14231
14232 // Enter a new evaluation context to insulate the block from any
14233 // cleanups from the enclosing full-expression.
14234 PushExpressionEvaluationContext(
14235 ExpressionEvaluationContext::PotentiallyEvaluated);
14236 }
14237
14238 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14239 Scope *CurScope) {
14240 assert(ParamInfo.getIdentifier() == nullptr &&
14241 "block-id should have no identifier!");
14242 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14243 BlockScopeInfo *CurBlock = getCurBlock();
14244
14245 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14246 QualType T = Sig->getType();
14247
14248 // FIXME: We should allow unexpanded parameter packs here, but that would,
14249 // in turn, make the block expression contain unexpanded parameter packs.
14250 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14251 // Drop the parameters.
14252 FunctionProtoType::ExtProtoInfo EPI;
14253 EPI.HasTrailingReturn = false;
14254 EPI.TypeQuals.addConst();
14255 T = Context.getFunctionType(Context.DependentTy, None, EPI);
14256 Sig = Context.getTrivialTypeSourceInfo(T);
14257 }
14258
14259 // GetTypeForDeclarator always produces a function type for a block
14260 // literal signature. Furthermore, it is always a FunctionProtoType
14261 // unless the function was written with a typedef.
14262 assert(T->isFunctionType() &&
14263 "GetTypeForDeclarator made a non-function block signature");
14264
14265 // Look for an explicit signature in that function type.
14266 FunctionProtoTypeLoc ExplicitSignature;
14267
14268 if ((ExplicitSignature = Sig->getTypeLoc()
14269 .getAsAdjusted<FunctionProtoTypeLoc>())) {
14270
14271 // Check whether that explicit signature was synthesized by
14272 // GetTypeForDeclarator. If so, don't save that as part of the
14273 // written signature.
14274 if (ExplicitSignature.getLocalRangeBegin() ==
14275 ExplicitSignature.getLocalRangeEnd()) {
14276 // This would be much cheaper if we stored TypeLocs instead of
14277 // TypeSourceInfos.
14278 TypeLoc Result = ExplicitSignature.getReturnLoc();
14279 unsigned Size = Result.getFullDataSize();
14280 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14281 Sig->getTypeLoc().initializeFullCopy(Result, Size);
14282
14283 ExplicitSignature = FunctionProtoTypeLoc();
14284 }
14285 }
14286
14287 CurBlock->TheDecl->setSignatureAsWritten(Sig);
14288 CurBlock->FunctionType = T;
14289
14290 const FunctionType *Fn = T->getAs<FunctionType>();
14291 QualType RetTy = Fn->getReturnType();
14292 bool isVariadic =
14293 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14294
14295 CurBlock->TheDecl->setIsVariadic(isVariadic);
14296
14297 // Context.DependentTy is used as a placeholder for a missing block
14298 // return type. TODO: what should we do with declarators like:
14299 // ^ * { ... }
14300 // If the answer is "apply template argument deduction"....
14301 if (RetTy != Context.DependentTy) {
14302 CurBlock->ReturnType = RetTy;
14303 CurBlock->TheDecl->setBlockMissingReturnType(false);
14304 CurBlock->HasImplicitReturnType = false;
14305 }
14306
14307 // Push block parameters from the declarator if we had them.
14308 SmallVector<ParmVarDecl*, 8> Params;
14309 if (ExplicitSignature) {
14310 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14311 ParmVarDecl *Param = ExplicitSignature.getParam(I);
14312 if (Param->getIdentifier() == nullptr &&
14313 !Param->isImplicit() &&
14314 !Param->isInvalidDecl() &&
14315 !getLangOpts().CPlusPlus)
14316 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14317 Params.push_back(Param);
14318 }
14319
14320 // Fake up parameter variables if we have a typedef, like
14321 // ^ fntype { ... }
14322 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14323 for (const auto &I : Fn->param_types()) {
14324 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14325 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14326 Params.push_back(Param);
14327 }
14328 }
14329
14330 // Set the parameters on the block decl.
14331 if (!Params.empty()) {
14332 CurBlock->TheDecl->setParams(Params);
14333 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14334 /*CheckParameterNames=*/false);
14335 }
14336
14337 // Finally we can process decl attributes.
14338 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14339
14340 // Put the parameter variables in scope.
14341 for (auto AI : CurBlock->TheDecl->parameters()) {
14342 AI->setOwningFunction(CurBlock->TheDecl);
14343
14344 // If this has an identifier, add it to the scope stack.
14345 if (AI->getIdentifier()) {
14346 CheckShadow(CurBlock->TheScope, AI);
14347
14348 PushOnScopeChains(AI, CurBlock->TheScope);
14349 }
14350 }
14351 }
14352
14353 /// ActOnBlockError - If there is an error parsing a block, this callback
14354 /// is invoked to pop the information about the block from the action impl.
14355 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14356 // Leave the expression-evaluation context.
14357 DiscardCleanupsInEvaluationContext();
14358 PopExpressionEvaluationContext();
14359
14360 // Pop off CurBlock, handle nested blocks.
14361 PopDeclContext();
14362 PopFunctionScopeInfo();
14363 }
14364
14365 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14366 /// literal was successfully completed. ^(int x){...}
14367 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14368 Stmt *Body, Scope *CurScope) {
14369 // If blocks are disabled, emit an error.
14370 if (!LangOpts.Blocks)
14371 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14372
14373 // Leave the expression-evaluation context.
14374 if (hasAnyUnrecoverableErrorsInThisFunction())
14375 DiscardCleanupsInEvaluationContext();
14376 assert(!Cleanup.exprNeedsCleanups() &&
14377 "cleanups within block not correctly bound!");
14378 PopExpressionEvaluationContext();
14379
14380 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14381 BlockDecl *BD = BSI->TheDecl;
14382
14383 if (BSI->HasImplicitReturnType)
14384 deduceClosureReturnType(*BSI);
14385
14386 QualType RetTy = Context.VoidTy;
14387 if (!BSI->ReturnType.isNull())
14388 RetTy = BSI->ReturnType;
14389
14390 bool NoReturn = BD->hasAttr<NoReturnAttr>();
14391 QualType BlockTy;
14392
14393 // If the user wrote a function type in some form, try to use that.
14394 if (!BSI->FunctionType.isNull()) {
14395 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14396
14397 FunctionType::ExtInfo Ext = FTy->getExtInfo();
14398 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14399
14400 // Turn protoless block types into nullary block types.
14401 if (isa<FunctionNoProtoType>(FTy)) {
14402 FunctionProtoType::ExtProtoInfo EPI;
14403 EPI.ExtInfo = Ext;
14404 BlockTy = Context.getFunctionType(RetTy, None, EPI);
14405
14406 // Otherwise, if we don't need to change anything about the function type,
14407 // preserve its sugar structure.
14408 } else if (FTy->getReturnType() == RetTy &&
14409 (!NoReturn || FTy->getNoReturnAttr())) {
14410 BlockTy = BSI->FunctionType;
14411
14412 // Otherwise, make the minimal modifications to the function type.
14413 } else {
14414 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14416 EPI.TypeQuals = Qualifiers();
14417 EPI.ExtInfo = Ext;
14418 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14419 }
14420
14421 // If we don't have a function type, just build one from nothing.
14422 } else {
14423 FunctionProtoType::ExtProtoInfo EPI;
14424 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14425 BlockTy = Context.getFunctionType(RetTy, None, EPI);
14426 }
14427
14428 DiagnoseUnusedParameters(BD->parameters());
14429 BlockTy = Context.getBlockPointerType(BlockTy);
14430
14431 // If needed, diagnose invalid gotos and switches in the block.
14432 if (getCurFunction()->NeedsScopeChecking() &&
14433 !PP.isCodeCompletionEnabled())
14434 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14435
14436 BD->setBody(cast<CompoundStmt>(Body));
14437
14438 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14439 DiagnoseUnguardedAvailabilityViolations(BD);
14440
14441 // Try to apply the named return value optimization. We have to check again
14442 // if we can do this, though, because blocks keep return statements around
14443 // to deduce an implicit return type.
14444 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14445 !BD->isDependentContext())
14446 computeNRVO(Body, BSI);
14447
14448 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14449 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14450 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14451 NTCUK_Destruct|NTCUK_Copy);
14452
14453 PopDeclContext();
14454
14455 // Pop the block scope now but keep it alive to the end of this function.
14456 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14457 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14458
14459 // Set the captured variables on the block.
14460 SmallVector<BlockDecl::Capture, 4> Captures;
14461 for (Capture &Cap : BSI->Captures) {
14462 if (Cap.isInvalid() || Cap.isThisCapture())
14463 continue;
14464
14465 VarDecl *Var = Cap.getVariable();
14466 Expr *CopyExpr = nullptr;
14467 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14468 if (const RecordType *Record =
14469 Cap.getCaptureType()->getAs<RecordType>()) {
14470 // The capture logic needs the destructor, so make sure we mark it.
14471 // Usually this is unnecessary because most local variables have
14472 // their destructors marked at declaration time, but parameters are
14473 // an exception because it's technically only the call site that
14474 // actually requires the destructor.
14475 if (isa<ParmVarDecl>(Var))
14476 FinalizeVarWithDestructor(Var, Record);
14477
14478 // Enter a separate potentially-evaluated context while building block
14479 // initializers to isolate their cleanups from those of the block
14480 // itself.
14481 // FIXME: Is this appropriate even when the block itself occurs in an
14482 // unevaluated operand?
14483 EnterExpressionEvaluationContext EvalContext(
14484 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14485
14486 SourceLocation Loc = Cap.getLocation();
14487
14488 ExprResult Result = BuildDeclarationNameExpr(
14489 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14490
14491 // According to the blocks spec, the capture of a variable from
14492 // the stack requires a const copy constructor. This is not true
14493 // of the copy/move done to move a __block variable to the heap.
14494 if (!Result.isInvalid() &&
14495 !Result.get()->getType().isConstQualified()) {
14496 Result = ImpCastExprToType(Result.get(),
14497 Result.get()->getType().withConst(),
14498 CK_NoOp, VK_LValue);
14499 }
14500
14501 if (!Result.isInvalid()) {
14502 Result = PerformCopyInitialization(
14503 InitializedEntity::InitializeBlock(Var->getLocation(),
14504 Cap.getCaptureType(), false),
14505 Loc, Result.get());
14506 }
14507
14508 // Build a full-expression copy expression if initialization
14509 // succeeded and used a non-trivial constructor. Recover from
14510 // errors by pretending that the copy isn't necessary.
14511 if (!Result.isInvalid() &&
14512 !cast<CXXConstructExpr>(Result.get())->getConstructor()
14513 ->isTrivial()) {
14514 Result = MaybeCreateExprWithCleanups(Result);
14515 CopyExpr = Result.get();
14516 }
14517 }
14518 }
14519
14520 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14521 CopyExpr);
14522 Captures.push_back(NewCap);
14523 }
14524 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14525
14526 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14527
14528 // If the block isn't obviously global, i.e. it captures anything at
14529 // all, then we need to do a few things in the surrounding context:
14530 if (Result->getBlockDecl()->hasCaptures()) {
14531 // First, this expression has a new cleanup object.
14532 ExprCleanupObjects.push_back(Result->getBlockDecl());
14533 Cleanup.setExprNeedsCleanups(true);
14534
14535 // It also gets a branch-protected scope if any of the captured
14536 // variables needs destruction.
14537 for (const auto &CI : Result->getBlockDecl()->captures()) {
14538 const VarDecl *var = CI.getVariable();
14539 if (var->getType().isDestructedType() != QualType::DK_none) {
14540 setFunctionHasBranchProtectedScope();
14541 break;
14542 }
14543 }
14544 }
14545
14546 if (getCurFunction())
14547 getCurFunction()->addBlock(BD);
14548
14549 return Result;
14550 }
14551
14552 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14553 SourceLocation RPLoc) {
14554 TypeSourceInfo *TInfo;
14555 GetTypeFromParser(Ty, &TInfo);
14556 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14557 }
14558
14559 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14560 Expr *E, TypeSourceInfo *TInfo,
14561 SourceLocation RPLoc) {
14562 Expr *OrigExpr = E;
14563 bool IsMS = false;
14564
14565 // CUDA device code does not support varargs.
14566 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14567 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14568 CUDAFunctionTarget T = IdentifyCUDATarget(F);
14569 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14570 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14571 }
14572 }
14573
14574 // NVPTX does not support va_arg expression.
14575 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14576 Context.getTargetInfo().getTriple().isNVPTX())
14577 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14578
14579 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14580 // as Microsoft ABI on an actual Microsoft platform, where
14581 // __builtin_ms_va_list and __builtin_va_list are the same.)
14582 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14583 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14584 QualType MSVaListType = Context.getBuiltinMSVaListType();
14585 if (Context.hasSameType(MSVaListType, E->getType())) {
14586 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14587 return ExprError();
14588 IsMS = true;
14589 }
14590 }
14591
14592 // Get the va_list type
14593 QualType VaListType = Context.getBuiltinVaListType();
14594 if (!IsMS) {
14595 if (VaListType->isArrayType()) {
14596 // Deal with implicit array decay; for example, on x86-64,
14597 // va_list is an array, but it's supposed to decay to
14598 // a pointer for va_arg.
14599 VaListType = Context.getArrayDecayedType(VaListType);
14600 // Make sure the input expression also decays appropriately.
14601 ExprResult Result = UsualUnaryConversions(E);
14602 if (Result.isInvalid())
14603 return ExprError();
14604 E = Result.get();
14605 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14606 // If va_list is a record type and we are compiling in C++ mode,
14607 // check the argument using reference binding.
14608 InitializedEntity Entity = InitializedEntity::InitializeParameter(
14609 Context, Context.getLValueReferenceType(VaListType), false);
14610 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14611 if (Init.isInvalid())
14612 return ExprError();
14613 E = Init.getAs<Expr>();
14614 } else {
14615 // Otherwise, the va_list argument must be an l-value because
14616 // it is modified by va_arg.
14617 if (!E->isTypeDependent() &&
14618 CheckForModifiableLvalue(E, BuiltinLoc, *this))
14619 return ExprError();
14620 }
14621 }
14622
14623 if (!IsMS && !E->isTypeDependent() &&
14624 !Context.hasSameType(VaListType, E->getType()))
14625 return ExprError(
14626 Diag(E->getBeginLoc(),
14627 diag::err_first_argument_to_va_arg_not_of_type_va_list)
14628 << OrigExpr->getType() << E->getSourceRange());
14629
14630 if (!TInfo->getType()->isDependentType()) {
14631 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14632 diag::err_second_parameter_to_va_arg_incomplete,
14633 TInfo->getTypeLoc()))
14634 return ExprError();
14635
14636 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14637 TInfo->getType(),
14638 diag::err_second_parameter_to_va_arg_abstract,
14639 TInfo->getTypeLoc()))
14640 return ExprError();
14641
14642 if (!TInfo->getType().isPODType(Context)) {
14643 Diag(TInfo->getTypeLoc().getBeginLoc(),
14644 TInfo->getType()->isObjCLifetimeType()
14645 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14646 : diag::warn_second_parameter_to_va_arg_not_pod)
14647 << TInfo->getType()
14648 << TInfo->getTypeLoc().getSourceRange();
14649 }
14650
14651 // Check for va_arg where arguments of the given type will be promoted
14652 // (i.e. this va_arg is guaranteed to have undefined behavior).
14653 QualType PromoteType;
14654 if (TInfo->getType()->isPromotableIntegerType()) {
14655 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14656 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14657 PromoteType = QualType();
14658 }
14659 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14660 PromoteType = Context.DoubleTy;
14661 if (!PromoteType.isNull())
14662 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14663 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14664 << TInfo->getType()
14665 << PromoteType
14666 << TInfo->getTypeLoc().getSourceRange());
14667 }
14668
14669 QualType T = TInfo->getType().getNonLValueExprType(Context);
14670 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14671 }
14672
14673 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14674 // The type of __null will be int or long, depending on the size of
14675 // pointers on the target.
14676 QualType Ty;
14677 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14678 if (pw == Context.getTargetInfo().getIntWidth())
14679 Ty = Context.IntTy;
14680 else if (pw == Context.getTargetInfo().getLongWidth())
14681 Ty = Context.LongTy;
14682 else if (pw == Context.getTargetInfo().getLongLongWidth())
14683 Ty = Context.LongLongTy;
14684 else {
14685 llvm_unreachable("I don't know size of pointer!");
14686 }
14687
14688 return new (Context) GNUNullExpr(Ty, TokenLoc);
14689 }
14690
14691 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14692 SourceLocation BuiltinLoc,
14693 SourceLocation RPLoc) {
14694 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14695 }
14696
14697 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14698 SourceLocation BuiltinLoc,
14699 SourceLocation RPLoc,
14700 DeclContext *ParentContext) {
14701 return new (Context)
14702 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14703 }
14704
14705 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14706 bool Diagnose) {
14707 if (!getLangOpts().ObjC)
14708 return false;
14709
14710 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14711 if (!PT)
14712 return false;
14713
14714 if (!PT->isObjCIdType()) {
14715 // Check if the destination is the 'NSString' interface.
14716 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14717 if (!ID || !ID->getIdentifier()->isStr("NSString"))
14718 return false;
14719 }
14720
14721 // Ignore any parens, implicit casts (should only be
14722 // array-to-pointer decays), and not-so-opaque values. The last is
14723 // important for making this trigger for property assignments.
14724 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14725 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14726 if (OV->getSourceExpr())
14727 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14728
14729 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14730 if (!SL || !SL->isAscii())
14731 return false;
14732 if (Diagnose) {
14733 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14734 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14735 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14736 }
14737 return true;
14738 }
14739
14740 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14741 const Expr *SrcExpr) {
14742 if (!DstType->isFunctionPointerType() ||
14743 !SrcExpr->getType()->isFunctionType())
14744 return false;
14745
14746 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14747 if (!DRE)
14748 return false;
14749
14750 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14751 if (!FD)
14752 return false;
14753
14754 return !S.checkAddressOfFunctionIsAvailable(FD,
14755 /*Complain=*/true,
14756 SrcExpr->getBeginLoc());
14757 }
14758
14759 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14760 SourceLocation Loc,
14761 QualType DstType, QualType SrcType,
14762 Expr *SrcExpr, AssignmentAction Action,
14763 bool *Complained) {
14764 if (Complained)
14765 *Complained = false;
14766
14767 // Decode the result (notice that AST's are still created for extensions).
14768 bool CheckInferredResultType = false;
14769 bool isInvalid = false;
14770 unsigned DiagKind = 0;
14771 FixItHint Hint;
14772 ConversionFixItGenerator ConvHints;
14773 bool MayHaveConvFixit = false;
14774 bool MayHaveFunctionDiff = false;
14775 const ObjCInterfaceDecl *IFace = nullptr;
14776 const ObjCProtocolDecl *PDecl = nullptr;
14777
14778 switch (ConvTy) {
14779 case Compatible:
14780 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14781 return false;
14782
14783 case PointerToInt:
14784 DiagKind = diag::ext_typecheck_convert_pointer_int;
14785 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14786 MayHaveConvFixit = true;
14787 break;
14788 case IntToPointer:
14789 DiagKind = diag::ext_typecheck_convert_int_pointer;
14790 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14791 MayHaveConvFixit = true;
14792 break;
14793 case IncompatiblePointer:
14794 if (Action == AA_Passing_CFAudited)
14795 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14796 else if (SrcType->isFunctionPointerType() &&
14797 DstType->isFunctionPointerType())
14798 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14799 else
14800 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14801
14802 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14803 SrcType->isObjCObjectPointerType();
14804 if (Hint.isNull() && !CheckInferredResultType) {
14805 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14806 }
14807 else if (CheckInferredResultType) {
14808 SrcType = SrcType.getUnqualifiedType();
14809 DstType = DstType.getUnqualifiedType();
14810 }
14811 MayHaveConvFixit = true;
14812 break;
14813 case IncompatiblePointerSign:
14814 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14815 break;
14816 case FunctionVoidPointer:
14817 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14818 break;
14819 case IncompatiblePointerDiscardsQualifiers: {
14820 // Perform array-to-pointer decay if necessary.
14821 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14822
14823 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14824 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14825 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14826 DiagKind = diag::err_typecheck_incompatible_address_space;
14827 break;
14828
14829 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14830 DiagKind = diag::err_typecheck_incompatible_ownership;
14831 break;
14832 }
14833
14834 llvm_unreachable("unknown error case for discarding qualifiers!");
14835 // fallthrough
14836 }
14837 case CompatiblePointerDiscardsQualifiers:
14838 // If the qualifiers lost were because we were applying the
14839 // (deprecated) C++ conversion from a string literal to a char*
14840 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14841 // Ideally, this check would be performed in
14842 // checkPointerTypesForAssignment. However, that would require a
14843 // bit of refactoring (so that the second argument is an
14844 // expression, rather than a type), which should be done as part
14845 // of a larger effort to fix checkPointerTypesForAssignment for
14846 // C++ semantics.
14847 if (getLangOpts().CPlusPlus &&
14848 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14849 return false;
14850 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14851 break;
14852 case IncompatibleNestedPointerQualifiers:
14853 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14854 break;
14855 case IncompatibleNestedPointerAddressSpaceMismatch:
14856 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14857 break;
14858 case IntToBlockPointer:
14859 DiagKind = diag::err_int_to_block_pointer;
14860 break;
14861 case IncompatibleBlockPointer:
14862 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14863 break;
14864 case IncompatibleObjCQualifiedId: {
14865 if (SrcType->isObjCQualifiedIdType()) {
14866 const ObjCObjectPointerType *srcOPT =
14867 SrcType->castAs<ObjCObjectPointerType>();
14868 for (auto *srcProto : srcOPT->quals()) {
14869 PDecl = srcProto;
14870 break;
14871 }
14872 if (const ObjCInterfaceType *IFaceT =
14873 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14874 IFace = IFaceT->getDecl();
14875 }
14876 else if (DstType->isObjCQualifiedIdType()) {
14877 const ObjCObjectPointerType *dstOPT =
14878 DstType->castAs<ObjCObjectPointerType>();
14879 for (auto *dstProto : dstOPT->quals()) {
14880 PDecl = dstProto;
14881 break;
14882 }
14883 if (const ObjCInterfaceType *IFaceT =
14884 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14885 IFace = IFaceT->getDecl();
14886 }
14887 DiagKind = diag::warn_incompatible_qualified_id;
14888 break;
14889 }
14890 case IncompatibleVectors:
14891 DiagKind = diag::warn_incompatible_vectors;
14892 break;
14893 case IncompatibleObjCWeakRef:
14894 DiagKind = diag::err_arc_weak_unavailable_assign;
14895 break;
14896 case Incompatible:
14897 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14898 if (Complained)
14899 *Complained = true;
14900 return true;
14901 }
14902
14903 DiagKind = diag::err_typecheck_convert_incompatible;
14904 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14905 MayHaveConvFixit = true;
14906 isInvalid = true;
14907 MayHaveFunctionDiff = true;
14908 break;
14909 }
14910
14911 QualType FirstType, SecondType;
14912 switch (Action) {
14913 case AA_Assigning:
14914 case AA_Initializing:
14915 // The destination type comes first.
14916 FirstType = DstType;
14917 SecondType = SrcType;
14918 break;
14919
14920 case AA_Returning:
14921 case AA_Passing:
14922 case AA_Passing_CFAudited:
14923 case AA_Converting:
14924 case AA_Sending:
14925 case AA_Casting:
14926 // The source type comes first.
14927 FirstType = SrcType;
14928 SecondType = DstType;
14929 break;
14930 }
14931
14932 PartialDiagnostic FDiag = PDiag(DiagKind);
14933 if (Action == AA_Passing_CFAudited)
14934 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14935 else
14936 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14937
14938 // If we can fix the conversion, suggest the FixIts.
14939 assert(ConvHints.isNull() || Hint.isNull());
14940 if (!ConvHints.isNull()) {
14941 for (FixItHint &H : ConvHints.Hints)
14942 FDiag << H;
14943 } else {
14944 FDiag << Hint;
14945 }
14946 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14947
14948 if (MayHaveFunctionDiff)
14949 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14950
14951 Diag(Loc, FDiag);
14952 if (DiagKind == diag::warn_incompatible_qualified_id &&
14953 PDecl && IFace && !IFace->hasDefinition())
14954 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14955 << IFace << PDecl;
14956
14957 if (SecondType == Context.OverloadTy)
14958 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14959 FirstType, /*TakingAddress=*/true);
14960
14961 if (CheckInferredResultType)
14962 EmitRelatedResultTypeNote(SrcExpr);
14963
14964 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14965 EmitRelatedResultTypeNoteForReturn(DstType);
14966
14967 if (Complained)
14968 *Complained = true;
14969 return isInvalid;
14970 }
14971
14972 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14973 llvm::APSInt *Result) {
14974 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14975 public:
14976 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14977 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14978 }
14979 } Diagnoser;
14980
14981 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14982 }
14983
14984 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14985 llvm::APSInt *Result,
14986 unsigned DiagID,
14987 bool AllowFold) {
14988 class IDDiagnoser : public VerifyICEDiagnoser {
14989 unsigned DiagID;
14990
14991 public:
14992 IDDiagnoser(unsigned DiagID)
14993 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14994
14995 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14996 S.Diag(Loc, DiagID) << SR;
14997 }
14998 } Diagnoser(DiagID);
14999
15000 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15001 }
15002
15003 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15004 SourceRange SR) {
15005 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15006 }
15007
15008 ExprResult
15009 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15010 VerifyICEDiagnoser &Diagnoser,
15011 bool AllowFold) {
15012 SourceLocation DiagLoc = E->getBeginLoc();
15013
15014 if (getLangOpts().CPlusPlus11) {
15015 // C++11 [expr.const]p5:
15016 // If an expression of literal class type is used in a context where an
15017 // integral constant expression is required, then that class type shall
15018 // have a single non-explicit conversion function to an integral or
15019 // unscoped enumeration type
15020 ExprResult Converted;
15021 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15022 public:
15023 CXX11ConvertDiagnoser(bool Silent)
15024 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15025 Silent, true) {}
15026
15027 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15028 QualType T) override {
15029 return S.Diag(Loc, diag::err_ice_not_integral) << T;
15030 }
15031
15032 SemaDiagnosticBuilder diagnoseIncomplete(
15033 Sema &S, SourceLocation Loc, QualType T) override {
15034 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15035 }
15036
15037 SemaDiagnosticBuilder diagnoseExplicitConv(
15038 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15039 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15040 }
15041
15042 SemaDiagnosticBuilder noteExplicitConv(
15043 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15044 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15045 << ConvTy->isEnumeralType() << ConvTy;
15046 }
15047
15048 SemaDiagnosticBuilder diagnoseAmbiguous(
15049 Sema &S, SourceLocation Loc, QualType T) override {
15050 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15051 }
15052
15053 SemaDiagnosticBuilder noteAmbiguous(
15054 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15055 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15056 << ConvTy->isEnumeralType() << ConvTy;
15057 }
15058
15059 SemaDiagnosticBuilder diagnoseConversion(
15060 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15061 llvm_unreachable("conversion functions are permitted");
15062 }
15063 } ConvertDiagnoser(Diagnoser.Suppress);
15064
15065 Converted = PerformContextualImplicitConversion(DiagLoc, E,
15066 ConvertDiagnoser);
15067 if (Converted.isInvalid())
15068 return Converted;
15069 E = Converted.get();
15070 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15071 return ExprError();
15072 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15073 // An ICE must be of integral or unscoped enumeration type.
15074 if (!Diagnoser.Suppress)
15075 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15076 return ExprError();
15077 }
15078
15079 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15080 // in the non-ICE case.
15081 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15082 if (Result)
15083 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15084 if (!isa<ConstantExpr>(E))
15085 E = ConstantExpr::Create(Context, E);
15086 return E;
15087 }
15088
15089 Expr::EvalResult EvalResult;
15090 SmallVector<PartialDiagnosticAt, 8> Notes;
15091 EvalResult.Diag = &Notes;
15092
15093 // Try to evaluate the expression, and produce diagnostics explaining why it's
15094 // not a constant expression as a side-effect.
15095 bool Folded =
15096 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15097 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15098
15099 if (!isa<ConstantExpr>(E))
15100 E = ConstantExpr::Create(Context, E, EvalResult.Val);
15101
15102 // In C++11, we can rely on diagnostics being produced for any expression
15103 // which is not a constant expression. If no diagnostics were produced, then
15104 // this is a constant expression.
15105 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15106 if (Result)
15107 *Result = EvalResult.Val.getInt();
15108 return E;
15109 }
15110
15111 // If our only note is the usual "invalid subexpression" note, just point
15112 // the caret at its location rather than producing an essentially
15113 // redundant note.
15114 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15115 diag::note_invalid_subexpr_in_const_expr) {
15116 DiagLoc = Notes[0].first;
15117 Notes.clear();
15118 }
15119
15120 if (!Folded || !AllowFold) {
15121 if (!Diagnoser.Suppress) {
15122 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15123 for (const PartialDiagnosticAt &Note : Notes)
15124 Diag(Note.first, Note.second);
15125 }
15126
15127 return ExprError();
15128 }
15129
15130 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15131 for (const PartialDiagnosticAt &Note : Notes)
15132 Diag(Note.first, Note.second);
15133
15134 if (Result)
15135 *Result = EvalResult.Val.getInt();
15136 return E;
15137 }
15138
15139 namespace {
15140 // Handle the case where we conclude a expression which we speculatively
15141 // considered to be unevaluated is actually evaluated.
15142 class TransformToPE : public TreeTransform<TransformToPE> {
15143 typedef TreeTransform<TransformToPE> BaseTransform;
15144
15145 public:
15146 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15147
15148 // Make sure we redo semantic analysis
15149 bool AlwaysRebuild() { return true; }
15150 bool ReplacingOriginal() { return true; }
15151
15152 // We need to special-case DeclRefExprs referring to FieldDecls which
15153 // are not part of a member pointer formation; normal TreeTransforming
15154 // doesn't catch this case because of the way we represent them in the AST.
15155 // FIXME: This is a bit ugly; is it really the best way to handle this
15156 // case?
15157 //
15158 // Error on DeclRefExprs referring to FieldDecls.
15159 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15160 if (isa<FieldDecl>(E->getDecl()) &&
15161 !SemaRef.isUnevaluatedContext())
15162 return SemaRef.Diag(E->getLocation(),
15163 diag::err_invalid_non_static_member_use)
15164 << E->getDecl() << E->getSourceRange();
15165
15166 return BaseTransform::TransformDeclRefExpr(E);
15167 }
15168
15169 // Exception: filter out member pointer formation
15170 ExprResult TransformUnaryOperator(UnaryOperator *E) {
15171 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15172 return E;
15173
15174 return BaseTransform::TransformUnaryOperator(E);
15175 }
15176
15177 // The body of a lambda-expression is in a separate expression evaluation
15178 // context so never needs to be transformed.
15179 // FIXME: Ideally we wouldn't transform the closure type either, and would
15180 // just recreate the capture expressions and lambda expression.
15181 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15182 return SkipLambdaBody(E, Body);
15183 }
15184 };
15185 }
15186
15187 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15188 assert(isUnevaluatedContext() &&
15189 "Should only transform unevaluated expressions");
15190 ExprEvalContexts.back().Context =
15191 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15192 if (isUnevaluatedContext())
15193 return E;
15194 return TransformToPE(*this).TransformExpr(E);
15195 }
15196
15197 void
15198 Sema::PushExpressionEvaluationContext(
15199 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15200 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15201 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15202 LambdaContextDecl, ExprContext);
15203 Cleanup.reset();
15204 if (!MaybeODRUseExprs.empty())
15205 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15206 }
15207
15208 void
15209 Sema::PushExpressionEvaluationContext(
15210 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15211 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15212 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15213 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15214 }
15215
15216 namespace {
15217
15218 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15219 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15220 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15221 if (E->getOpcode() == UO_Deref)
15222 return CheckPossibleDeref(S, E->getSubExpr());
15223 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15224 return CheckPossibleDeref(S, E->getBase());
15225 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15226 return CheckPossibleDeref(S, E->getBase());
15227 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15228 QualType Inner;
15229 QualType Ty = E->getType();
15230 if (const auto *Ptr = Ty->getAs<PointerType>())
15231 Inner = Ptr->getPointeeType();
15232 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15233 Inner = Arr->getElementType();
15234 else
15235 return nullptr;
15236
15237 if (Inner->hasAttr(attr::NoDeref))
15238 return E;
15239 }
15240 return nullptr;
15241 }
15242
15243 } // namespace
15244
15245 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15246 for (const Expr *E : Rec.PossibleDerefs) {
15247 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15248 if (DeclRef) {
15249 const ValueDecl *Decl = DeclRef->getDecl();
15250 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15251 << Decl->getName() << E->getSourceRange();
15252 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15253 } else {
15254 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15255 << E->getSourceRange();
15256 }
15257 }
15258 Rec.PossibleDerefs.clear();
15259 }
15260
15261 /// Check whether E, which is either a discarded-value expression or an
15262 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15263 /// and if so, remove it from the list of volatile-qualified assignments that
15264 /// we are going to warn are deprecated.
15265 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15266 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15267 return;
15268
15269 // Note: ignoring parens here is not justified by the standard rules, but
15270 // ignoring parentheses seems like a more reasonable approach, and this only
15271 // drives a deprecation warning so doesn't affect conformance.
15272 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15273 if (BO->getOpcode() == BO_Assign) {
15274 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15275 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15276 LHSs.end());
15277 }
15278 }
15279 }
15280
15281 void Sema::PopExpressionEvaluationContext() {
15282 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15283 unsigned NumTypos = Rec.NumTypos;
15284
15285 if (!Rec.Lambdas.empty()) {
15286 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15287 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15288 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15289 unsigned D;
15290 if (Rec.isUnevaluated()) {
15291 // C++11 [expr.prim.lambda]p2:
15292 // A lambda-expression shall not appear in an unevaluated operand
15293 // (Clause 5).
15294 D = diag::err_lambda_unevaluated_operand;
15295 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15296 // C++1y [expr.const]p2:
15297 // A conditional-expression e is a core constant expression unless the
15298 // evaluation of e, following the rules of the abstract machine, would
15299 // evaluate [...] a lambda-expression.
15300 D = diag::err_lambda_in_constant_expression;
15301 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15302 // C++17 [expr.prim.lamda]p2:
15303 // A lambda-expression shall not appear [...] in a template-argument.
15304 D = diag::err_lambda_in_invalid_context;
15305 } else
15306 llvm_unreachable("Couldn't infer lambda error message.");
15307
15308 for (const auto *L : Rec.Lambdas)
15309 Diag(L->getBeginLoc(), D);
15310 }
15311 }
15312
15313 WarnOnPendingNoDerefs(Rec);
15314
15315 // Warn on any volatile-qualified simple-assignments that are not discarded-
15316 // value expressions nor unevaluated operands (those cases get removed from
15317 // this list by CheckUnusedVolatileAssignment).
15318 for (auto *BO : Rec.VolatileAssignmentLHSs)
15319 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15320 << BO->getType();
15321
15322 // When are coming out of an unevaluated context, clear out any
15323 // temporaries that we may have created as part of the evaluation of
15324 // the expression in that context: they aren't relevant because they
15325 // will never be constructed.
15326 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15327 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15328 ExprCleanupObjects.end());
15329 Cleanup = Rec.ParentCleanup;
15330 CleanupVarDeclMarking();
15331 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15332 // Otherwise, merge the contexts together.
15333 } else {
15334 Cleanup.mergeFrom(Rec.ParentCleanup);
15335 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15336 Rec.SavedMaybeODRUseExprs.end());
15337 }
15338
15339 // Pop the current expression evaluation context off the stack.
15340 ExprEvalContexts.pop_back();
15341
15342 // The global expression evaluation context record is never popped.
15343 ExprEvalContexts.back().NumTypos += NumTypos;
15344 }
15345
15346 void Sema::DiscardCleanupsInEvaluationContext() {
15347 ExprCleanupObjects.erase(
15348 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15349 ExprCleanupObjects.end());
15350 Cleanup.reset();
15351 MaybeODRUseExprs.clear();
15352 }
15353
15354 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15355 ExprResult Result = CheckPlaceholderExpr(E);
15356 if (Result.isInvalid())
15357 return ExprError();
15358 E = Result.get();
15359 if (!E->getType()->isVariablyModifiedType())
15360 return E;
15361 return TransformToPotentiallyEvaluated(E);
15362 }
15363
15364 /// Are we in a context that is potentially constant evaluated per C++20
15365 /// [expr.const]p12?
15366 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15367 /// C++2a [expr.const]p12:
15368 // An expression or conversion is potentially constant evaluated if it is
15369 switch (SemaRef.ExprEvalContexts.back().Context) {
15370 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15371 // -- a manifestly constant-evaluated expression,
15372 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15373 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15374 case Sema::ExpressionEvaluationContext::DiscardedStatement:
15375 // -- a potentially-evaluated expression,
15376 case Sema::ExpressionEvaluationContext::UnevaluatedList:
15377 // -- an immediate subexpression of a braced-init-list,
15378
15379 // -- [FIXME] an expression of the form & cast-expression that occurs
15380 // within a templated entity
15381 // -- a subexpression of one of the above that is not a subexpression of
15382 // a nested unevaluated operand.
15383 return true;
15384
15385 case Sema::ExpressionEvaluationContext::Unevaluated:
15386 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15387 // Expressions in this context are never evaluated.
15388 return false;
15389 }
15390 llvm_unreachable("Invalid context");
15391 }
15392
15393 /// Return true if this function has a calling convention that requires mangling
15394 /// in the size of the parameter pack.
15395 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15396 // These manglings don't do anything on non-Windows or non-x86 platforms, so
15397 // we don't need parameter type sizes.
15398 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15399 if (!TT.isOSWindows() || !TT.isX86())
15400 return false;
15401
15402 // If this is C++ and this isn't an extern "C" function, parameters do not
15403 // need to be complete. In this case, C++ mangling will apply, which doesn't
15404 // use the size of the parameters.
15405 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15406 return false;
15407
15408 // Stdcall, fastcall, and vectorcall need this special treatment.
15409 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15410 switch (CC) {
15411 case CC_X86StdCall:
15412 case CC_X86FastCall:
15413 case CC_X86VectorCall:
15414 return true;
15415 default:
15416 break;
15417 }
15418 return false;
15419 }
15420
15421 /// Require that all of the parameter types of function be complete. Normally,
15422 /// parameter types are only required to be complete when a function is called
15423 /// or defined, but to mangle functions with certain calling conventions, the
15424 /// mangler needs to know the size of the parameter list. In this situation,
15425 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15426 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15427 /// result in a linker error. Clang doesn't implement this behavior, and instead
15428 /// attempts to error at compile time.
15429 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15430 SourceLocation Loc) {
15431 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15432 FunctionDecl *FD;
15433 ParmVarDecl *Param;
15434
15435 public:
15436 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15437 : FD(FD), Param(Param) {}
15438
15439 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15440 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15441 StringRef CCName;
15442 switch (CC) {
15443 case CC_X86StdCall:
15444 CCName = "stdcall";
15445 break;
15446 case CC_X86FastCall:
15447 CCName = "fastcall";
15448 break;
15449 case CC_X86VectorCall:
15450 CCName = "vectorcall";
15451 break;
15452 default:
15453 llvm_unreachable("CC does not need mangling");
15454 }
15455
15456 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15457 << Param->getDeclName() << FD->getDeclName() << CCName;
15458 }
15459 };
15460
15461 for (ParmVarDecl *Param : FD->parameters()) {
15462 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15463 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15464 }
15465 }
15466
15467 namespace {
15468 enum class OdrUseContext {
15469 /// Declarations in this context are not odr-used.
15470 None,
15471 /// Declarations in this context are formally odr-used, but this is a
15472 /// dependent context.
15473 Dependent,
15474 /// Declarations in this context are odr-used but not actually used (yet).
15475 FormallyOdrUsed,
15476 /// Declarations in this context are used.
15477 Used
15478 };
15479 }
15480
15481 /// Are we within a context in which references to resolved functions or to
15482 /// variables result in odr-use?
15483 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15484 OdrUseContext Result;
15485
15486 switch (SemaRef.ExprEvalContexts.back().Context) {
15487 case Sema::ExpressionEvaluationContext::Unevaluated:
15488 case Sema::ExpressionEvaluationContext::UnevaluatedList:
15489 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15490 return OdrUseContext::None;
15491
15492 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15493 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15494 Result = OdrUseContext::Used;
15495 break;
15496
15497 case Sema::ExpressionEvaluationContext::DiscardedStatement:
15498 Result = OdrUseContext::FormallyOdrUsed;
15499 break;
15500
15501 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15502 // A default argument formally results in odr-use, but doesn't actually
15503 // result in a use in any real sense until it itself is used.
15504 Result = OdrUseContext::FormallyOdrUsed;
15505 break;
15506 }
15507
15508 if (SemaRef.CurContext->isDependentContext())
15509 return OdrUseContext::Dependent;
15510
15511 return Result;
15512 }
15513
15514 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15515 return Func->isConstexpr() &&
15516 (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
15517 }
15518
15519 /// Mark a function referenced, and check whether it is odr-used
15520 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15521 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15522 bool MightBeOdrUse) {
15523 assert(Func && "No function?");
15524
15525 Func->setReferenced();
15526
15527 // Recursive functions aren't really used until they're used from some other
15528 // context.
15529 bool IsRecursiveCall = CurContext == Func;
15530
15531 // C++11 [basic.def.odr]p3:
15532 // A function whose name appears as a potentially-evaluated expression is
15533 // odr-used if it is the unique lookup result or the selected member of a
15534 // set of overloaded functions [...].
15535 //
15536 // We (incorrectly) mark overload resolution as an unevaluated context, so we
15537 // can just check that here.
15538 OdrUseContext OdrUse =
15539 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15540 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15541 OdrUse = OdrUseContext::FormallyOdrUsed;
15542
15543 // Trivial default constructors and destructors are never actually used.
15544 // FIXME: What about other special members?
15545 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15546 OdrUse == OdrUseContext::Used) {
15547 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15548 if (Constructor->isDefaultConstructor())
15549 OdrUse = OdrUseContext::FormallyOdrUsed;
15550 if (isa<CXXDestructorDecl>(Func))
15551 OdrUse = OdrUseContext::FormallyOdrUsed;
15552 }
15553
15554 // C++20 [expr.const]p12:
15555 // A function [...] is needed for constant evaluation if it is [...] a
15556 // constexpr function that is named by an expression that is potentially
15557 // constant evaluated
15558 bool NeededForConstantEvaluation =
15559 isPotentiallyConstantEvaluatedContext(*this) &&
15560 isImplicitlyDefinableConstexprFunction(Func);
15561
15562 // Determine whether we require a function definition to exist, per
15563 // C++11 [temp.inst]p3:
15564 // Unless a function template specialization has been explicitly
15565 // instantiated or explicitly specialized, the function template
15566 // specialization is implicitly instantiated when the specialization is
15567 // referenced in a context that requires a function definition to exist.
15568 // C++20 [temp.inst]p7:
15569 // The existence of a definition of a [...] function is considered to
15570 // affect the semantics of the program if the [...] function is needed for
15571 // constant evaluation by an expression
15572 // C++20 [basic.def.odr]p10:
15573 // Every program shall contain exactly one definition of every non-inline
15574 // function or variable that is odr-used in that program outside of a
15575 // discarded statement
15576 // C++20 [special]p1:
15577 // The implementation will implicitly define [defaulted special members]
15578 // if they are odr-used or needed for constant evaluation.
15579 //
15580 // Note that we skip the implicit instantiation of templates that are only
15581 // used in unused default arguments or by recursive calls to themselves.
15582 // This is formally non-conforming, but seems reasonable in practice.
15583 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15584 NeededForConstantEvaluation);
15585
15586 // C++14 [temp.expl.spec]p6:
15587 // If a template [...] is explicitly specialized then that specialization
15588 // shall be declared before the first use of that specialization that would
15589 // cause an implicit instantiation to take place, in every translation unit
15590 // in which such a use occurs
15591 if (NeedDefinition &&
15592 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15593 Func->getMemberSpecializationInfo()))
15594 checkSpecializationVisibility(Loc, Func);
15595
15596 if (getLangOpts().CUDA)
15597 CheckCUDACall(Loc, Func);
15598
15599 // If we need a definition, try to create one.
15600 if (NeedDefinition && !Func->getBody()) {
15601 runWithSufficientStackSpace(Loc, [&] {
15602 if (CXXConstructorDecl *Constructor =
15603 dyn_cast<CXXConstructorDecl>(Func)) {
15604 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15605 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15606 if (Constructor->isDefaultConstructor()) {
15607 if (Constructor->isTrivial() &&
15608 !Constructor->hasAttr<DLLExportAttr>())
15609 return;
15610 DefineImplicitDefaultConstructor(Loc, Constructor);
15611 } else if (Constructor->isCopyConstructor()) {
15612 DefineImplicitCopyConstructor(Loc, Constructor);
15613 } else if (Constructor->isMoveConstructor()) {
15614 DefineImplicitMoveConstructor(Loc, Constructor);
15615 }
15616 } else if (Constructor->getInheritedConstructor()) {
15617 DefineInheritingConstructor(Loc, Constructor);
15618 }
15619 } else if (CXXDestructorDecl *Destructor =
15620 dyn_cast<CXXDestructorDecl>(Func)) {
15621 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15622 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15623 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15624 return;
15625 DefineImplicitDestructor(Loc, Destructor);
15626 }
15627 if (Destructor->isVirtual() && getLangOpts().AppleKext)
15628 MarkVTableUsed(Loc, Destructor->getParent());
15629 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15630 if (MethodDecl->isOverloadedOperator() &&
15631 MethodDecl->getOverloadedOperator() == OO_Equal) {
15632 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15633 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15634 if (MethodDecl->isCopyAssignmentOperator())
15635 DefineImplicitCopyAssignment(Loc, MethodDecl);
15636 else if (MethodDecl->isMoveAssignmentOperator())
15637 DefineImplicitMoveAssignment(Loc, MethodDecl);
15638 }
15639 } else if (isa<CXXConversionDecl>(MethodDecl) &&
15640 MethodDecl->getParent()->isLambda()) {
15641 CXXConversionDecl *Conversion =
15642 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15643 if (Conversion->isLambdaToBlockPointerConversion())
15644 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15645 else
15646 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15647 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15648 MarkVTableUsed(Loc, MethodDecl->getParent());
15649 }
15650
15651 if (Func->isDefaulted() && !Func->isDeleted()) {
15652 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
15653 if (DCK != DefaultedComparisonKind::None)
15654 DefineDefaultedComparison(Loc, Func, DCK);
15655 }
15656
15657 // Implicit instantiation of function templates and member functions of
15658 // class templates.
15659 if (Func->isImplicitlyInstantiable()) {
15660 TemplateSpecializationKind TSK =
15661 Func->getTemplateSpecializationKindForInstantiation();
15662 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15663 bool FirstInstantiation = PointOfInstantiation.isInvalid();
15664 if (FirstInstantiation) {
15665 PointOfInstantiation = Loc;
15666 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15667 } else if (TSK != TSK_ImplicitInstantiation) {
15668 // Use the point of use as the point of instantiation, instead of the
15669 // point of explicit instantiation (which we track as the actual point
15670 // of instantiation). This gives better backtraces in diagnostics.
15671 PointOfInstantiation = Loc;
15672 }
15673
15674 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15675 Func->isConstexpr()) {
15676 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15677 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15678 CodeSynthesisContexts.size())
15679 PendingLocalImplicitInstantiations.push_back(
15680 std::make_pair(Func, PointOfInstantiation));
15681 else if (Func->isConstexpr())
15682 // Do not defer instantiations of constexpr functions, to avoid the
15683 // expression evaluator needing to call back into Sema if it sees a
15684 // call to such a function.
15685 InstantiateFunctionDefinition(PointOfInstantiation, Func);
15686 else {
15687 Func->setInstantiationIsPending(true);
15688 PendingInstantiations.push_back(
15689 std::make_pair(Func, PointOfInstantiation));
15690 // Notify the consumer that a function was implicitly instantiated.
15691 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15692 }
15693 }
15694 } else {
15695 // Walk redefinitions, as some of them may be instantiable.
15696 for (auto i : Func->redecls()) {
15697 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15698 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15699 }
15700 }
15701 });
15702 }
15703
15704 // C++14 [except.spec]p17:
15705 // An exception-specification is considered to be needed when:
15706 // - the function is odr-used or, if it appears in an unevaluated operand,
15707 // would be odr-used if the expression were potentially-evaluated;
15708 //
15709 // Note, we do this even if MightBeOdrUse is false. That indicates that the
15710 // function is a pure virtual function we're calling, and in that case the
15711 // function was selected by overload resolution and we need to resolve its
15712 // exception specification for a different reason.
15713 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15714 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15715 ResolveExceptionSpec(Loc, FPT);
15716
15717 // If this is the first "real" use, act on that.
15718 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15719 // Keep track of used but undefined functions.
15720 if (!Func->isDefined()) {
15721 if (mightHaveNonExternalLinkage(Func))
15722 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15723 else if (Func->getMostRecentDecl()->isInlined() &&
15724 !LangOpts.GNUInline &&
15725 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15726 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15727 else if (isExternalWithNoLinkageType(Func))
15728 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15729 }
15730
15731 // Some x86 Windows calling conventions mangle the size of the parameter
15732 // pack into the name. Computing the size of the parameters requires the
15733 // parameter types to be complete. Check that now.
15734 if (funcHasParameterSizeMangling(*this, Func))
15735 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15736
15737 Func->markUsed(Context);
15738 }
15739
15740 if (LangOpts.OpenMP) {
15741 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15742 if (LangOpts.OpenMPIsDevice)
15743 checkOpenMPDeviceFunction(Loc, Func);
15744 else
15745 checkOpenMPHostFunction(Loc, Func);
15746 }
15747 }
15748
15749 /// Directly mark a variable odr-used. Given a choice, prefer to use
15750 /// MarkVariableReferenced since it does additional checks and then
15751 /// calls MarkVarDeclODRUsed.
15752 /// If the variable must be captured:
15753 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15754 /// - else capture it in the DeclContext that maps to the
15755 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15756 static void
15757 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15758 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15759 // Keep track of used but undefined variables.
15760 // FIXME: We shouldn't suppress this warning for static data members.
15761 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15762 (!Var->isExternallyVisible() || Var->isInline() ||
15763 SemaRef.isExternalWithNoLinkageType(Var)) &&
15764 !(Var->isStaticDataMember() && Var->hasInit())) {
15765 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15766 if (old.isInvalid())
15767 old = Loc;
15768 }
15769 QualType CaptureType, DeclRefType;
15770 if (SemaRef.LangOpts.OpenMP)
15771 SemaRef.tryCaptureOpenMPLambdas(Var);
15772 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15773 /*EllipsisLoc*/ SourceLocation(),
15774 /*BuildAndDiagnose*/ true,
15775 CaptureType, DeclRefType,
15776 FunctionScopeIndexToStopAt);
15777
15778 Var->markUsed(SemaRef.Context);
15779 }
15780
15781 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15782 SourceLocation Loc,
15783 unsigned CapturingScopeIndex) {
15784 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15785 }
15786
15787 static void
15788 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15789 ValueDecl *var, DeclContext *DC) {
15790 DeclContext *VarDC = var->getDeclContext();
15791
15792 // If the parameter still belongs to the translation unit, then
15793 // we're actually just using one parameter in the declaration of
15794 // the next.
15795 if (isa<ParmVarDecl>(var) &&
15796 isa<TranslationUnitDecl>(VarDC))
15797 return;
15798
15799 // For C code, don't diagnose about capture if we're not actually in code
15800 // right now; it's impossible to write a non-constant expression outside of
15801 // function context, so we'll get other (more useful) diagnostics later.
15802 //
15803 // For C++, things get a bit more nasty... it would be nice to suppress this
15804 // diagnostic for certain cases like using a local variable in an array bound
15805 // for a member of a local class, but the correct predicate is not obvious.
15806 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15807 return;
15808
15809 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15810 unsigned ContextKind = 3; // unknown
15811 if (isa<CXXMethodDecl>(VarDC) &&
15812 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15813 ContextKind = 2;
15814 } else if (isa<FunctionDecl>(VarDC)) {
15815 ContextKind = 0;
15816 } else if (isa<BlockDecl>(VarDC)) {
15817 ContextKind = 1;
15818 }
15819
15820 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15821 << var << ValueKind << ContextKind << VarDC;
15822 S.Diag(var->getLocation(), diag::note_entity_declared_at)
15823 << var;
15824
15825 // FIXME: Add additional diagnostic info about class etc. which prevents
15826 // capture.
15827 }
15828
15829
15830 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15831 bool &SubCapturesAreNested,
15832 QualType &CaptureType,
15833 QualType &DeclRefType) {
15834 // Check whether we've already captured it.
15835 if (CSI->CaptureMap.count(Var)) {
15836 // If we found a capture, any subcaptures are nested.
15837 SubCapturesAreNested = true;
15838
15839 // Retrieve the capture type for this variable.
15840 CaptureType = CSI->getCapture(Var).getCaptureType();
15841
15842 // Compute the type of an expression that refers to this variable.
15843 DeclRefType = CaptureType.getNonReferenceType();
15844
15845 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15846 // are mutable in the sense that user can change their value - they are
15847 // private instances of the captured declarations.
15848 const Capture &Cap = CSI->getCapture(Var);
15849 if (Cap.isCopyCapture() &&
15850 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15851 !(isa<CapturedRegionScopeInfo>(CSI) &&
15852 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15853 DeclRefType.addConst();
15854 return true;
15855 }
15856 return false;
15857 }
15858
15859 // Only block literals, captured statements, and lambda expressions can
15860 // capture; other scopes don't work.
15861 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15862 SourceLocation Loc,
15863 const bool Diagnose, Sema &S) {
15864 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15865 return getLambdaAwareParentOfDeclContext(DC);
15866 else if (Var->hasLocalStorage()) {
15867 if (Diagnose)
15868 diagnoseUncapturableValueReference(S, Loc, Var, DC);
15869 }
15870 return nullptr;
15871 }
15872
15873 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15874 // certain types of variables (unnamed, variably modified types etc.)
15875 // so check for eligibility.
15876 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15877 SourceLocation Loc,
15878 const bool Diagnose, Sema &S) {
15879
15880 bool IsBlock = isa<BlockScopeInfo>(CSI);
15881 bool IsLambda = isa<LambdaScopeInfo>(CSI);
15882
15883 // Lambdas are not allowed to capture unnamed variables
15884 // (e.g. anonymous unions).
15885 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15886 // assuming that's the intent.
15887 if (IsLambda && !Var->getDeclName()) {
15888 if (Diagnose) {
15889 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15890 S.Diag(Var->getLocation(), diag::note_declared_at);
15891 }
15892 return false;
15893 }
15894
15895 // Prohibit variably-modified types in blocks; they're difficult to deal with.
15896 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15897 if (Diagnose) {
15898 S.Diag(Loc, diag::err_ref_vm_type);
15899 S.Diag(Var->getLocation(), diag::note_previous_decl)
15900 << Var->getDeclName();
15901 }
15902 return false;
15903 }
15904 // Prohibit structs with flexible array members too.
15905 // We cannot capture what is in the tail end of the struct.
15906 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15907 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15908 if (Diagnose) {
15909 if (IsBlock)
15910 S.Diag(Loc, diag::err_ref_flexarray_type);
15911 else
15912 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15913 << Var->getDeclName();
15914 S.Diag(Var->getLocation(), diag::note_previous_decl)
15915 << Var->getDeclName();
15916 }
15917 return false;
15918 }
15919 }
15920 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15921 // Lambdas and captured statements are not allowed to capture __block
15922 // variables; they don't support the expected semantics.
15923 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15924 if (Diagnose) {
15925 S.Diag(Loc, diag::err_capture_block_variable)
15926 << Var->getDeclName() << !IsLambda;
15927 S.Diag(Var->getLocation(), diag::note_previous_decl)
15928 << Var->getDeclName();
15929 }
15930 return false;
15931 }
15932 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15933 if (S.getLangOpts().OpenCL && IsBlock &&
15934 Var->getType()->isBlockPointerType()) {
15935 if (Diagnose)
15936 S.Diag(Loc, diag::err_opencl_block_ref_block);
15937 return false;
15938 }
15939
15940 return true;
15941 }
15942
15943 // Returns true if the capture by block was successful.
15944 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15945 SourceLocation Loc,
15946 const bool BuildAndDiagnose,
15947 QualType &CaptureType,
15948 QualType &DeclRefType,
15949 const bool Nested,
15950 Sema &S, bool Invalid) {
15951 bool ByRef = false;
15952
15953 // Blocks are not allowed to capture arrays, excepting OpenCL.
15954 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15955 // (decayed to pointers).
15956 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15957 if (BuildAndDiagnose) {
15958 S.Diag(Loc, diag::err_ref_array_type);
15959 S.Diag(Var->getLocation(), diag::note_previous_decl)
15960 << Var->getDeclName();
15961 Invalid = true;
15962 } else {
15963 return false;
15964 }
15965 }
15966
15967 // Forbid the block-capture of autoreleasing variables.
15968 if (!Invalid &&
15969 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15970 if (BuildAndDiagnose) {
15971 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15972 << /*block*/ 0;
15973 S.Diag(Var->getLocation(), diag::note_previous_decl)
15974 << Var->getDeclName();
15975 Invalid = true;
15976 } else {
15977 return false;
15978 }
15979 }
15980
15981 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15982 if (const auto *PT = CaptureType->getAs<PointerType>()) {
15983 QualType PointeeTy = PT->getPointeeType();
15984
15985 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15986 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15987 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15988 if (BuildAndDiagnose) {
15989 SourceLocation VarLoc = Var->getLocation();
15990 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15991 S.Diag(VarLoc, diag::note_declare_parameter_strong);
15992 }
15993 }
15994 }
15995
15996 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15997 if (HasBlocksAttr || CaptureType->isReferenceType() ||
15998 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15999 // Block capture by reference does not change the capture or
16000 // declaration reference types.
16001 ByRef = true;
16002 } else {
16003 // Block capture by copy introduces 'const'.
16004 CaptureType = CaptureType.getNonReferenceType().withConst();
16005 DeclRefType = CaptureType;
16006 }
16007
16008 // Actually capture the variable.
16009 if (BuildAndDiagnose)
16010 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16011 CaptureType, Invalid);
16012
16013 return !Invalid;
16014 }
16015
16016
16017 /// Capture the given variable in the captured region.
16018 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16019 VarDecl *Var,
16020 SourceLocation Loc,
16021 const bool BuildAndDiagnose,
16022 QualType &CaptureType,
16023 QualType &DeclRefType,
16024 const bool RefersToCapturedVariable,
16025 Sema &S, bool Invalid) {
16026 // By default, capture variables by reference.
16027 bool ByRef = true;
16028 // Using an LValue reference type is consistent with Lambdas (see below).
16029 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16030 if (S.isOpenMPCapturedDecl(Var)) {
16031 bool HasConst = DeclRefType.isConstQualified();
16032 DeclRefType = DeclRefType.getUnqualifiedType();
16033 // Don't lose diagnostics about assignments to const.
16034 if (HasConst)
16035 DeclRefType.addConst();
16036 }
16037 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16038 RSI->OpenMPCaptureLevel);
16039 }
16040
16041 if (ByRef)
16042 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16043 else
16044 CaptureType = DeclRefType;
16045
16046 // Actually capture the variable.
16047 if (BuildAndDiagnose)
16048 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16049 Loc, SourceLocation(), CaptureType, Invalid);
16050
16051 return !Invalid;
16052 }
16053
16054 /// Capture the given variable in the lambda.
16055 static bool captureInLambda(LambdaScopeInfo *LSI,
16056 VarDecl *Var,
16057 SourceLocation Loc,
16058 const bool BuildAndDiagnose,
16059 QualType &CaptureType,
16060 QualType &DeclRefType,
16061 const bool RefersToCapturedVariable,
16062 const Sema::TryCaptureKind Kind,
16063 SourceLocation EllipsisLoc,
16064 const bool IsTopScope,
16065 Sema &S, bool Invalid) {
16066 // Determine whether we are capturing by reference or by value.
16067 bool ByRef = false;
16068 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16069 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16070 } else {
16071 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16072 }
16073
16074 // Compute the type of the field that will capture this variable.
16075 if (ByRef) {
16076 // C++11 [expr.prim.lambda]p15:
16077 // An entity is captured by reference if it is implicitly or
16078 // explicitly captured but not captured by copy. It is
16079 // unspecified whether additional unnamed non-static data
16080 // members are declared in the closure type for entities
16081 // captured by reference.
16082 //
16083 // FIXME: It is not clear whether we want to build an lvalue reference
16084 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16085 // to do the former, while EDG does the latter. Core issue 1249 will
16086 // clarify, but for now we follow GCC because it's a more permissive and
16087 // easily defensible position.
16088 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16089 } else {
16090 // C++11 [expr.prim.lambda]p14:
16091 // For each entity captured by copy, an unnamed non-static
16092 // data member is declared in the closure type. The
16093 // declaration order of these members is unspecified. The type
16094 // of such a data member is the type of the corresponding
16095 // captured entity if the entity is not a reference to an
16096 // object, or the referenced type otherwise. [Note: If the
16097 // captured entity is a reference to a function, the
16098 // corresponding data member is also a reference to a
16099 // function. - end note ]
16100 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16101 if (!RefType->getPointeeType()->isFunctionType())
16102 CaptureType = RefType->getPointeeType();
16103 }
16104
16105 // Forbid the lambda copy-capture of autoreleasing variables.
16106 if (!Invalid &&
16107 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16108 if (BuildAndDiagnose) {
16109 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16110 S.Diag(Var->getLocation(), diag::note_previous_decl)
16111 << Var->getDeclName();
16112 Invalid = true;
16113 } else {
16114 return false;
16115 }
16116 }
16117
16118 // Make sure that by-copy captures are of a complete and non-abstract type.
16119 if (!Invalid && BuildAndDiagnose) {
16120 if (!CaptureType->isDependentType() &&
16121 S.RequireCompleteType(Loc, CaptureType,
16122 diag::err_capture_of_incomplete_type,
16123 Var->getDeclName()))
16124 Invalid = true;
16125 else if (S.RequireNonAbstractType(Loc, CaptureType,
16126 diag::err_capture_of_abstract_type))
16127 Invalid = true;
16128 }
16129 }
16130
16131 // Compute the type of a reference to this captured variable.
16132 if (ByRef)
16133 DeclRefType = CaptureType.getNonReferenceType();
16134 else {
16135 // C++ [expr.prim.lambda]p5:
16136 // The closure type for a lambda-expression has a public inline
16137 // function call operator [...]. This function call operator is
16138 // declared const (9.3.1) if and only if the lambda-expression's
16139 // parameter-declaration-clause is not followed by mutable.
16140 DeclRefType = CaptureType.getNonReferenceType();
16141 if (!LSI->Mutable && !CaptureType->isReferenceType())
16142 DeclRefType.addConst();
16143 }
16144
16145 // Add the capture.
16146 if (BuildAndDiagnose)
16147 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16148 Loc, EllipsisLoc, CaptureType, Invalid);
16149
16150 return !Invalid;
16151 }
16152
16153 bool Sema::tryCaptureVariable(
16154 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16155 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16156 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16157 // An init-capture is notionally from the context surrounding its
16158 // declaration, but its parent DC is the lambda class.
16159 DeclContext *VarDC = Var->getDeclContext();
16160 if (Var->isInitCapture())
16161 VarDC = VarDC->getParent();
16162
16163 DeclContext *DC = CurContext;
16164 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16165 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16166 // We need to sync up the Declaration Context with the
16167 // FunctionScopeIndexToStopAt
16168 if (FunctionScopeIndexToStopAt) {
16169 unsigned FSIndex = FunctionScopes.size() - 1;
16170 while (FSIndex != MaxFunctionScopesIndex) {
16171 DC = getLambdaAwareParentOfDeclContext(DC);
16172 --FSIndex;
16173 }
16174 }
16175
16176
16177 // If the variable is declared in the current context, there is no need to
16178 // capture it.
16179 if (VarDC == DC) return true;
16180
16181 // Capture global variables if it is required to use private copy of this
16182 // variable.
16183 bool IsGlobal = !Var->hasLocalStorage();
16184 if (IsGlobal &&
16185 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16186 MaxFunctionScopesIndex)))
16187 return true;
16188 Var = Var->getCanonicalDecl();
16189
16190 // Walk up the stack to determine whether we can capture the variable,
16191 // performing the "simple" checks that don't depend on type. We stop when
16192 // we've either hit the declared scope of the variable or find an existing
16193 // capture of that variable. We start from the innermost capturing-entity
16194 // (the DC) and ensure that all intervening capturing-entities
16195 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16196 // declcontext can either capture the variable or have already captured
16197 // the variable.
16198 CaptureType = Var->getType();
16199 DeclRefType = CaptureType.getNonReferenceType();
16200 bool Nested = false;
16201 bool Explicit = (Kind != TryCapture_Implicit);
16202 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16203 do {
16204 // Only block literals, captured statements, and lambda expressions can
16205 // capture; other scopes don't work.
16206 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16207 ExprLoc,
16208 BuildAndDiagnose,
16209 *this);
16210 // We need to check for the parent *first* because, if we *have*
16211 // private-captured a global variable, we need to recursively capture it in
16212 // intermediate blocks, lambdas, etc.
16213 if (!ParentDC) {
16214 if (IsGlobal) {
16215 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16216 break;
16217 }
16218 return true;
16219 }
16220
16221 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
16222 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16223
16224
16225 // Check whether we've already captured it.
16226 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16227 DeclRefType)) {
16228 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16229 break;
16230 }
16231 // If we are instantiating a generic lambda call operator body,
16232 // we do not want to capture new variables. What was captured
16233 // during either a lambdas transformation or initial parsing
16234 // should be used.
16235 if (isGenericLambdaCallOperatorSpecialization(DC)) {
16236 if (BuildAndDiagnose) {
16237 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16238 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16239 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16240 Diag(Var->getLocation(), diag::note_previous_decl)
16241 << Var->getDeclName();
16242 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16243 } else
16244 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16245 }
16246 return true;
16247 }
16248
16249 // Try to capture variable-length arrays types.
16250 if (Var->getType()->isVariablyModifiedType()) {
16251 // We're going to walk down into the type and look for VLA
16252 // expressions.
16253 QualType QTy = Var->getType();
16254 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16255 QTy = PVD->getOriginalType();
16256 captureVariablyModifiedType(Context, QTy, CSI);
16257 }
16258
16259 if (getLangOpts().OpenMP) {
16260 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16261 // OpenMP private variables should not be captured in outer scope, so
16262 // just break here. Similarly, global variables that are captured in a
16263 // target region should not be captured outside the scope of the region.
16264 if (RSI->CapRegionKind == CR_OpenMP) {
16265 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16266 // If the variable is private (i.e. not captured) and has variably
16267 // modified type, we still need to capture the type for correct
16268 // codegen in all regions, associated with the construct. Currently,
16269 // it is captured in the innermost captured region only.
16270 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16271 QualType QTy = Var->getType();
16272 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16273 QTy = PVD->getOriginalType();
16274 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16275 I < E; ++I) {
16276 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16277 FunctionScopes[FunctionScopesIndex - I]);
16278 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16279 "Wrong number of captured regions associated with the "
16280 "OpenMP construct.");
16281 captureVariablyModifiedType(Context, QTy, OuterRSI);
16282 }
16283 }
16284 bool IsTargetCap = !IsOpenMPPrivateDecl &&
16285 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16286 // When we detect target captures we are looking from inside the
16287 // target region, therefore we need to propagate the capture from the
16288 // enclosing region. Therefore, the capture is not initially nested.
16289 if (IsTargetCap)
16290 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16291
16292 if (IsTargetCap || IsOpenMPPrivateDecl) {
16293 Nested = !IsTargetCap;
16294 DeclRefType = DeclRefType.getUnqualifiedType();
16295 CaptureType = Context.getLValueReferenceType(DeclRefType);
16296 break;
16297 }
16298 }
16299 }
16300 }
16301 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16302 // No capture-default, and this is not an explicit capture
16303 // so cannot capture this variable.
16304 if (BuildAndDiagnose) {
16305 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16306 Diag(Var->getLocation(), diag::note_previous_decl)
16307 << Var->getDeclName();
16308 if (cast<LambdaScopeInfo>(CSI)->Lambda)
16309 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16310 diag::note_lambda_decl);
16311 // FIXME: If we error out because an outer lambda can not implicitly
16312 // capture a variable that an inner lambda explicitly captures, we
16313 // should have the inner lambda do the explicit capture - because
16314 // it makes for cleaner diagnostics later. This would purely be done
16315 // so that the diagnostic does not misleadingly claim that a variable
16316 // can not be captured by a lambda implicitly even though it is captured
16317 // explicitly. Suggestion:
16318 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16319 // at the function head
16320 // - cache the StartingDeclContext - this must be a lambda
16321 // - captureInLambda in the innermost lambda the variable.
16322 }
16323 return true;
16324 }
16325
16326 FunctionScopesIndex--;
16327 DC = ParentDC;
16328 Explicit = false;
16329 } while (!VarDC->Equals(DC));
16330
16331 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16332 // computing the type of the capture at each step, checking type-specific
16333 // requirements, and adding captures if requested.
16334 // If the variable had already been captured previously, we start capturing
16335 // at the lambda nested within that one.
16336 bool Invalid = false;
16337 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16338 ++I) {
16339 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16340
16341 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16342 // certain types of variables (unnamed, variably modified types etc.)
16343 // so check for eligibility.
16344 if (!Invalid)
16345 Invalid =
16346 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16347
16348 // After encountering an error, if we're actually supposed to capture, keep
16349 // capturing in nested contexts to suppress any follow-on diagnostics.
16350 if (Invalid && !BuildAndDiagnose)
16351 return true;
16352
16353 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16354 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16355 DeclRefType, Nested, *this, Invalid);
16356 Nested = true;
16357 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16358 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16359 CaptureType, DeclRefType, Nested,
16360 *this, Invalid);
16361 Nested = true;
16362 } else {
16363 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16364 Invalid =
16365 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16366 DeclRefType, Nested, Kind, EllipsisLoc,
16367 /*IsTopScope*/ I == N - 1, *this, Invalid);
16368 Nested = true;
16369 }
16370
16371 if (Invalid && !BuildAndDiagnose)
16372 return true;
16373 }
16374 return Invalid;
16375 }
16376
16377 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16378 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16379 QualType CaptureType;
16380 QualType DeclRefType;
16381 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16382 /*BuildAndDiagnose=*/true, CaptureType,
16383 DeclRefType, nullptr);
16384 }
16385
16386 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16387 QualType CaptureType;
16388 QualType DeclRefType;
16389 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16390 /*BuildAndDiagnose=*/false, CaptureType,
16391 DeclRefType, nullptr);
16392 }
16393
16394 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16395 QualType CaptureType;
16396 QualType DeclRefType;
16397
16398 // Determine whether we can capture this variable.
16399 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16400 /*BuildAndDiagnose=*/false, CaptureType,
16401 DeclRefType, nullptr))
16402 return QualType();
16403
16404 return DeclRefType;
16405 }
16406
16407 namespace {
16408 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16409 // The produced TemplateArgumentListInfo* points to data stored within this
16410 // object, so should only be used in contexts where the pointer will not be
16411 // used after the CopiedTemplateArgs object is destroyed.
16412 class CopiedTemplateArgs {
16413 bool HasArgs;
16414 TemplateArgumentListInfo TemplateArgStorage;
16415 public:
16416 template<typename RefExpr>
16417 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16418 if (HasArgs)
16419 E->copyTemplateArgumentsInto(TemplateArgStorage);
16420 }
16421 operator TemplateArgumentListInfo*()
16422 #ifdef __has_cpp_attribute
16423 #if __has_cpp_attribute(clang::lifetimebound)
16424 [[clang::lifetimebound]]
16425 #endif
16426 #endif
16427 {
16428 return HasArgs ? &TemplateArgStorage : nullptr;
16429 }
16430 };
16431 }
16432
16433 /// Walk the set of potential results of an expression and mark them all as
16434 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16435 ///
16436 /// \return A new expression if we found any potential results, ExprEmpty() if
16437 /// not, and ExprError() if we diagnosed an error.
16438 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16439 NonOdrUseReason NOUR) {
16440 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16441 // an object that satisfies the requirements for appearing in a
16442 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16443 // is immediately applied." This function handles the lvalue-to-rvalue
16444 // conversion part.
16445 //
16446 // If we encounter a node that claims to be an odr-use but shouldn't be, we
16447 // transform it into the relevant kind of non-odr-use node and rebuild the
16448 // tree of nodes leading to it.
16449 //
16450 // This is a mini-TreeTransform that only transforms a restricted subset of
16451 // nodes (and only certain operands of them).
16452
16453 // Rebuild a subexpression.
16454 auto Rebuild = [&](Expr *Sub) {
16455 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16456 };
16457
16458 // Check whether a potential result satisfies the requirements of NOUR.
16459 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16460 // Any entity other than a VarDecl is always odr-used whenever it's named
16461 // in a potentially-evaluated expression.
16462 auto *VD = dyn_cast<VarDecl>(D);
16463 if (!VD)
16464 return true;
16465
16466 // C++2a [basic.def.odr]p4:
16467 // A variable x whose name appears as a potentially-evalauted expression
16468 // e is odr-used by e unless
16469 // -- x is a reference that is usable in constant expressions, or
16470 // -- x is a variable of non-reference type that is usable in constant
16471 // expressions and has no mutable subobjects, and e is an element of
16472 // the set of potential results of an expression of
16473 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
16474 // conversion is applied, or
16475 // -- x is a variable of non-reference type, and e is an element of the
16476 // set of potential results of a discarded-value expression to which
16477 // the lvalue-to-rvalue conversion is not applied
16478 //
16479 // We check the first bullet and the "potentially-evaluated" condition in
16480 // BuildDeclRefExpr. We check the type requirements in the second bullet
16481 // in CheckLValueToRValueConversionOperand below.
16482 switch (NOUR) {
16483 case NOUR_None:
16484 case NOUR_Unevaluated:
16485 llvm_unreachable("unexpected non-odr-use-reason");
16486
16487 case NOUR_Constant:
16488 // Constant references were handled when they were built.
16489 if (VD->getType()->isReferenceType())
16490 return true;
16491 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16492 if (RD->hasMutableFields())
16493 return true;
16494 if (!VD->isUsableInConstantExpressions(S.Context))
16495 return true;
16496 break;
16497
16498 case NOUR_Discarded:
16499 if (VD->getType()->isReferenceType())
16500 return true;
16501 break;
16502 }
16503 return false;
16504 };
16505
16506 // Mark that this expression does not constitute an odr-use.
16507 auto MarkNotOdrUsed = [&] {
16508 S.MaybeODRUseExprs.erase(E);
16509 if (LambdaScopeInfo *LSI = S.getCurLambda())
16510 LSI->markVariableExprAsNonODRUsed(E);
16511 };
16512
16513 // C++2a [basic.def.odr]p2:
16514 // The set of potential results of an expression e is defined as follows:
16515 switch (E->getStmtClass()) {
16516 // -- If e is an id-expression, ...
16517 case Expr::DeclRefExprClass: {
16518 auto *DRE = cast<DeclRefExpr>(E);
16519 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16520 break;
16521
16522 // Rebuild as a non-odr-use DeclRefExpr.
16523 MarkNotOdrUsed();
16524 return DeclRefExpr::Create(
16525 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16526 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16527 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16528 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16529 }
16530
16531 case Expr::FunctionParmPackExprClass: {
16532 auto *FPPE = cast<FunctionParmPackExpr>(E);
16533 // If any of the declarations in the pack is odr-used, then the expression
16534 // as a whole constitutes an odr-use.
16535 for (VarDecl *D : *FPPE)
16536 if (IsPotentialResultOdrUsed(D))
16537 return ExprEmpty();
16538
16539 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16540 // nothing cares about whether we marked this as an odr-use, but it might
16541 // be useful for non-compiler tools.
16542 MarkNotOdrUsed();
16543 break;
16544 }
16545
16546 // -- If e is a subscripting operation with an array operand...
16547 case Expr::ArraySubscriptExprClass: {
16548 auto *ASE = cast<ArraySubscriptExpr>(E);
16549 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16550 if (!OldBase->getType()->isArrayType())
16551 break;
16552 ExprResult Base = Rebuild(OldBase);
16553 if (!Base.isUsable())
16554 return Base;
16555 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16556 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16557 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16558 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16559 ASE->getRBracketLoc());
16560 }
16561
16562 case Expr::MemberExprClass: {
16563 auto *ME = cast<MemberExpr>(E);
16564 // -- If e is a class member access expression [...] naming a non-static
16565 // data member...
16566 if (isa<FieldDecl>(ME->getMemberDecl())) {
16567 ExprResult Base = Rebuild(ME->getBase());
16568 if (!Base.isUsable())
16569 return Base;
16570 return MemberExpr::Create(
16571 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16572 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16573 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16574 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16575 ME->getObjectKind(), ME->isNonOdrUse());
16576 }
16577
16578 if (ME->getMemberDecl()->isCXXInstanceMember())
16579 break;
16580
16581 // -- If e is a class member access expression naming a static data member,
16582 // ...
16583 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16584 break;
16585
16586 // Rebuild as a non-odr-use MemberExpr.
16587 MarkNotOdrUsed();
16588 return MemberExpr::Create(
16589 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16590 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16591 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16592 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16593 return ExprEmpty();
16594 }
16595
16596 case Expr::BinaryOperatorClass: {
16597 auto *BO = cast<BinaryOperator>(E);
16598 Expr *LHS = BO->getLHS();
16599 Expr *RHS = BO->getRHS();
16600 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16601 if (BO->getOpcode() == BO_PtrMemD) {
16602 ExprResult Sub = Rebuild(LHS);
16603 if (!Sub.isUsable())
16604 return Sub;
16605 LHS = Sub.get();
16606 // -- If e is a comma expression, ...
16607 } else if (BO->getOpcode() == BO_Comma) {
16608 ExprResult Sub = Rebuild(RHS);
16609 if (!Sub.isUsable())
16610 return Sub;
16611 RHS = Sub.get();
16612 } else {
16613 break;
16614 }
16615 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16616 LHS, RHS);
16617 }
16618
16619 // -- If e has the form (e1)...
16620 case Expr::ParenExprClass: {
16621 auto *PE = cast<ParenExpr>(E);
16622 ExprResult Sub = Rebuild(PE->getSubExpr());
16623 if (!Sub.isUsable())
16624 return Sub;
16625 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16626 }
16627
16628 // -- If e is a glvalue conditional expression, ...
16629 // We don't apply this to a binary conditional operator. FIXME: Should we?
16630 case Expr::ConditionalOperatorClass: {
16631 auto *CO = cast<ConditionalOperator>(E);
16632 ExprResult LHS = Rebuild(CO->getLHS());
16633 if (LHS.isInvalid())
16634 return ExprError();
16635 ExprResult RHS = Rebuild(CO->getRHS());
16636 if (RHS.isInvalid())
16637 return ExprError();
16638 if (!LHS.isUsable() && !RHS.isUsable())
16639 return ExprEmpty();
16640 if (!LHS.isUsable())
16641 LHS = CO->getLHS();
16642 if (!RHS.isUsable())
16643 RHS = CO->getRHS();
16644 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16645 CO->getCond(), LHS.get(), RHS.get());
16646 }
16647
16648 // [Clang extension]
16649 // -- If e has the form __extension__ e1...
16650 case Expr::UnaryOperatorClass: {
16651 auto *UO = cast<UnaryOperator>(E);
16652 if (UO->getOpcode() != UO_Extension)
16653 break;
16654 ExprResult Sub = Rebuild(UO->getSubExpr());
16655 if (!Sub.isUsable())
16656 return Sub;
16657 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16658 Sub.get());
16659 }
16660
16661 // [Clang extension]
16662 // -- If e has the form _Generic(...), the set of potential results is the
16663 // union of the sets of potential results of the associated expressions.
16664 case Expr::GenericSelectionExprClass: {
16665 auto *GSE = cast<GenericSelectionExpr>(E);
16666
16667 SmallVector<Expr *, 4> AssocExprs;
16668 bool AnyChanged = false;
16669 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16670 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16671 if (AssocExpr.isInvalid())
16672 return ExprError();
16673 if (AssocExpr.isUsable()) {
16674 AssocExprs.push_back(AssocExpr.get());
16675 AnyChanged = true;
16676 } else {
16677 AssocExprs.push_back(OrigAssocExpr);
16678 }
16679 }
16680
16681 return AnyChanged ? S.CreateGenericSelectionExpr(
16682 GSE->getGenericLoc(), GSE->getDefaultLoc(),
16683 GSE->getRParenLoc(), GSE->getControllingExpr(),
16684 GSE->getAssocTypeSourceInfos(), AssocExprs)
16685 : ExprEmpty();
16686 }
16687
16688 // [Clang extension]
16689 // -- If e has the form __builtin_choose_expr(...), the set of potential
16690 // results is the union of the sets of potential results of the
16691 // second and third subexpressions.
16692 case Expr::ChooseExprClass: {
16693 auto *CE = cast<ChooseExpr>(E);
16694
16695 ExprResult LHS = Rebuild(CE->getLHS());
16696 if (LHS.isInvalid())
16697 return ExprError();
16698
16699 ExprResult RHS = Rebuild(CE->getLHS());
16700 if (RHS.isInvalid())
16701 return ExprError();
16702
16703 if (!LHS.get() && !RHS.get())
16704 return ExprEmpty();
16705 if (!LHS.isUsable())
16706 LHS = CE->getLHS();
16707 if (!RHS.isUsable())
16708 RHS = CE->getRHS();
16709
16710 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16711 RHS.get(), CE->getRParenLoc());
16712 }
16713
16714 // Step through non-syntactic nodes.
16715 case Expr::ConstantExprClass: {
16716 auto *CE = cast<ConstantExpr>(E);
16717 ExprResult Sub = Rebuild(CE->getSubExpr());
16718 if (!Sub.isUsable())
16719 return Sub;
16720 return ConstantExpr::Create(S.Context, Sub.get());
16721 }
16722
16723 // We could mostly rely on the recursive rebuilding to rebuild implicit
16724 // casts, but not at the top level, so rebuild them here.
16725 case Expr::ImplicitCastExprClass: {
16726 auto *ICE = cast<ImplicitCastExpr>(E);
16727 // Only step through the narrow set of cast kinds we expect to encounter.
16728 // Anything else suggests we've left the region in which potential results
16729 // can be found.
16730 switch (ICE->getCastKind()) {
16731 case CK_NoOp:
16732 case CK_DerivedToBase:
16733 case CK_UncheckedDerivedToBase: {
16734 ExprResult Sub = Rebuild(ICE->getSubExpr());
16735 if (!Sub.isUsable())
16736 return Sub;
16737 CXXCastPath Path(ICE->path());
16738 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16739 ICE->getValueKind(), &Path);
16740 }
16741
16742 default:
16743 break;
16744 }
16745 break;
16746 }
16747
16748 default:
16749 break;
16750 }
16751
16752 // Can't traverse through this node. Nothing to do.
16753 return ExprEmpty();
16754 }
16755
16756 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16757 // Check whether the operand is or contains an object of non-trivial C union
16758 // type.
16759 if (E->getType().isVolatileQualified() &&
16760 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16761 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16762 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16763 Sema::NTCUC_LValueToRValueVolatile,
16764 NTCUK_Destruct|NTCUK_Copy);
16765
16766 // C++2a [basic.def.odr]p4:
16767 // [...] an expression of non-volatile-qualified non-class type to which
16768 // the lvalue-to-rvalue conversion is applied [...]
16769 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16770 return E;
16771
16772 ExprResult Result =
16773 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16774 if (Result.isInvalid())
16775 return ExprError();
16776 return Result.get() ? Result : E;
16777 }
16778
16779 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16780 Res = CorrectDelayedTyposInExpr(Res);
16781
16782 if (!Res.isUsable())
16783 return Res;
16784
16785 // If a constant-expression is a reference to a variable where we delay
16786 // deciding whether it is an odr-use, just assume we will apply the
16787 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
16788 // (a non-type template argument), we have special handling anyway.
16789 return CheckLValueToRValueConversionOperand(Res.get());
16790 }
16791
16792 void Sema::CleanupVarDeclMarking() {
16793 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16794 // call.
16795 MaybeODRUseExprSet LocalMaybeODRUseExprs;
16796 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16797
16798 for (Expr *E : LocalMaybeODRUseExprs) {
16799 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16800 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16801 DRE->getLocation(), *this);
16802 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16803 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16804 *this);
16805 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16806 for (VarDecl *VD : *FP)
16807 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16808 } else {
16809 llvm_unreachable("Unexpected expression");
16810 }
16811 }
16812
16813 assert(MaybeODRUseExprs.empty() &&
16814 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16815 }
16816
16817 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16818 VarDecl *Var, Expr *E) {
16819 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16820 isa<FunctionParmPackExpr>(E)) &&
16821 "Invalid Expr argument to DoMarkVarDeclReferenced");
16822 Var->setReferenced();
16823
16824 if (Var->isInvalidDecl())
16825 return;
16826
16827 auto *MSI = Var->getMemberSpecializationInfo();
16828 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16829 : Var->getTemplateSpecializationKind();
16830
16831 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16832 bool UsableInConstantExpr =
16833 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16834
16835 // C++20 [expr.const]p12:
16836 // A variable [...] is needed for constant evaluation if it is [...] a
16837 // variable whose name appears as a potentially constant evaluated
16838 // expression that is either a contexpr variable or is of non-volatile
16839 // const-qualified integral type or of reference type
16840 bool NeededForConstantEvaluation =
16841 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16842
16843 bool NeedDefinition =
16844 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16845
16846 VarTemplateSpecializationDecl *VarSpec =
16847 dyn_cast<VarTemplateSpecializationDecl>(Var);
16848 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16849 "Can't instantiate a partial template specialization.");
16850
16851 // If this might be a member specialization of a static data member, check
16852 // the specialization is visible. We already did the checks for variable
16853 // template specializations when we created them.
16854 if (NeedDefinition && TSK != TSK_Undeclared &&
16855 !isa<VarTemplateSpecializationDecl>(Var))
16856 SemaRef.checkSpecializationVisibility(Loc, Var);
16857
16858 // Perform implicit instantiation of static data members, static data member
16859 // templates of class templates, and variable template specializations. Delay
16860 // instantiations of variable templates, except for those that could be used
16861 // in a constant expression.
16862 if (NeedDefinition && isTemplateInstantiation(TSK)) {
16863 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16864 // instantiation declaration if a variable is usable in a constant
16865 // expression (among other cases).
16866 bool TryInstantiating =
16867 TSK == TSK_ImplicitInstantiation ||
16868 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16869
16870 if (TryInstantiating) {
16871 SourceLocation PointOfInstantiation =
16872 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16873 bool FirstInstantiation = PointOfInstantiation.isInvalid();
16874 if (FirstInstantiation) {
16875 PointOfInstantiation = Loc;
16876 if (MSI)
16877 MSI->setPointOfInstantiation(PointOfInstantiation);
16878 else
16879 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16880 }
16881
16882 bool InstantiationDependent = false;
16883 bool IsNonDependent =
16884 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16885 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16886 : true;
16887
16888 // Do not instantiate specializations that are still type-dependent.
16889 if (IsNonDependent) {
16890 if (UsableInConstantExpr) {
16891 // Do not defer instantiations of variables that could be used in a
16892 // constant expression.
16893 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16894 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16895 });
16896 } else if (FirstInstantiation ||
16897 isa<VarTemplateSpecializationDecl>(Var)) {
16898 // FIXME: For a specialization of a variable template, we don't
16899 // distinguish between "declaration and type implicitly instantiated"
16900 // and "implicit instantiation of definition requested", so we have
16901 // no direct way to avoid enqueueing the pending instantiation
16902 // multiple times.
16903 SemaRef.PendingInstantiations
16904 .push_back(std::make_pair(Var, PointOfInstantiation));
16905 }
16906 }
16907 }
16908 }
16909
16910 // C++2a [basic.def.odr]p4:
16911 // A variable x whose name appears as a potentially-evaluated expression e
16912 // is odr-used by e unless
16913 // -- x is a reference that is usable in constant expressions
16914 // -- x is a variable of non-reference type that is usable in constant
16915 // expressions and has no mutable subobjects [FIXME], and e is an
16916 // element of the set of potential results of an expression of
16917 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
16918 // conversion is applied
16919 // -- x is a variable of non-reference type, and e is an element of the set
16920 // of potential results of a discarded-value expression to which the
16921 // lvalue-to-rvalue conversion is not applied [FIXME]
16922 //
16923 // We check the first part of the second bullet here, and
16924 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16925 // FIXME: To get the third bullet right, we need to delay this even for
16926 // variables that are not usable in constant expressions.
16927
16928 // If we already know this isn't an odr-use, there's nothing more to do.
16929 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16930 if (DRE->isNonOdrUse())
16931 return;
16932 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16933 if (ME->isNonOdrUse())
16934 return;
16935
16936 switch (OdrUse) {
16937 case OdrUseContext::None:
16938 assert((!E || isa<FunctionParmPackExpr>(E)) &&
16939 "missing non-odr-use marking for unevaluated decl ref");
16940 break;
16941
16942 case OdrUseContext::FormallyOdrUsed:
16943 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16944 // behavior.
16945 break;
16946
16947 case OdrUseContext::Used:
16948 // If we might later find that this expression isn't actually an odr-use,
16949 // delay the marking.
16950 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16951 SemaRef.MaybeODRUseExprs.insert(E);
16952 else
16953 MarkVarDeclODRUsed(Var, Loc, SemaRef);
16954 break;
16955
16956 case OdrUseContext::Dependent:
16957 // If this is a dependent context, we don't need to mark variables as
16958 // odr-used, but we may still need to track them for lambda capture.
16959 // FIXME: Do we also need to do this inside dependent typeid expressions
16960 // (which are modeled as unevaluated at this point)?
16961 const bool RefersToEnclosingScope =
16962 (SemaRef.CurContext != Var->getDeclContext() &&
16963 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16964 if (RefersToEnclosingScope) {
16965 LambdaScopeInfo *const LSI =
16966 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16967 if (LSI && (!LSI->CallOperator ||
16968 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16969 // If a variable could potentially be odr-used, defer marking it so
16970 // until we finish analyzing the full expression for any
16971 // lvalue-to-rvalue
16972 // or discarded value conversions that would obviate odr-use.
16973 // Add it to the list of potential captures that will be analyzed
16974 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16975 // unless the variable is a reference that was initialized by a constant
16976 // expression (this will never need to be captured or odr-used).
16977 //
16978 // FIXME: We can simplify this a lot after implementing P0588R1.
16979 assert(E && "Capture variable should be used in an expression.");
16980 if (!Var->getType()->isReferenceType() ||
16981 !Var->isUsableInConstantExpressions(SemaRef.Context))
16982 LSI->addPotentialCapture(E->IgnoreParens());
16983 }
16984 }
16985 break;
16986 }
16987 }
16988
16989 /// Mark a variable referenced, and check whether it is odr-used
16990 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
16991 /// used directly for normal expressions referring to VarDecl.
16992 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16993 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16994 }
16995
16996 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16997 Decl *D, Expr *E, bool MightBeOdrUse) {
16998 if (SemaRef.isInOpenMPDeclareTargetContext())
16999 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17000
17001 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17002 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17003 return;
17004 }
17005
17006 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17007
17008 // If this is a call to a method via a cast, also mark the method in the
17009 // derived class used in case codegen can devirtualize the call.
17010 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17011 if (!ME)
17012 return;
17013 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17014 if (!MD)
17015 return;
17016 // Only attempt to devirtualize if this is truly a virtual call.
17017 bool IsVirtualCall = MD->isVirtual() &&
17018 ME->performsVirtualDispatch(SemaRef.getLangOpts());
17019 if (!IsVirtualCall)
17020 return;
17021
17022 // If it's possible to devirtualize the call, mark the called function
17023 // referenced.
17024 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17025 ME->getBase(), SemaRef.getLangOpts().AppleKext);
17026 if (DM)
17027 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17028 }
17029
17030 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
17031 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17032 // TODO: update this with DR# once a defect report is filed.
17033 // C++11 defect. The address of a pure member should not be an ODR use, even
17034 // if it's a qualified reference.
17035 bool OdrUse = true;
17036 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17037 if (Method->isVirtual() &&
17038 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17039 OdrUse = false;
17040 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17041 }
17042
17043 /// Perform reference-marking and odr-use handling for a MemberExpr.
17044 void Sema::MarkMemberReferenced(MemberExpr *E) {
17045 // C++11 [basic.def.odr]p2:
17046 // A non-overloaded function whose name appears as a potentially-evaluated
17047 // expression or a member of a set of candidate functions, if selected by
17048 // overload resolution when referred to from a potentially-evaluated
17049 // expression, is odr-used, unless it is a pure virtual function and its
17050 // name is not explicitly qualified.
17051 bool MightBeOdrUse = true;
17052 if (E->performsVirtualDispatch(getLangOpts())) {
17053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17054 if (Method->isPure())
17055 MightBeOdrUse = false;
17056 }
17057 SourceLocation Loc =
17058 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17059 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17060 }
17061
17062 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17063 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17064 for (VarDecl *VD : *E)
17065 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17066 }
17067
17068 /// Perform marking for a reference to an arbitrary declaration. It
17069 /// marks the declaration referenced, and performs odr-use checking for
17070 /// functions and variables. This method should not be used when building a
17071 /// normal expression which refers to a variable.
17072 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17073 bool MightBeOdrUse) {
17074 if (MightBeOdrUse) {
17075 if (auto *VD = dyn_cast<VarDecl>(D)) {
17076 MarkVariableReferenced(Loc, VD);
17077 return;
17078 }
17079 }
17080 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17081 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17082 return;
17083 }
17084 D->setReferenced();
17085 }
17086
17087 namespace {
17088 // Mark all of the declarations used by a type as referenced.
17089 // FIXME: Not fully implemented yet! We need to have a better understanding
17090 // of when we're entering a context we should not recurse into.
17091 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17092 // TreeTransforms rebuilding the type in a new context. Rather than
17093 // duplicating the TreeTransform logic, we should consider reusing it here.
17094 // Currently that causes problems when rebuilding LambdaExprs.
17095 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17096 Sema &S;
17097 SourceLocation Loc;
17098
17099 public:
17100 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17101
17102 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17103
17104 bool TraverseTemplateArgument(const TemplateArgument &Arg);
17105 };
17106 }
17107
17108 bool MarkReferencedDecls::TraverseTemplateArgument(
17109 const TemplateArgument &Arg) {
17110 {
17111 // A non-type template argument is a constant-evaluated context.
17112 EnterExpressionEvaluationContext Evaluated(
17113 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17114 if (Arg.getKind() == TemplateArgument::Declaration) {
17115 if (Decl *D = Arg.getAsDecl())
17116 S.MarkAnyDeclReferenced(Loc, D, true);
17117 } else if (Arg.getKind() == TemplateArgument::Expression) {
17118 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17119 }
17120 }
17121
17122 return Inherited::TraverseTemplateArgument(Arg);
17123 }
17124
17125 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17126 MarkReferencedDecls Marker(*this, Loc);
17127 Marker.TraverseType(T);
17128 }
17129
17130 namespace {
17131 /// Helper class that marks all of the declarations referenced by
17132 /// potentially-evaluated subexpressions as "referenced".
17133 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
17134 Sema &S;
17135 bool SkipLocalVariables;
17136
17137 public:
17138 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
17139
17140 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17141 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
17142
17143 void VisitDeclRefExpr(DeclRefExpr *E) {
17144 // If we were asked not to visit local variables, don't.
17145 if (SkipLocalVariables) {
17146 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17147 if (VD->hasLocalStorage())
17148 return;
17149 }
17150
17151 S.MarkDeclRefReferenced(E);
17152 }
17153
17154 void VisitMemberExpr(MemberExpr *E) {
17155 S.MarkMemberReferenced(E);
17156 Inherited::VisitMemberExpr(E);
17157 }
17158
17159 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17160 S.MarkFunctionReferenced(
17161 E->getBeginLoc(),
17162 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17163 Visit(E->getSubExpr());
17164 }
17165
17166 void VisitCXXNewExpr(CXXNewExpr *E) {
17167 if (E->getOperatorNew())
17168 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
17169 if (E->getOperatorDelete())
17170 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17171 Inherited::VisitCXXNewExpr(E);
17172 }
17173
17174 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17175 if (E->getOperatorDelete())
17176 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17177 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
17178 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17179 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17180 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
17181 }
17182
17183 Inherited::VisitCXXDeleteExpr(E);
17184 }
17185
17186 void VisitCXXConstructExpr(CXXConstructExpr *E) {
17187 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
17188 Inherited::VisitCXXConstructExpr(E);
17189 }
17190
17191 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17192 Visit(E->getExpr());
17193 }
17194 };
17195 }
17196
17197 /// Mark any declarations that appear within this expression or any
17198 /// potentially-evaluated subexpressions as "referenced".
17199 ///
17200 /// \param SkipLocalVariables If true, don't mark local variables as
17201 /// 'referenced'.
17202 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17203 bool SkipLocalVariables) {
17204 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17205 }
17206
17207 /// Emit a diagnostic that describes an effect on the run-time behavior
17208 /// of the program being compiled.
17209 ///
17210 /// This routine emits the given diagnostic when the code currently being
17211 /// type-checked is "potentially evaluated", meaning that there is a
17212 /// possibility that the code will actually be executable. Code in sizeof()
17213 /// expressions, code used only during overload resolution, etc., are not
17214 /// potentially evaluated. This routine will suppress such diagnostics or,
17215 /// in the absolutely nutty case of potentially potentially evaluated
17216 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17217 /// later.
17218 ///
17219 /// This routine should be used for all diagnostics that describe the run-time
17220 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17221 /// Failure to do so will likely result in spurious diagnostics or failures
17222 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17223 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17224 const PartialDiagnostic &PD) {
17225 switch (ExprEvalContexts.back().Context) {
17226 case ExpressionEvaluationContext::Unevaluated:
17227 case ExpressionEvaluationContext::UnevaluatedList:
17228 case ExpressionEvaluationContext::UnevaluatedAbstract:
17229 case ExpressionEvaluationContext::DiscardedStatement:
17230 // The argument will never be evaluated, so don't complain.
17231 break;
17232
17233 case ExpressionEvaluationContext::ConstantEvaluated:
17234 // Relevant diagnostics should be produced by constant evaluation.
17235 break;
17236
17237 case ExpressionEvaluationContext::PotentiallyEvaluated:
17238 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17239 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17240 FunctionScopes.back()->PossiblyUnreachableDiags.
17241 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17242 return true;
17243 }
17244
17245 // The initializer of a constexpr variable or of the first declaration of a
17246 // static data member is not syntactically a constant evaluated constant,
17247 // but nonetheless is always required to be a constant expression, so we
17248 // can skip diagnosing.
17249 // FIXME: Using the mangling context here is a hack.
17250 if (auto *VD = dyn_cast_or_null<VarDecl>(
17251 ExprEvalContexts.back().ManglingContextDecl)) {
17252 if (VD->isConstexpr() ||
17253 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17254 break;
17255 // FIXME: For any other kind of variable, we should build a CFG for its
17256 // initializer and check whether the context in question is reachable.
17257 }
17258
17259 Diag(Loc, PD);
17260 return true;
17261 }
17262
17263 return false;
17264 }
17265
17266 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17267 const PartialDiagnostic &PD) {
17268 return DiagRuntimeBehavior(
17269 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17270 }
17271
17272 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17273 CallExpr *CE, FunctionDecl *FD) {
17274 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17275 return false;
17276
17277 // If we're inside a decltype's expression, don't check for a valid return
17278 // type or construct temporaries until we know whether this is the last call.
17279 if (ExprEvalContexts.back().ExprContext ==
17280 ExpressionEvaluationContextRecord::EK_Decltype) {
17281 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17282 return false;
17283 }
17284
17285 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17286 FunctionDecl *FD;
17287 CallExpr *CE;
17288
17289 public:
17290 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17291 : FD(FD), CE(CE) { }
17292
17293 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17294 if (!FD) {
17295 S.Diag(Loc, diag::err_call_incomplete_return)
17296 << T << CE->getSourceRange();
17297 return;
17298 }
17299
17300 S.Diag(Loc, diag::err_call_function_incomplete_return)
17301 << CE->getSourceRange() << FD->getDeclName() << T;
17302 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17303 << FD->getDeclName();
17304 }
17305 } Diagnoser(FD, CE);
17306
17307 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17308 return true;
17309
17310 return false;
17311 }
17312
17313 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17314 // will prevent this condition from triggering, which is what we want.
17315 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17316 SourceLocation Loc;
17317
17318 unsigned diagnostic = diag::warn_condition_is_assignment;
17319 bool IsOrAssign = false;
17320
17321 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17322 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17323 return;
17324
17325 IsOrAssign = Op->getOpcode() == BO_OrAssign;
17326
17327 // Greylist some idioms by putting them into a warning subcategory.
17328 if (ObjCMessageExpr *ME
17329 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17330 Selector Sel = ME->getSelector();
17331
17332 // self = [<foo> init...]
17333 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17334 diagnostic = diag::warn_condition_is_idiomatic_assignment;
17335
17336 // <foo> = [<bar> nextObject]
17337 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17338 diagnostic = diag::warn_condition_is_idiomatic_assignment;
17339 }
17340
17341 Loc = Op->getOperatorLoc();
17342 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17343 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17344 return;
17345
17346 IsOrAssign = Op->getOperator() == OO_PipeEqual;
17347 Loc = Op->getOperatorLoc();
17348 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17349 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17350 else {
17351 // Not an assignment.
17352 return;
17353 }
17354
17355 Diag(Loc, diagnostic) << E->getSourceRange();
17356
17357 SourceLocation Open = E->getBeginLoc();
17358 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17359 Diag(Loc, diag::note_condition_assign_silence)
17360 << FixItHint::CreateInsertion(Open, "(")
17361 << FixItHint::CreateInsertion(Close, ")");
17362
17363 if (IsOrAssign)
17364 Diag(Loc, diag::note_condition_or_assign_to_comparison)
17365 << FixItHint::CreateReplacement(Loc, "!=");
17366 else
17367 Diag(Loc, diag::note_condition_assign_to_comparison)
17368 << FixItHint::CreateReplacement(Loc, "==");
17369 }
17370
17371 /// Redundant parentheses over an equality comparison can indicate
17372 /// that the user intended an assignment used as condition.
17373 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17374 // Don't warn if the parens came from a macro.
17375 SourceLocation parenLoc = ParenE->getBeginLoc();
17376 if (parenLoc.isInvalid() || parenLoc.isMacroID())
17377 return;
17378 // Don't warn for dependent expressions.
17379 if (ParenE->isTypeDependent())
17380 return;
17381
17382 Expr *E = ParenE->IgnoreParens();
17383
17384 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17385 if (opE->getOpcode() == BO_EQ &&
17386 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17387 == Expr::MLV_Valid) {
17388 SourceLocation Loc = opE->getOperatorLoc();
17389
17390 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17391 SourceRange ParenERange = ParenE->getSourceRange();
17392 Diag(Loc, diag::note_equality_comparison_silence)
17393 << FixItHint::CreateRemoval(ParenERange.getBegin())
17394 << FixItHint::CreateRemoval(ParenERange.getEnd());
17395 Diag(Loc, diag::note_equality_comparison_to_assign)
17396 << FixItHint::CreateReplacement(Loc, "=");
17397 }
17398 }
17399
17400 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17401 bool IsConstexpr) {
17402 DiagnoseAssignmentAsCondition(E);
17403 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17404 DiagnoseEqualityWithExtraParens(parenE);
17405
17406 ExprResult result = CheckPlaceholderExpr(E);
17407 if (result.isInvalid()) return ExprError();
17408 E = result.get();
17409
17410 if (!E->isTypeDependent()) {
17411 if (getLangOpts().CPlusPlus)
17412 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17413
17414 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17415 if (ERes.isInvalid())
17416 return ExprError();
17417 E = ERes.get();
17418
17419 QualType T = E->getType();
17420 if (!T->isScalarType()) { // C99 6.8.4.1p1
17421 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17422 << T << E->getSourceRange();
17423 return ExprError();
17424 }
17425 CheckBoolLikeConversion(E, Loc);
17426 }
17427
17428 return E;
17429 }
17430
17431 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17432 Expr *SubExpr, ConditionKind CK) {
17433 // Empty conditions are valid in for-statements.
17434 if (!SubExpr)
17435 return ConditionResult();
17436
17437 ExprResult Cond;
17438 switch (CK) {
17439 case ConditionKind::Boolean:
17440 Cond = CheckBooleanCondition(Loc, SubExpr);
17441 break;
17442
17443 case ConditionKind::ConstexprIf:
17444 Cond = CheckBooleanCondition(Loc, SubExpr, true);
17445 break;
17446
17447 case ConditionKind::Switch:
17448 Cond = CheckSwitchCondition(Loc, SubExpr);
17449 break;
17450 }
17451 if (Cond.isInvalid())
17452 return ConditionError();
17453
17454 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17455 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17456 if (!FullExpr.get())
17457 return ConditionError();
17458
17459 return ConditionResult(*this, nullptr, FullExpr,
17460 CK == ConditionKind::ConstexprIf);
17461 }
17462
17463 namespace {
17464 /// A visitor for rebuilding a call to an __unknown_any expression
17465 /// to have an appropriate type.
17466 struct RebuildUnknownAnyFunction
17467 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17468
17469 Sema &S;
17470
17471 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17472
17473 ExprResult VisitStmt(Stmt *S) {
17474 llvm_unreachable("unexpected statement!");
17475 }
17476
17477 ExprResult VisitExpr(Expr *E) {
17478 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17479 << E->getSourceRange();
17480 return ExprError();
17481 }
17482
17483 /// Rebuild an expression which simply semantically wraps another
17484 /// expression which it shares the type and value kind of.
17485 template <class T> ExprResult rebuildSugarExpr(T *E) {
17486 ExprResult SubResult = Visit(E->getSubExpr());
17487 if (SubResult.isInvalid()) return ExprError();
17488
17489 Expr *SubExpr = SubResult.get();
17490 E->setSubExpr(SubExpr);
17491 E->setType(SubExpr->getType());
17492 E->setValueKind(SubExpr->getValueKind());
17493 assert(E->getObjectKind() == OK_Ordinary);
17494 return E;
17495 }
17496
17497 ExprResult VisitParenExpr(ParenExpr *E) {
17498 return rebuildSugarExpr(E);
17499 }
17500
17501 ExprResult VisitUnaryExtension(UnaryOperator *E) {
17502 return rebuildSugarExpr(E);
17503 }
17504
17505 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17506 ExprResult SubResult = Visit(E->getSubExpr());
17507 if (SubResult.isInvalid()) return ExprError();
17508
17509 Expr *SubExpr = SubResult.get();
17510 E->setSubExpr(SubExpr);
17511 E->setType(S.Context.getPointerType(SubExpr->getType()));
17512 assert(E->getValueKind() == VK_RValue);
17513 assert(E->getObjectKind() == OK_Ordinary);
17514 return E;
17515 }
17516
17517 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17518 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17519
17520 E->setType(VD->getType());
17521
17522 assert(E->getValueKind() == VK_RValue);
17523 if (S.getLangOpts().CPlusPlus &&
17524 !(isa<CXXMethodDecl>(VD) &&
17525 cast<CXXMethodDecl>(VD)->isInstance()))
17526 E->setValueKind(VK_LValue);
17527
17528 return E;
17529 }
17530
17531 ExprResult VisitMemberExpr(MemberExpr *E) {
17532 return resolveDecl(E, E->getMemberDecl());
17533 }
17534
17535 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17536 return resolveDecl(E, E->getDecl());
17537 }
17538 };
17539 }
17540
17541 /// Given a function expression of unknown-any type, try to rebuild it
17542 /// to have a function type.
17543 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17544 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17545 if (Result.isInvalid()) return ExprError();
17546 return S.DefaultFunctionArrayConversion(Result.get());
17547 }
17548
17549 namespace {
17550 /// A visitor for rebuilding an expression of type __unknown_anytype
17551 /// into one which resolves the type directly on the referring
17552 /// expression. Strict preservation of the original source
17553 /// structure is not a goal.
17554 struct RebuildUnknownAnyExpr
17555 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17556
17557 Sema &S;
17558
17559 /// The current destination type.
17560 QualType DestType;
17561
17562 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17563 : S(S), DestType(CastType) {}
17564
17565 ExprResult VisitStmt(Stmt *S) {
17566 llvm_unreachable("unexpected statement!");
17567 }
17568
17569 ExprResult VisitExpr(Expr *E) {
17570 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17571 << E->getSourceRange();
17572 return ExprError();
17573 }
17574
17575 ExprResult VisitCallExpr(CallExpr *E);
17576 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17577
17578 /// Rebuild an expression which simply semantically wraps another
17579 /// expression which it shares the type and value kind of.
17580 template <class T> ExprResult rebuildSugarExpr(T *E) {
17581 ExprResult SubResult = Visit(E->getSubExpr());
17582 if (SubResult.isInvalid()) return ExprError();
17583 Expr *SubExpr = SubResult.get();
17584 E->setSubExpr(SubExpr);
17585 E->setType(SubExpr->getType());
17586 E->setValueKind(SubExpr->getValueKind());
17587 assert(E->getObjectKind() == OK_Ordinary);
17588 return E;
17589 }
17590
17591 ExprResult VisitParenExpr(ParenExpr *E) {
17592 return rebuildSugarExpr(E);
17593 }
17594
17595 ExprResult VisitUnaryExtension(UnaryOperator *E) {
17596 return rebuildSugarExpr(E);
17597 }
17598
17599 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17600 const PointerType *Ptr = DestType->getAs<PointerType>();
17601 if (!Ptr) {
17602 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17603 << E->getSourceRange();
17604 return ExprError();
17605 }
17606
17607 if (isa<CallExpr>(E->getSubExpr())) {
17608 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17609 << E->getSourceRange();
17610 return ExprError();
17611 }
17612
17613 assert(E->getValueKind() == VK_RValue);
17614 assert(E->getObjectKind() == OK_Ordinary);
17615 E->setType(DestType);
17616
17617 // Build the sub-expression as if it were an object of the pointee type.
17618 DestType = Ptr->getPointeeType();
17619 ExprResult SubResult = Visit(E->getSubExpr());
17620 if (SubResult.isInvalid()) return ExprError();
17621 E->setSubExpr(SubResult.get());
17622 return E;
17623 }
17624
17625 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17626
17627 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17628
17629 ExprResult VisitMemberExpr(MemberExpr *E) {
17630 return resolveDecl(E, E->getMemberDecl());
17631 }
17632
17633 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17634 return resolveDecl(E, E->getDecl());
17635 }
17636 };
17637 }
17638
17639 /// Rebuilds a call expression which yielded __unknown_anytype.
17640 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17641 Expr *CalleeExpr = E->getCallee();
17642
17643 enum FnKind {
17644 FK_MemberFunction,
17645 FK_FunctionPointer,
17646 FK_BlockPointer
17647 };
17648
17649 FnKind Kind;
17650 QualType CalleeType = CalleeExpr->getType();
17651 if (CalleeType == S.Context.BoundMemberTy) {
17652 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17653 Kind = FK_MemberFunction;
17654 CalleeType = Expr::findBoundMemberType(CalleeExpr);
17655 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17656 CalleeType = Ptr->getPointeeType();
17657 Kind = FK_FunctionPointer;
17658 } else {
17659 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17660 Kind = FK_BlockPointer;
17661 }
17662 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17663
17664 // Verify that this is a legal result type of a function.
17665 if (DestType->isArrayType() || DestType->isFunctionType()) {
17666 unsigned diagID = diag::err_func_returning_array_function;
17667 if (Kind == FK_BlockPointer)
17668 diagID = diag::err_block_returning_array_function;
17669
17670 S.Diag(E->getExprLoc(), diagID)
17671 << DestType->isFunctionType() << DestType;
17672 return ExprError();
17673 }
17674
17675 // Otherwise, go ahead and set DestType as the call's result.
17676 E->setType(DestType.getNonLValueExprType(S.Context));
17677 E->setValueKind(Expr::getValueKindForType(DestType));
17678 assert(E->getObjectKind() == OK_Ordinary);
17679
17680 // Rebuild the function type, replacing the result type with DestType.
17681 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17682 if (Proto) {
17683 // __unknown_anytype(...) is a special case used by the debugger when
17684 // it has no idea what a function's signature is.
17685 //
17686 // We want to build this call essentially under the K&R
17687 // unprototyped rules, but making a FunctionNoProtoType in C++
17688 // would foul up all sorts of assumptions. However, we cannot
17689 // simply pass all arguments as variadic arguments, nor can we
17690 // portably just call the function under a non-variadic type; see
17691 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17692 // However, it turns out that in practice it is generally safe to
17693 // call a function declared as "A foo(B,C,D);" under the prototype
17694 // "A foo(B,C,D,...);". The only known exception is with the
17695 // Windows ABI, where any variadic function is implicitly cdecl
17696 // regardless of its normal CC. Therefore we change the parameter
17697 // types to match the types of the arguments.
17698 //
17699 // This is a hack, but it is far superior to moving the
17700 // corresponding target-specific code from IR-gen to Sema/AST.
17701
17702 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17703 SmallVector<QualType, 8> ArgTypes;
17704 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17705 ArgTypes.reserve(E->getNumArgs());
17706 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17707 Expr *Arg = E->getArg(i);
17708 QualType ArgType = Arg->getType();
17709 if (E->isLValue()) {
17710 ArgType = S.Context.getLValueReferenceType(ArgType);
17711 } else if (E->isXValue()) {
17712 ArgType = S.Context.getRValueReferenceType(ArgType);
17713 }
17714 ArgTypes.push_back(ArgType);
17715 }
17716 ParamTypes = ArgTypes;
17717 }
17718 DestType = S.Context.getFunctionType(DestType, ParamTypes,
17719 Proto->getExtProtoInfo());
17720 } else {
17721 DestType = S.Context.getFunctionNoProtoType(DestType,
17722 FnType->getExtInfo());
17723 }
17724
17725 // Rebuild the appropriate pointer-to-function type.
17726 switch (Kind) {
17727 case FK_MemberFunction:
17728 // Nothing to do.
17729 break;
17730
17731 case FK_FunctionPointer:
17732 DestType = S.Context.getPointerType(DestType);
17733 break;
17734
17735 case FK_BlockPointer:
17736 DestType = S.Context.getBlockPointerType(DestType);
17737 break;
17738 }
17739
17740 // Finally, we can recurse.
17741 ExprResult CalleeResult = Visit(CalleeExpr);
17742 if (!CalleeResult.isUsable()) return ExprError();
17743 E->setCallee(CalleeResult.get());
17744
17745 // Bind a temporary if necessary.
17746 return S.MaybeBindToTemporary(E);
17747 }
17748
17749 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17750 // Verify that this is a legal result type of a call.
17751 if (DestType->isArrayType() || DestType->isFunctionType()) {
17752 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17753 << DestType->isFunctionType() << DestType;
17754 return ExprError();
17755 }
17756
17757 // Rewrite the method result type if available.
17758 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17759 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17760 Method->setReturnType(DestType);
17761 }
17762
17763 // Change the type of the message.
17764 E->setType(DestType.getNonReferenceType());
17765 E->setValueKind(Expr::getValueKindForType(DestType));
17766
17767 return S.MaybeBindToTemporary(E);
17768 }
17769
17770 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17771 // The only case we should ever see here is a function-to-pointer decay.
17772 if (E->getCastKind() == CK_FunctionToPointerDecay) {
17773 assert(E->getValueKind() == VK_RValue);
17774 assert(E->getObjectKind() == OK_Ordinary);
17775
17776 E->setType(DestType);
17777
17778 // Rebuild the sub-expression as the pointee (function) type.
17779 DestType = DestType->castAs<PointerType>()->getPointeeType();
17780
17781 ExprResult Result = Visit(E->getSubExpr());
17782 if (!Result.isUsable()) return ExprError();
17783
17784 E->setSubExpr(Result.get());
17785 return E;
17786 } else if (E->getCastKind() == CK_LValueToRValue) {
17787 assert(E->getValueKind() == VK_RValue);
17788 assert(E->getObjectKind() == OK_Ordinary);
17789
17790 assert(isa<BlockPointerType>(E->getType()));
17791
17792 E->setType(DestType);
17793
17794 // The sub-expression has to be a lvalue reference, so rebuild it as such.
17795 DestType = S.Context.getLValueReferenceType(DestType);
17796
17797 ExprResult Result = Visit(E->getSubExpr());
17798 if (!Result.isUsable()) return ExprError();
17799
17800 E->setSubExpr(Result.get());
17801 return E;
17802 } else {
17803 llvm_unreachable("Unhandled cast type!");
17804 }
17805 }
17806
17807 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17808 ExprValueKind ValueKind = VK_LValue;
17809 QualType Type = DestType;
17810
17811 // We know how to make this work for certain kinds of decls:
17812
17813 // - functions
17814 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17815 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17816 DestType = Ptr->getPointeeType();
17817 ExprResult Result = resolveDecl(E, VD);
17818 if (Result.isInvalid()) return ExprError();
17819 return S.ImpCastExprToType(Result.get(), Type,
17820 CK_FunctionToPointerDecay, VK_RValue);
17821 }
17822
17823 if (!Type->isFunctionType()) {
17824 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17825 << VD << E->getSourceRange();
17826 return ExprError();
17827 }
17828 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17829 // We must match the FunctionDecl's type to the hack introduced in
17830 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17831 // type. See the lengthy commentary in that routine.
17832 QualType FDT = FD->getType();
17833 const FunctionType *FnType = FDT->castAs<FunctionType>();
17834 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17835 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17836 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17837 SourceLocation Loc = FD->getLocation();
17838 FunctionDecl *NewFD = FunctionDecl::Create(
17839 S.Context, FD->getDeclContext(), Loc, Loc,
17840 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17841 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17842 /*ConstexprKind*/ CSK_unspecified);
17843
17844 if (FD->getQualifier())
17845 NewFD->setQualifierInfo(FD->getQualifierLoc());
17846
17847 SmallVector<ParmVarDecl*, 16> Params;
17848 for (const auto &AI : FT->param_types()) {
17849 ParmVarDecl *Param =
17850 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17851 Param->setScopeInfo(0, Params.size());
17852 Params.push_back(Param);
17853 }
17854 NewFD->setParams(Params);
17855 DRE->setDecl(NewFD);
17856 VD = DRE->getDecl();
17857 }
17858 }
17859
17860 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17861 if (MD->isInstance()) {
17862 ValueKind = VK_RValue;
17863 Type = S.Context.BoundMemberTy;
17864 }
17865
17866 // Function references aren't l-values in C.
17867 if (!S.getLangOpts().CPlusPlus)
17868 ValueKind = VK_RValue;
17869
17870 // - variables
17871 } else if (isa<VarDecl>(VD)) {
17872 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17873 Type = RefTy->getPointeeType();
17874 } else if (Type->isFunctionType()) {
17875 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17876 << VD << E->getSourceRange();
17877 return ExprError();
17878 }
17879
17880 // - nothing else
17881 } else {
17882 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17883 << VD << E->getSourceRange();
17884 return ExprError();
17885 }
17886
17887 // Modifying the declaration like this is friendly to IR-gen but
17888 // also really dangerous.
17889 VD->setType(DestType);
17890 E->setType(Type);
17891 E->setValueKind(ValueKind);
17892 return E;
17893 }
17894
17895 /// Check a cast of an unknown-any type. We intentionally only
17896 /// trigger this for C-style casts.
17897 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17898 Expr *CastExpr, CastKind &CastKind,
17899 ExprValueKind &VK, CXXCastPath &Path) {
17900 // The type we're casting to must be either void or complete.
17901 if (!CastType->isVoidType() &&
17902 RequireCompleteType(TypeRange.getBegin(), CastType,
17903 diag::err_typecheck_cast_to_incomplete))
17904 return ExprError();
17905
17906 // Rewrite the casted expression from scratch.
17907 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17908 if (!result.isUsable()) return ExprError();
17909
17910 CastExpr = result.get();
17911 VK = CastExpr->getValueKind();
17912 CastKind = CK_NoOp;
17913
17914 return CastExpr;
17915 }
17916
17917 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17918 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17919 }
17920
17921 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17922 Expr *arg, QualType &paramType) {
17923 // If the syntactic form of the argument is not an explicit cast of
17924 // any sort, just do default argument promotion.
17925 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17926 if (!castArg) {
17927 ExprResult result = DefaultArgumentPromotion(arg);
17928 if (result.isInvalid()) return ExprError();
17929 paramType = result.get()->getType();
17930 return result;
17931 }
17932
17933 // Otherwise, use the type that was written in the explicit cast.
17934 assert(!arg->hasPlaceholderType());
17935 paramType = castArg->getTypeAsWritten();
17936
17937 // Copy-initialize a parameter of that type.
17938 InitializedEntity entity =
17939 InitializedEntity::InitializeParameter(Context, paramType,
17940 /*consumed*/ false);
17941 return PerformCopyInitialization(entity, callLoc, arg);
17942 }
17943
17944 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17945 Expr *orig = E;
17946 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17947 while (true) {
17948 E = E->IgnoreParenImpCasts();
17949 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17950 E = call->getCallee();
17951 diagID = diag::err_uncasted_call_of_unknown_any;
17952 } else {
17953 break;
17954 }
17955 }
17956
17957 SourceLocation loc;
17958 NamedDecl *d;
17959 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17960 loc = ref->getLocation();
17961 d = ref->getDecl();
17962 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17963 loc = mem->getMemberLoc();
17964 d = mem->getMemberDecl();
17965 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17966 diagID = diag::err_uncasted_call_of_unknown_any;
17967 loc = msg->getSelectorStartLoc();
17968 d = msg->getMethodDecl();
17969 if (!d) {
17970 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17971 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17972 << orig->getSourceRange();
17973 return ExprError();
17974 }
17975 } else {
17976 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17977 << E->getSourceRange();
17978 return ExprError();
17979 }
17980
17981 S.Diag(loc, diagID) << d << orig->getSourceRange();
17982
17983 // Never recoverable.
17984 return ExprError();
17985 }
17986
17987 /// Check for operands with placeholder types and complain if found.
17988 /// Returns ExprError() if there was an error and no recovery was possible.
17989 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17990 if (!getLangOpts().CPlusPlus) {
17991 // C cannot handle TypoExpr nodes on either side of a binop because it
17992 // doesn't handle dependent types properly, so make sure any TypoExprs have
17993 // been dealt with before checking the operands.
17994 ExprResult Result = CorrectDelayedTyposInExpr(E);
17995 if (!Result.isUsable()) return ExprError();
17996 E = Result.get();
17997 }
17998
17999 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18000 if (!placeholderType) return E;
18001
18002 switch (placeholderType->getKind()) {
18003
18004 // Overloaded expressions.
18005 case BuiltinType::Overload: {
18006 // Try to resolve a single function template specialization.
18007 // This is obligatory.
18008 ExprResult Result = E;
18009 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18010 return Result;
18011
18012 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18013 // leaves Result unchanged on failure.
18014 Result = E;
18015 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18016 return Result;
18017
18018 // If that failed, try to recover with a call.
18019 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18020 /*complain*/ true);
18021 return Result;
18022 }
18023
18024 // Bound member functions.
18025 case BuiltinType::BoundMember: {
18026 ExprResult result = E;
18027 const Expr *BME = E->IgnoreParens();
18028 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18029 // Try to give a nicer diagnostic if it is a bound member that we recognize.
18030 if (isa<CXXPseudoDestructorExpr>(BME)) {
18031 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18032 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18033 if (ME->getMemberNameInfo().getName().getNameKind() ==
18034 DeclarationName::CXXDestructorName)
18035 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18036 }
18037 tryToRecoverWithCall(result, PD,
18038 /*complain*/ true);
18039 return result;
18040 }
18041
18042 // ARC unbridged casts.
18043 case BuiltinType::ARCUnbridgedCast: {
18044 Expr *realCast = stripARCUnbridgedCast(E);
18045 diagnoseARCUnbridgedCast(realCast);
18046 return realCast;
18047 }
18048
18049 // Expressions of unknown type.
18050 case BuiltinType::UnknownAny:
18051 return diagnoseUnknownAnyExpr(*this, E);
18052
18053 // Pseudo-objects.
18054 case BuiltinType::PseudoObject:
18055 return checkPseudoObjectRValue(E);
18056
18057 case BuiltinType::BuiltinFn: {
18058 // Accept __noop without parens by implicitly converting it to a call expr.
18059 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18060 if (DRE) {
18061 auto *FD = cast<FunctionDecl>(DRE->getDecl());
18062 if (FD->getBuiltinID() == Builtin::BI__noop) {
18063 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18064 CK_BuiltinFnToFnPtr)
18065 .get();
18066 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18067 VK_RValue, SourceLocation());
18068 }
18069 }
18070
18071 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18072 return ExprError();
18073 }
18074
18075 // Expressions of unknown type.
18076 case BuiltinType::OMPArraySection:
18077 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18078 return ExprError();
18079
18080 // Everything else should be impossible.
18081 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18082 case BuiltinType::Id:
18083 #include "clang/Basic/OpenCLImageTypes.def"
18084 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18085 case BuiltinType::Id:
18086 #include "clang/Basic/OpenCLExtensionTypes.def"
18087 #define SVE_TYPE(Name, Id, SingletonId) \
18088 case BuiltinType::Id:
18089 #include "clang/Basic/AArch64SVEACLETypes.def"
18090 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18091 #define PLACEHOLDER_TYPE(Id, SingletonId)
18092 #include "clang/AST/BuiltinTypes.def"
18093 break;
18094 }
18095
18096 llvm_unreachable("invalid placeholder type!");
18097 }
18098
18099 bool Sema::CheckCaseExpression(Expr *E) {
18100 if (E->isTypeDependent())
18101 return true;
18102 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18103 return E->getType()->isIntegralOrEnumerationType();
18104 return false;
18105 }
18106
18107 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18108 ExprResult
18109 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18110 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
18111 "Unknown Objective-C Boolean value!");
18112 QualType BoolT = Context.ObjCBuiltinBoolTy;
18113 if (!Context.getBOOLDecl()) {
18114 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18115 Sema::LookupOrdinaryName);
18116 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18117 NamedDecl *ND = Result.getFoundDecl();
18118 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18119 Context.setBOOLDecl(TD);
18120 }
18121 }
18122 if (Context.getBOOLDecl())
18123 BoolT = Context.getBOOLType();
18124 return new (Context)
18125 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18126 }
18127
18128 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18129 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18130 SourceLocation RParen) {
18131
18132 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18133
18134 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18135 return Spec.getPlatform() == Platform;
18136 });
18137
18138 VersionTuple Version;
18139 if (Spec != AvailSpecs.end())
18140 Version = Spec->getVersion();
18141
18142 // The use of `@available` in the enclosing function should be analyzed to
18143 // warn when it's used inappropriately (i.e. not if(@available)).
18144 if (getCurFunctionOrMethodDecl())
18145 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18146 else if (getCurBlock() || getCurLambda())
18147 getCurFunction()->HasPotentialAvailabilityViolations = true;
18148
18149 return new (Context)
18150 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18151 }
18152
18153 bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18154 assert(E->isTypeDependent());
18155 return isa<UnresolvedLookupExpr>(E);
18156 }
clang::Sema::TypeDiagnoser
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1665
diagnoseArithmeticOnFunctionPointer
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:9502
clang::CorrectionCandidateCallback::setTypoName
void setTypoName(IdentifierInfo *II)
Definition: TypoCorrection.h:322
clang::OMF_finalize
Definition: IdentifierTable.h:641
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
clang::Expr::LV_IncompleteVoidType
Definition: Expr.h:266
clang::AR_Unavailable
Definition: DeclBase.h:78
clang::Sema::LookupMethodInQualifiedType
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
Definition: SemaExprObjC.cpp:1834
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:719
ParsedTemplate.h
clang::ObjCObjectPointerType::getInterfaceType
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1607
clang::Builtin::ID
ID
Definition: Builtins.h:46
clang::ast_matchers::type
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchersInternal.cpp:638
DiagnoseBitwisePrecedence
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:13205
ASTContext.h
Defines the clang::ASTContext interface.
clang::ASTContext::getAddrSpaceQualType
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
Definition: ASTContext.cpp:2868
clang::BlockExpr::getBlockDecl
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5593
clang::ObjCInterfaceDecl::hasDefinition
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1549
clang::QualType::isNonWeakInMRRWithObjCWeak
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2326
clang::Sema::MarkDeclarationsReferencedInExpr
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:17202
clang::Sema::VariadicCallType
VariadicCallType
Definition: Sema.h:10527
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1628
clang::CharacterLiteral::Ascii
Definition: Expr.h:1533
clang::Sema::getCurrentThisType
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
Definition: SemaExprCXX.cpp:1082
clang::CanQual::withConst
QualType withConst() const
Retrieves a version of this type with const applied.
Definition: CanonicalType.h:161
clang::Sema::ActOnCondition
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:17431
clang::CXXTemporary::getDestructor
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1352
clang::ObjCMethodDecl::isClassMethod
bool isClassMethod() const
Definition: DeclObjC.h:431
clang::CC_X86VectorCall
Definition: Specifiers.h:270
isOverflowingIntegerType
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:13568
clang::ASTContext::LongLongTy
CanQualType LongLongTy
Definition: ASTContext.h:1025
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5550
clang::VarDecl::mightBeUsableInConstantExpressions
bool mightBeUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2292
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1783
isVariableAlreadyCapturedInScopeInfo
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:15830
CheckConstraintSatisfaction
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< const Expr *> ConstraintExprs, ArrayRef< TemplateArgument > TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Definition: SemaConcept.cpp:233
clang::Type::hasAttr
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1707
clang::Type::isFixedPointType
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6824
clang::CallExpr::getArgs
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2692
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:77
clang::interp::Cast
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:800
clang::Sema::ActOnCastExpr
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6774
clang::TypoCorrection::getCorrectionRange
SourceRange getCorrectionRange() const
Definition: TypoCorrection.h:226
clang::Builtin::Context::isPredefinedLibFunction
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc", where we know the signature a priori.
Definition: Builtins.h:138
clang::Sema::IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:10640
clang::ObjCObjectPointerType::isObjCQualifiedIdType
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:6030
clang::TargetInfo::hasBuiltinMSVaList
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:790
clang::LangOptions::isSignedOverflowDefined
bool isSignedOverflowDefined() const
Definition: LangOptions.h:322
clang::ASTContext::AccumTy
CanQualType AccumTy
Definition: ASTContext.h:1029
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:132
clang::UnqualifiedId::setKind
void setKind(UnqualifiedIdKind kind)
Definition: DeclSpec.h:1043
clang::Sema::ACK_Comparison
A comparison.
Definition: Sema.h:10581
clang::DynamicInitKind::Initializer
clang::Selector
Smart pointer class that efficiently represents Objective-C method names.
Definition: IdentifierTable.h:685
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1874
clang::Sema::CheckLValueToRValueConversionOperand
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:16756
clang::BlockDecl::Capture
A class which contains all the information about a particular captured value.
Definition: Decl.h:4043
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::Sema::PushExpressionEvaluationContext
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:15198
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
Definition: RecursiveASTVisitor.h:1045
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
clang::Type::STK_FixedPoint
Definition: Type.h:2142
OEK_Member
Definition: SemaExpr.cpp:11754
clang::EvaluatedExprVisitor
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
Definition: EvaluatedExprVisitor.h:111
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2627
clang::Sema::CheckLoopHintExpr
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3485
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:654
clang::ASTContext::getIntegerTypeOrder
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
Definition: ASTContext.cpp:6085
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6512
checkConditionalPointerCompatibility
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7045
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
clang::ArraySubscriptExpr::getBase
Expr * getBase()
Definition: Expr.h:2505
clang::Sema::CheckAssignmentOperands
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType)
Definition: SemaExpr.cpp:11995
clang::ASTContext::areCommonBaseCompatible
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
Definition: ASTContext.cpp:8546
clang::QualType::isPODType
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2185
clang::QualType::hasNonTrivialToPrimitiveCopyCUnion
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:6398
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6570
clang::Sema::getExprRange
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:463
clang::Type::isMemberPointerType
bool isMemberPointerType() const
Definition: Type.h:6552
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2919
clang::ImplicitConversionKind
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter&#39;s...
Definition: Overload.h:105
clang::MangleNumberingContext::getManglingNumber
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
checkBlockType
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:7438
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2525
clang::ASTContext::getFixedPointScale
unsigned char getFixedPointScale(QualType Ty) const
Definition: ASTContext.cpp:10779
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2702
clang::BlockDecl::hasCaptures
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:4156
DiagnoseSelfAssignment
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:12764
clang::ObjCMethodDecl::getClassInterface
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1155
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3075
clang::LocalInstantiationScope
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:227
diagnoseArithmeticOnTwoFunctionPointers
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:9486
clang::ASTContext::getBuiltinVaListType
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1929
clang::Sema::ActOnConditionalOp
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7914
clang::TargetInfo::getLongWidth
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:401
clang::Sema::getFunctionLevelDeclContext
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1283
clang::Sema::ActOnIntegerConstant
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3447
clang::Expr::EvaluateKnownConstIntCheckOverflow
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Definition: ExprConstant.cpp:13973
handleIntToFloatConversion
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1066
clang::APFixedPoint::getValue
llvm::APSInt getValue() const
Definition: FixedPoint.h:110
breakDownVectorType
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:6605
clang::ASTContext::FractTy
CanQualType FractTy
Definition: ASTContext.h:1032
clang::QualType::isCForbiddenLValueType
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C...
Definition: Type.h:6459
clang::Sema::LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3435
clang::Sema::ActOnParenListExpr
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6947
clang::ASTContext::Char32Ty
CanQualType Char32Ty
Definition: ASTContext.h:1024
checkConditionalNullPointer
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7032
diagnoseUnknownAnyExpr
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:17944
clang::LookupResult::setLookupName
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:248
clang::ASTContext::getPointerDiffType
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Definition: ASTContext.cpp:5298
clang::TemplateIdAnnotation::TemplateNameLoc
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
Definition: ParsedTemplate.h:160
ConvertUTF8ToWideString
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3308
clang::Type::STK_FloatingComplex
Definition: Type.h:2141
clang::NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:245
clang::Type::isArithmeticType
bool isArithmeticType() const
Definition: Type.cpp:2036
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:66
clang::CallExpr::getNumArgs
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2689
clang::isGenericLambdaCallOperatorSpecialization
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
clang::NullabilityKind
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:315
clang::BuiltinType::getKind
Kind getKind() const
Definition: Type.h:2495
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
EvaluatedExprVisitor.h
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
clang::EnumConstantDecl
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2941
clang::Type::isRealFloatingType
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2021
clang::sema::CapturingScopeInfo::ReturnType
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:659
clang::Sema::LookupMethodInObjectType
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
Definition: SemaExprObjC.cpp:1810
clang::sema::CapturingScopeInfo::isVLATypeCaptured
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:225
IsReadonlyMessage
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:11561
clang::QualType::DK_nontrivial_c_struct
Definition: Type.h:1167
clang::Expr::hasPlaceholderType
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:481
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:2087
Base
clang::Sema::ActOnArraySubscriptExpr
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4452
clang::TypedefDecl
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3173
SourceManager.h
Defines the SourceManager interface.
clang::ConversionFixItGenerator::tryToFixConversion
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
Definition: SemaFixItUtils.cpp:50
clang::CharSourceRange::getTokenRange
static CharSourceRange getTokenRange(SourceRange R)
Definition: SourceLocation.h:258
clang::QualType::addConst
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:823
clang::Sema::BuildCXXDefaultArgExpr
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:5051
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2200
clang::ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:140
clang::TemplateArgument::Expression
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
diagnoseObjCLiteralComparison
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:10309
clang::StringLiteral::isAscii
bool isAscii() const
Definition: Expr.h:1830
clang::Expr::MLV_IncompleteType
Definition: Expr.h:285
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6594
clang::Sema::InvalidLogicalVectorOperands
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:8867
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:2913
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
CheckIdentityFieldAssignment
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:11950
clang::Type::isSpecificPlaceholderType
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6764
clang::InitializedEntity::InitializeParameter
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Definition: Initialization.h:248
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1958
clang::ASTContext::getLValueReferenceType
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
Definition: ASTContext.cpp:3222
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:3053
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1411
clang::Sema::CheckRemainderOperands
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:9426
clang::sema::Capture::getCaptureType
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:625
clang::Sema::DiagnoseConditionalForNull
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:6956
clang::Sema::ActOnBlockArguments
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:14238
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
DiagnoseRecursiveConstFields
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:11758
clang::FunctionProtoType::isVariadic
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4086
clang::AvailabilitySpec::getPlatform
StringRef getPlatform() const
Definition: Availability.h:52
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:34
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:1976
clang::OverloadCandidateSet::CSK_Normal
Normal lookup.
Definition: Overload.h:900
clang::CXXNewExpr::getOperatorNew
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2218
clang::Type::isExtVectorType
bool isExtVectorType() const
Definition: Type.h:6610
clang::Expr::setType
void setType(QualType t)
Definition: Expr.h:138
clang::Sema::PendingInstantiations
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:8541
clang::Sema::AssignConvertType
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:10601
clang::UnresolvedLookupExpr
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3037
isReferenceToNonConstCapture
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:11575
DeclTemplate.h
Defines the C++ template declaration subclasses.
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3469
clang::Scope::BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it...
Definition: Scope.h:51
clang::Sema::TUScope
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:906
clang::AutoType
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:4874
checkPointerIntegerMismatch
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer...
Definition: SemaExpr.cpp:7239
clang::CallExpr::setNumArgsUnsafe
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:2732
clang::NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:231
CheckObjCTraitOperandConstraints
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3903
clang::Sema::DefaultArgumentPromotion
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:776
clang::sema::Capture::isCopyCapture
bool isCopyCapture() const
Definition: ScopeInfo.h:584
clang::ParenExpr
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1994
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6452
clang::Sema::CheckVecStepExpr
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4151
clang::Sema::forceUnknownAnyToType
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:17917
clang::Sema::CreateBuiltinArraySubscriptExpr
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4734
clang::ASTContext::ARCUnbridgedCastTy
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1047
clang::FieldDecl::getParent
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
clang::IntegerLiteral
Definition: Expr.h:1446
clang::Sema::ActOnVAArg
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14552
clang::ASTContext::getBlockPointerType
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
Definition: ASTContext.cpp:3190
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1450
clang::CanQual::getUnqualifiedType
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Definition: CanonicalType.h:618
clang::ASTContext::LongTy
CanQualType LongTy
Definition: ASTContext.h:1025
clang::Sema::CheckShiftOperands
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10099
clang::Type::isClkEventT
bool isClkEventT() const
Definition: Type.h:6691
clang::Sema::CheckSubtractionOperands
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9810
clang::ASTContext::getCorrespondingSignedFixedPointType
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
Definition: ASTContext.cpp:10891
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1931
clang::Expr::MLV_ArrayTemporary
Definition: Expr.h:295
clang::CXXRecordDecl::isDerivedFrom
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Definition: CXXInheritance.cpp:91
clang::sema::CapturingScopeInfo::ImpCap_LambdaByref
Definition: ScopeInfo.h:634
CXXInheritance.h
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:3070
clang::ASTContext::getCorrespondingUnsignedType
QualType getCorrespondingUnsignedType(QualType T) const
Definition: ASTContext.cpp:9474
clang::TemplateArgument::Declaration
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
clang::Sema::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:49
clang::CXXConstructExpr
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1422
clang::DeclarationNameInfo::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclarationName.h:805
clang::Expr::getValueKindForType
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:404
clang::ObjCRuntime::allowsPointerArithmetic
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:323
clang::CharUnits::isZero
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
clang::QualType::withConst
QualType withConst() const
Definition: Type.h:826
convertPointersToCompositeType
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:10169
clang::FunctionType::getNoReturnAttr
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3688
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
clang::TemplateIdAnnotation::Kind
TemplateNameKind Kind
The kind of template that Template refers to.
Definition: ParsedTemplate.h:173
DeclObjC.h
clang::ASTContext::adjustStringLiteralBaseType
QualType adjustStringLiteralBaseType(QualType StrLTy) const
Definition: ASTContext.cpp:4081
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6227
clang::FunctionDecl::getCallResultType
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2481
handleComplexFloatConversion
static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1010
clang::OpaquePtr< QualType >
LiteralSupport.h
clang::ASTContext::getLogicalOperationType
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1810
clang::AutoTypeKeyword::Auto
auto
clang::FPOptions
Floating point control options.
Definition: LangOptions.h:357
clang::XRayInstrKind::Function
constexpr XRayInstrMask Function
Definition: XRayInstr.h:38
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=CSK_unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:1955
clang::MSPropertySubscriptExpr
MS property subscript expression.
Definition: ExprCXX.h:937
clang::FunctionDecl::isDefined
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2883
clang::Sema::CheckVectorLogicalOperands
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11394
CheckForModifiableLvalue
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:11822
clang::DecayedTypeLoc
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1187
clang::FunctionDecl::isImplicitlyInstantiable
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:3571
clang::Sema::VerifyICEDiagnoser
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:11090
clang::CXXBasePath
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Definition: CXXInheritance.h:70
checkVectorResult
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:7378
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2383
clang::LookupResult::clear
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:554
clang::Sema::CheckCXXDefaultArgExpr
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4926
clang::ASTContext::WideCharTy
CanQualType WideCharTy
Definition: ASTContext.h:1020
TryTypoCorrectionForCall
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr *> Args)
Definition: SemaExpr.cpp:5103
clang::Sema::MarkFunctionReferenced
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:15521
clang::FunctionDecl::param_size
size_t param_size() const
Definition: Decl.h:2415
clang::CC_X86StdCall
Definition: Specifiers.h:267
clang::Sema::isQualifiedMemberAccess
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:13802
clang::Sema::InstantiateVariableDefinition
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
Definition: SemaTemplateInstantiateDecl.cpp:4978
clang::Expr::isModifiableLvalueResult
isModifiableLvalueResult
Definition: Expr.h:278
clang::ASTContext::HalfTy
CanQualType HalfTy
Definition: ASTContext.h:1040
clang::Sema::ActOnGNUNullExpr
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:14673
clang::NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:164
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:2910
clang::InitializedEntity::InitializeTemporary
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
Definition: Initialization.h:318
clang::Type::getAsUnionType
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:592
Value
Value
Definition: UninitializedValues.cpp:101
clang::CharacterLiteral::UTF16
Definition: Expr.h:1536
clang::Sema::BuildBuiltinOffsetOf
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:13983
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:98
clang::Type::isUnsignedIntegerType
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1968
ASTLambda.h
This file provides some common utility functions for processing Lambda related AST Constructs...
clang::Sema::CheckVectorCast
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:6686
hasIsEqualMethod
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:10221
clang::TemplateArgumentListInfo::setRAngleLoc
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:574
clang::CXXConstructExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.cpp:587
clang::Sema::UseArgumentDependentLookup
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:2947
clang::EnterExpressionEvaluationContext
RAII object that enters a new expression evaluation context.
Definition: Sema.h:12029
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:820
funcHasParameterSizeMangling
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:15395
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:58
clang::ImplicitConversionSequence::isFailure
bool isFailure() const
Definition: Overload.h:632
clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:1088
clang::Expr::MLV_LValueCast
Definition: Expr.h:284
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1792
clang::ObjCIsaExpr
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC &#39;id&#39; type.
Definition: ExprObjC.h:1492
clang::Qualifiers::removeObjCLifetime
void removeObjCLifetime()
Definition: Type.h:339
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2445
clang::CompoundLiteralExpr
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3077
clang::FunctionProtoType::isParamConsumed
bool isParamConsumed(unsigned I) const
Definition: Type.h:4181
diagnoseFunctionPointerToVoidComparison
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:10198
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:3964
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6598
clang::SC_None
Definition: Specifiers.h:237
clang::DeclarationNameInfo::setCXXLiteralOperatorNameLoc
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
Definition: DeclarationName.h:779
clang::ASTContext::getFixedPointMax
APFixedPoint getFixedPointMax(QualType Ty) const
Definition: ASTContext.cpp:10881
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
clang::Type::isOverloadableType
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:6907
clang::ASTContext::Float128Ty
CanQualType Float128Ty
Definition: ASTContext.h:1028
clang::Sema::computeDeclContext
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Definition: SemaCXXScopeSpec.cpp:53
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:3837
clang::ASTContext::ShortAccumTy
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
clang::PredefinedExpr::FuncDName
Definition: Expr.h:1918
canConvertIntToOtherIntTy
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:8969
clang::VarTemplateSpecializationDecl
Represents a variable template specialization, which refers to a variable template with a given set o...
Definition: DeclTemplate.h:2655
TreeTransform.h
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:414
clang::Sema::UndefinedButUsed
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1203
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:91
clang::ASTContext::getMemberPointerType
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
Definition: ASTContext.cpp:3295
clang::TypoCorrection::getCorrectionDeclAs
DeclClass * getCorrectionDeclAs() const
Definition: TypoCorrection.h:156
clang::Sema::BuildIvarRefExpr
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:2680
handleIntegerToComplexFloatConversion
static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Converts an integer to complex float type.
Definition: SemaExpr.cpp:988
clang::Sema::ActOnStartStmtExpr
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:13901
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:553
clang::TypoCorrection::isOverloaded
bool isOverloaded() const
Definition: TypoCorrection.h:215
clang::ValueStmt::getExprStmt
const Expr * getExprStmt() const
Definition: Stmt.cpp:335
CheckAlignOfExpr
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4095
clang::ObjCPropertyDecl::findPropertyDecl
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:176
clang::InitializationKind::CreateDirectList
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Definition: Initialization.h:609
clang::PredefinedExpr::Function
Definition: Expr.h:1916
ConstFunction
Definition: SemaExpr.cpp:11621
clang::ASTContext::ShortFractTy
CanQualType ShortFractTy
Definition: ASTContext.h:1032
SemaInternal.h
clang::Sema::BuildUnaryOp
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:13839
clang::tooling::fixit::internal::getSourceRange
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
clang::Sema::tryCaptureVariable
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:16153
clang::CPlusPlus11
Definition: LangStandard.h:48
DiagnoseConstAssignment
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:11633
clang::ConversionFixItGenerator::Hints
std::vector< FixItHint > Hints
The list of Hints generated so far.
Definition: SemaFixItUtils.h:41
clang::MemberSpecializationInfo::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:644
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1595
clang::Expr::LV_ClassTemporary
Definition: Expr.h:272
ExprCXX.h
Defines the clang::Expr interface and subclasses for C++ expressions.
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:92
clang::BinaryOperator::isAdditiveOp
bool isAdditiveOp() const
Definition: Expr.h:3511
clang::BinaryOperator::isEqualityOp
bool isEqualityOp() const
Definition: Expr.h:3522
clang::sema::CapturingScopeInfo::addVLATypeCapture
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:669
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2105
diagnosePointerIncompatibility
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:9705
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:143
GCCTypeClass::Bool
clang::Type::isVariableArrayType
bool isVariableArrayType() const
Definition: Type.h:6582
ContextKind
tok::TokenKind ContextKind
Definition: TokenAnnotator.cpp:1259
clang::Type::hasFloatingRepresentation
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g., it is a floating-point type or a vector thereof.
Definition: Type.cpp:2014
clang::VarDecl::isARCPseudoStrong
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1390
clang::Expr::isXValue
bool isXValue() const
Definition: Expr.h:260
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3395
clang::Sema::MarkDeclarationsReferencedInType
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:17125
clang::LangOptions::LaxVectorConversionKind::Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
checkObjCPointerTypesForAssignment
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:8212
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3748
OpenCLConvertScalarsToVectors
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:7324
clang::TreeTransform
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:99
clang::Sema::FindCompositeObjCPointerType
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:7589
clang::TargetInfo::getPointerWidth
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:361
clang::Expr::isOrdinaryOrBitFieldObject
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:425
clang::UnqualifiedId::TemplateId
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1012
clang::Sema::UsualUnaryConversions
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:727
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
clang::Sema::ActOnPostfixUnaryOp
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4410
clang::Sema::BuildSourceLocExpr
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:14697
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1161
clang::NamedDecl::getFormalLinkage
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:353
clang::FunctionProtoType::ExtProtoInfo::ExtInfo
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3838
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:57
clang::Sema::NSAPIObj
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:938
clang::Type::STK_MemberPointer
Definition: Type.h:2136
clang::Sema::CreateOverloadedBinOp
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:13126
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1063
handleComplexIntConversion
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1242
clang::DeclaratorDecl::getOuterLocStart
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations. ...
Definition: Decl.cpp:1879
needsConversionOfHalfVec
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType SrcType)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:12910
clang::Sema::CheckPtrComparisonWithNullChar
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:10731
clang::Sema::DiagnoseUnusedExprResult
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:218
clang::SourceLocExpr
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(), or __builtin_FILE().
Definition: Expr.h:4295
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:136
clang::ObjCObjectType
Represents a class type in Objective C.
Definition: Type.h:5694
clang::OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:147
clang::TemplateArgument::getAsExpr
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
clang::OpenCL
Definition: LangStandard.h:56
DiagnoseConditionalPrecedence
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:7828
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:236
clang::TypoCorrection::getCorrection
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
Definition: TypoCorrection.h:84
clang::Sema::inTemplateInstantiation
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:8412
clang::ExprEmpty
ExprResult ExprEmpty()
Definition: Ownership.h:285
checkArithmeticOpPointerOperand
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:9537
llvm::Optional
Definition: LLVM.h:37
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3971
State
LineState State
Definition: UnwrappedLineFormatter.cpp:932
clang::Type::isObjCLifetimeType
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4080
clang::Expr::ClassifyLValue
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
Definition: ExprClassification.cpp:659
clang::ArraySubscriptExpr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2523
clang::ObjCMethodFamily
ObjCMethodFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:623
clang::UETT_PreferredAlignOf
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:106
clang::FullExpr
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:950
clang::TemplateSpecializationType::anyDependentTemplateArguments
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3428
rewriteBuiltinFunctionDecl
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:5527
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
checkPointerTypesForAssignment
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
Definition: SemaExpr.cpp:8023
clang::Type::isCharType
bool isCharType() const
Definition: Type.cpp:1871
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:3963
clang::TypeLocBuilder::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Definition: TypeLocBuilder.h:101
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:275
clang::DeclarationName::getNameKind
NameKind getNameKind() const
Determine what kind of name this is.
Definition: DeclarationName.h:384
clang::Type::isObjCIdType
bool isObjCIdType() const
Definition: Type.h:6651
NCCK_Block
Definition: SemaExpr.cpp:11574
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2729
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:194
clang::Sema::checkSpecializationVisibility
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We&#39;ve found a use of a templated declaration that would trigger an implicit instantiation.
Definition: SemaTemplate.cpp:10799
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
clang::ASTContext::setBOOLDecl
void setBOOLDecl(TypedefDecl *TD)
Save declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1910
clang::CharacterLiteral::UTF32
Definition: Expr.h:1537
clang::ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:107
clang::ArrayType::Static
Definition: Type.h:2896
clang::TemplateArgumentListInfo::size
unsigned size() const
Definition: TemplateBase.h:576
clang::CompoundStmt::getStmtExprResult
Stmt * getStmtExprResult()
Definition: Stmt.h:1424
clang::UnaryExprOrTypeTrait
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:96
clang::Sema::DefaultedComparisonKind
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:1259
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:3841
clang::ASTContext::LongAccumTy
CanQualType LongAccumTy
Definition: ASTContext.h:1029
clang::ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:137
clang::GNUNullExpr
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4210
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6516
clang::CallExpr::setArg
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2712
clang::Sema::DiagnoseEqualityWithExtraParens
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:17373
DiagnoseDirectIsaAccess
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:535
clang::CallExpr::shrinkNumArgs
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:2723
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::ASTContext::ObjCQualifiedIdTypesAreCompatible
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
Definition: ASTContext.cpp:8191
clang::Decl::isDefinedOutsideFunctionOrMethod
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:855
ScopeInfo.h
clang::Sema::CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:10629
diagnoseArithmeticOnTwoVoidPointers
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:9452
clang::Type::isSpecificBuiltinType
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6744
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1908
clang::UnresolvedMemberExpr
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3771
clang::FixItHint::isNull
bool isNull() const
Definition: Diagnostic.h:86
clang::Sema::isOpenMPCapturedByRef
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
Definition: SemaOpenMP.cpp:1803
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:93
clang::Sema::ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:10583
clang::ExtVectorElementExpr
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:5518
clang::Sema::ActOnObjCBoolLiteral
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:18109
clang::LookupResult::getResultKind
LookupResultKind getResultKind() const
Definition: Lookup.h:321
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3202
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:723
clang::Sema::CheckConditionalOperands
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:7452
clang::DeclarationName::CXXLiteralOperatorName
Definition: DeclarationName.h:212
clang::Type::isObjCQualifiedClassType
bool isObjCQualifiedClassType() const
Definition: Type.h:6645
clang::Sema::ExpressionEvaluationContextRecord::ExprContext
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
clang::Sema::DefaultFunctionArrayConversion
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:472
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:15281
clang::QualType::isAtLeastAsQualifiedAs
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6433
clang::BinaryOperator::isAssignmentOp
bool isAssignmentOp() const
Definition: Expr.h:3563
clang::Type::isIntegralOrEnumerationType
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6881
clang::LookupResult::NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
llvm::SmallVectorImpl
Definition: LLVM.h:36
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:580
clang::Sema::NoteDeletedFunction
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
clang::VK_RValue
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2530
clang::InitializedEntity::InitializeBlock
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Definition: Initialization.h:295
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
clang::Expr::EvaluateAsBooleanCondition
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
Definition: ExprConstant.cpp:13761
clang::NullabilityKind::Nullable
Values of this type can be null.
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:762
clang::Language::CUDA
clang::ASTContext::LongFractTy
CanQualType LongFractTy
Definition: ASTContext.h:1032
clang::Scope::ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:62
clang::Type::STK_ObjCObjectPointer
Definition: Type.h:2135
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:507
clang::VarDecl::getPointOfInstantiation
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2570
clang::BinaryOperator::getOpcodeStr
StringRef getOpcodeStr() const
Definition: Expr.h:3490
clang::ObjCIvarRefExpr::getOpLoc
SourceLocation getOpLoc() const
Definition: ExprObjC.h:597
GetFixedPointRank
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1288
checkCondition
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:6995
clang::TypeLocBuilder
Definition: TypeLocBuilder.h:22
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:261
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:997
clang::Expr::MLV_MemberFunction
Definition: Expr.h:291
clang::ParenListExpr::Create
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4497
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4403
clang::Sema::CheckStaticArrayArgument
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter, check that it is non-null, and that if it is formed by array-to-pointer decay, the underlying array is sufficiently large.
Definition: SemaExpr.cpp:5388
IsTypeModifiable
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:11611
clang::ObjCIvarRefExpr::isArrow
bool isArrow() const
Definition: ExprObjC.h:584
clang::Sema::ActOnBlockStmtExpr
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:14367
clang::sema::Capture::isThisCapture
bool isThisCapture() const
Definition: ScopeInfo.h:579
CheckVecStepTraitOperandType
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:3855
clang::BinaryOperatorKind
BinaryOperatorKind
Definition: OperationKinds.h:25
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:960
clang::FixedPointLiteral::CreateFromRawInt
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:950
clang::Sema::CanUseDecl
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:54
checkArithmeticOrEnumeralThreeWayCompare
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10622
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2807
clang::Expr::EvalStatus::Diag
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:573
clang::StringLiteral::getLength
unsigned getLength() const
Definition: Expr.h:1823
clang::TypeSpecTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:527
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
OpenCLArithmeticConversions
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:7269
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:170
clang::Sema::CallExprUnaryConversions
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:705
canConvertIntTyToFloatTy
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:9007
clang::Expr::refersToBitField
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:446
clang::FunctionDecl::getBody
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2894
clang::CXXDeleteExpr::getOperatorDelete
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2399
clang::DeclAccessPair::make
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
Definition: DeclAccessPair.h:35
clang::Sema::MaybeConvertParenListExprToParenExpr
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:6931
isVariableCapturable
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:15876
clang::Sema::ActOnBlockStart
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:14209
clang::ParmVarDecl::getOriginalType
QualType getOriginalType() const
Definition: Decl.cpp:2681
clang::Sema::getCurMethodDecl
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1309
clang::OverloadExpr::FindResult::HasFormOfMemberPointer
bool HasFormOfMemberPointer
Definition: ExprCXX.h:2896
clang::Sema::LK_Block
Definition: Sema.h:3111
clang::IdentifierInfo::getTokenID
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
Definition: IdentifierTable.h:185
clang::CharUnits
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
clang::Sema::BuildDeclRefExpr
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1868
clang::Sema::ActOnCallExpr
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5708
clang::Expr::EvalResult::Val
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:588
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
clang::FunctionCallFilterCCC::ValidateCandidate
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Definition: SemaLookup.cpp:5236
clang::Expr::MLV_InvalidExpression
Definition: Expr.h:283
clang::Expr::LV_Valid
Definition: Expr.h:264
clang::format::Tok
const FormatToken & Tok
Definition: BreakableToken.h:239
clang::CXXBindTemporaryExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1400
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:31
clang::PredefinedExpr::PrettyFunction
Definition: Expr.h:1921
clang::Type::getAsArrayTypeUnsafe
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:7053
clang::Sema::CheckAssignmentConstraints
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing, variable initialization, and function return values.
Definition: SemaExpr.cpp:8246
clang::Scope::ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:55
clang::Sema::CheckFloatComparison
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS)
Check for comparisons of floating point operands using != and ==.
Definition: SemaChecking.cpp:10130
clang::FunctionDecl::hasPrototype
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2173
clang::NullabilityKind::Unspecified
Whether values of this type can be null is (explicitly) unspecified.
clang::FunctionCallFilterCCC
Definition: TypoCorrection.h:379
clang::VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:134
clang::Expr::getValueKind
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
clang::ComparisonCategoryType::First
NestedConstMember
Definition: SemaExpr.cpp:11625
clang::Sema::CorrectDelayedTyposInExpr
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Definition: SemaExprCXX.cpp:8166
clang::Sema::CheckCXXThisCapture
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of &#39;this&#39; is actually available in the current context, if it is a potentially ev...
Definition: SemaExprCXX.cpp:1146
clang::toTargetAddressSpace
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:66
checkDirectCallValidity
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:5601
clang::TypeDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3056
clang::Sema::IsFunctionConversion
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
Definition: SemaOverload.cpp:1528
clang::Sema::MarkDeclRefReferenced
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:17031
clang::getAsTypeTemplateDecl
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Definition: DeclTemplate.h:3271
clang::Type::STK_CPointer
Definition: Type.h:2133
recoverFromMSUnqualifiedLookup
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes...
Definition: SemaExpr.cpp:2235
clang::sema::BlockScopeInfo::FunctionType
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:726
clang::VarDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2549
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3029
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3434
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6326
clang::DeclaratorDecl::getQualifierLoc
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:737
clang::ASTContext::PseudoObjectTy
CanQualType PseudoObjectTy
Definition: ASTContext.h:1047
clang::QualType::hasNonTrivialToPrimitiveDestructCUnion
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:6392
clang::Qualifiers::getAddressSpace
LangAS getAddressSpace() const
Definition: Type.h:359
checkConditionalBlockPointerCompatibility
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:7174
clang::LangAS::opencl_private
clang::StandardConversionSequence::Second
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:267
clang::Sema::ActOnObjCAvailabilityCheckExpr
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:18128
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:187
clang::CorrectionCandidateCallback::setTypoNNS
void setTypoNNS(NestedNameSpecifier *NNS)
Definition: TypoCorrection.h:323
ExprObjC.h
clang::MemberExpr::isArrow
bool isArrow() const
Definition: Expr.h:3020
clang::NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:237
clang::ASTContext::getObjCClassRedefinitionType
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1674
clang::ASTContext::LongDoubleTy
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2995
clang::NullabilityKind::NonNull
Values of this type can never be null.
clang::Sema::getCapturedDeclRefType
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope...
Definition: SemaExpr.cpp:16394
clang::Expr::MLV_IncompleteVoidType
Definition: Expr.h:281
clang::getLambdaAwareParentOfDeclContext
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:81
clang::VariableArrayType::getSizeExpr
Expr * getSizeExpr() const
Definition: Type.h:3058
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7750
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
clang::ASTContext::getBOOLDecl
TypedefDecl * getBOOLDecl() const
Retrieve declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1905
CheckExtensionTraitOperandType
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3873
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:492
clang::StringLiteral::StringKind
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1733
clang::Sema::BuildResolvedCallExpr
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr *> Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:5911
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1166
clang::ParmVarDecl::hasUnparsedDefaultArg
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1709
clang::TypoExpr
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5978
clang::Expr::MLV_ArrayType
Definition: Expr.h:289
clang::Sema::ActOnIdExpression
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2276
clang::Sema::WarnOnPendingNoDerefs
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:15245
clang::APValue::isInt
bool isInt() const
Definition: APValue.h:361
clang::ParenListExpr
Definition: Expr.h:5143
clang::Lexer::AdvanceToTokenCharacter
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token...
Definition: Lexer.h:363
clang::BinaryOperator::isRelationalOp
bool isRelationalOp() const
Definition: Expr.h:3519
clang::TagDecl::hasNameForLinkage
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:3425
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
captureVariablyModifiedType
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4161
clang::CastExpr
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3150
CheckIndirectionOperand
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc)
CheckIndirectionOperand - Type check unary indirection (prefix &#39;*&#39;).
Definition: SemaExpr.cpp:12640
ConstMember
Definition: SemaExpr.cpp:11623
clang::OffsetOfNode
Helper class for OffsetOfExpr.
Definition: Expr.h:2163
clang::Sema::ExpressionEvaluationContext::DiscardedStatement
The current expression occurs within a discarded statement.
clang::ObjCProtocolDecl
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2078
clang::CXXBindTemporaryExpr
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1373
clang::CXXBindTemporaryExpr::getTemporary
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1392
clang::Type::isBlockCompatibleObjCPointerType
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3983
checkAddressOfFunctionIsAvailable
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
Definition: SemaOverload.cpp:9934
clang::LambdaExpr
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1818
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1324
clang::IntegerLiteral::Create
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:928
clang::CXXMethodDecl::isInstance
bool isInstance() const
Definition: DeclCXX.h:1959
clang::Expr::isTypeDependent
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
clang::Sema::DefaultFunctionArrayLvalueConversion
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:693
clang::Type::isScalarType
bool isScalarType() const
Definition: Type.h:6866
clang::Sema::ActOnNumericConstant
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3513
clang::Sema::CheckSingleAssignmentConstraints
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:8668
clang::Qualifiers::compatiblyIncludesObjCLifetime
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:517
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:98
clang::OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:141
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
clang::CPlusPlus2a
Definition: LangStandard.h:51
clang::Sema::MaybeODRUseExprs
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:615
DiagnoseLogicalAndInLogicalOrRHS
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the right hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:13298
clang::RecursiveASTVisitor
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Definition: RecursiveASTVisitor.h:151
clang::Sema::isUnevaluatedContext
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:8441
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
clang::NOUR_None
This is an odr-use.
Definition: Specifiers.h:162
clang::Sema::ExpressionEvaluationContextRecord::Lambdas
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:1064
clang::UnaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2080
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:324
clang::LookupResult::addDecl
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:426
clang::FunctionDecl::getBuiltinID
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3173
clang::Sema::PrepareScalarCast
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:6396
llvm::ArrayRef
Definition: LLVM.h:31
enclosingClassIsRelatedToClassInWhichMembersWereFound
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:5627
clang::Sema::IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:10625
llvm::SmallString< 32 >
clang::Sema::BuildDeclarationNameExpr
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3036
isOdrUseContext
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use...
Definition: SemaExpr.cpp:15483
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:404
clang::Type::STK_Floating
Definition: Type.h:2139
clang::ASTContext::getBOOLType
QualType getBOOLType() const
type of &#39;BOOL&#39; type.
Definition: ASTContext.h:1915
clang::FunctionDecl::getMemberSpecializationInfo
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:3540
ASTMutationListener.h
clang::Sema::ExpressionEvaluationContext::ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
clang::CXXScopeSpec::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:142
clang::Sema::checkUnknownAnyArg
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that&#39;s being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:17921
clang::Sema::MarkVariableReferenced
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3).
Definition: SemaExpr.cpp:16992
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2172
clang::ASTContext::UnsignedCharTy
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
clang::CXXDefaultArgExpr
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1202
Template.h
clang::Sema::LangOpts
const LangOptions & LangOpts
Definition: Sema.h:383
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
clang::Type::isUnsignedFixedPointType
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6862
clang::Expr::MLV_ClassTemporary
Definition: Expr.h:294
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2970
CheckForNullPointerDereference
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:510
clang::Type::hasUnsignedIntegerRepresentation
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
Definition: Type.cpp:1998
clang::TypeLocBuilder::pushTypeSpec
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Definition: TypeLocBuilder.h:68
clang::MemberExpr::Create
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1662
clang::Sema::ActOnStmtExprError
void ActOnStmtExprError()
Definition: SemaExpr.cpp:13905
clang::Sema::VarArgKind
VarArgKind
Definition: Sema.h:10541
clang::TypeLocBuilder::push
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Definition: TypeLocBuilder.h:93
clang::ObjCIvarRefExpr::getDecl
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:576
clang::Qualifiers::withoutObjCGCAttr
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:316
clang::Sema::ExpressionEvaluationContextRecord::NumCleanupObjects
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:1054
clang::BinaryOperator::isNullPointerArithmeticExtension
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:2114
rebuildPotentialResultsAsNonOdrUsed
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:16438
clang::AS_none
Definition: Specifiers.h:117
OEK_Variable
Definition: SemaExpr.cpp:11753
clang::sema::CapturingScopeInfo::ImpCaptureStyle
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:638
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
Definition: ParsedTemplate.h:177
clang::Sema::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1328
clang::Type::isIntegralOrUnscopedEnumerationType
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1857
clang::sema::LambdaScopeInfo::addPotentialCapture
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas...
Definition: ScopeInfo.h:908
clang::Type::isHalfType
bool isHalfType() const
Definition: Type.h:6783
Parent
NodeId Parent
Definition: ASTDiff.cpp:191
DiagnoseDivisionSizeofPointerOrArray
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:9339
clang::Sema::getNonOdrUseReasonInCurrentContext
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why...
Definition: SemaExpr.cpp:1887
clang::ConversionFixItGenerator::Kind
OverloadFixItKind Kind
The type of fix applied.
Definition: SemaFixItUtils.h:49
clang::ExplicitCastExpr::getTypeAsWritten
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3360
clang::OMPArraySectionExpr
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:44
clang::Sema::BuildPredefinedExpr
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK)
Definition: SemaExpr.cpp:3320
clang::DefaultFilterCCC
Definition: TypoCorrection.h:352
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:542
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3732
clang::ASTContext::getCorrespondingSaturatedType
QualType getCorrespondingSaturatedType(QualType Ty) const
Definition: ASTContext.cpp:10725
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
DiagnoseBinOpPrecedence
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:13372
clang::Type::isPromotableIntegerType
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2560
clang::LookupResult::setNamingClass
void setNamingClass(CXXRecordDecl *Record)
Sets the &#39;naming class&#39; for this lookup.
Definition: Lookup.h:408
clang::TypoCorrection::getFoundDecl
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Definition: TypoCorrection.h:146
ExprLooksBoolean
static bool ExprLooksBoolean(Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:7807
clang::sema::LambdaScopeInfo::Mutable
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:814
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1332
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
clang::Sema::checkVariadicArgument
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:878
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
clang::CXXScopeSpec::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:118
computeConditionalNullability
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:7864
clang::Decl::getAvailability
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:574
clang::Sema::MarkAnyDeclReferenced
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:17072
ConstUnknown
Definition: SemaExpr.cpp:11626
clang::VarDecl::isUsableInConstantExpressions
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2323
clang::Qualifiers::compatiblyIncludes
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:496
getDeclFromExpr
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12841
clang::Sema::CreateBuiltinBinOp
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc...
Definition: SemaExpr.cpp:12920
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3501
clang::Type::isComplexType
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:533
clang::Sema::CheckShadowingDeclModification
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if &#39;E&#39;, which is an expression that is about to be modified, refers to a shadowing declaration...
Definition: SemaDecl.cpp:7477
clang::sema::CapturedRegionScopeInfo
Retains information about a captured region.
Definition: ScopeInfo.h:742
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1494
DiagnoseBitwiseOpInBitwiseOp
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:13315
clang::CastKind
CastKind
CastKind - The kind of operation required for a conversion.
Definition: OperationKinds.h:20
clang::TypeLoc::getLocalSourceRange
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:158
emitEmptyLookupTypoDiagnostic
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr *> Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2000
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1993
checkConditionalVoidType
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, ExprResult &RHS)
Handle when one or both operands are void type.
Definition: SemaExpr.cpp:7014
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:583
clang::Expr::NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:735
clang::Sema::CheckAdditionOperands
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9715
clang::Sema::FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:10615
clang::Type::STK_IntegralComplex
Definition: Type.h:2140
clang::UnaryOperator::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:2077
clang::UnaryExprOrTypeTraitExpr
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2372
clang::Type::isNonOverloadPlaceholderType
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6771
clang::BinaryOperator::getOpcodeStr
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:2042
clang::Expr::MLV_InvalidMessageExpression
Definition: Expr.h:293
Used
Definition: ObjCUnusedIVarsChecker.cpp:29
OdrUseContext
OdrUseContext
Definition: SemaExpr.cpp:15468
clang::ASTContext::isObjCSelType
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2601
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6331
diagnoseStringPlusChar
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:9654
clang::Sema::MaybeODRUseExprSet
llvm::SmallPtrSet< Expr *, 2 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition: Sema.h:614
clang::DeclRefExpr::getLocation
SourceLocation getLocation() const
Definition: Expr.h:1255
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:68
clang::CharUnits::getQuantity
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
Overload.h
clang::ObjCIvarDecl::getUsageType
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type...
Definition: DeclObjC.cpp:1839
clang::Sema::ICEConvertDiagnoser
Definition: Sema.h:3068
clang::SourceLocExpr::IdentKind
IdentKind
Definition: Expr.h:4300
clang::VAArgExpr
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4244
clang::ConstraintSatisfaction
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:29
clang::NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:234
clang::Type::STK_BlockPointer
Definition: Type.h:2134
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
Definition: ASTContext.cpp:2816
clang::TemplateArgument::getAsDecl
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
clang::Sema::CTK_ErrorRecovery
Definition: Sema.h:3669
clang::Type::isSaturatedFixedPointType
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6836
handleIntegerConversion
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1192
BuildCookedLiteralOperatorCall
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr *> Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1697
clang::ArrayType::Normal
Definition: Type.h:2896
diagnoseArithmeticOnVoidPointer
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:9462
clang::ASTContext::getPromotedIntegerType
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Definition: ASTContext.cpp:6013
clang::TypoCorrection::getAsString
std::string getAsString(const LangOptions &LO) const
Definition: SemaLookup.cpp:5180
clang::Sema::CheckLogicalOperands
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11458
clang::Expr::isSameComparisonOperand
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr&#39;s will refer to the same value as a comparison operand.
Definition: Expr.cpp:3980
Offset
unsigned Offset
Definition: Format.cpp:1827
clang::Lexer::getSourceText
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:939
clang::CharacterLiteral::getValue
unsigned getValue() const
Definition: Expr.h:1564
clang::Expr::HasSideEffects
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3396
clang::Sema::ActOnCompoundLiteral
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:6159
clang::MultiLevelTemplateArgumentList::getInnermost
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:154
clang::OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:151
clang::sema::CapturingScopeInfo::ImpCap_None
Definition: ScopeInfo.h:634
clang::runWithSufficientStackSpace
void runWithSufficientStackSpace(llvm::function_ref< void()> Diag, llvm::function_ref< void()> Fn)
Run a given function on a stack with "sufficient" space.
Definition: Stack.h:40
clang::Sema::DiagnoseAssignmentAsCondition
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition...
Definition: SemaExpr.cpp:17315
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
clang::Sema::ActOnBinOp
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13407
clang::Sema::UsualArithmeticConversions
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1432
clang::StringLiteral::Create
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1084
clang::sema::BlockScopeInfo
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:716
Designator.h
clang::sema::LambdaScopeInfo::CallOperator
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:800
clang::ComplexType::getElementType
QualType getElementType() const
Definition: Type.h:2567
clang::CallExpr::Create
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1384
clang::ValueDecl::isWeak
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4675
isPotentiallyConstantEvaluatedContext
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:15366
clang::DeclarationName::getCXXNameType
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function)...
Definition: DeclarationName.h:439
clang::ASTContext::getVectorType
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Definition: ASTContext.cpp:3651
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4037
clang::sema::Capture::isInvalid
bool isInvalid() const
Definition: ScopeInfo.h:591
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
clang::PredefinedExpr::LFunction
Definition: Expr.h:1917
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:619
clang::Expr
This represents one expression.
Definition: Expr.h:108
End
SourceLocation End
Definition: USRLocFinder.cpp:166
clang::ConversionFixItGenerator::isNull
bool isNull()
Definition: SemaFixItUtils.h:84
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:250
clang::ExprValueKind
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:122
DiagnoseLogicalAndInLogicalOrLHS
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for &#39;&&&#39; in the left hand of a &#39;||&#39; expr.
Definition: SemaExpr.cpp:13276
clang::FunctionDecl::isVariadic
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2827
NCCK_None
Definition: SemaExpr.cpp:11574
clang::CallExpr::setCallee
void setCallee(Expr *F)
Definition: Expr.h:2665
clang::FunctionDecl::isDefaulted
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:2130
llvm::MutableArrayRef
Definition: LLVM.h:32
clang::FunctionDecl::isUserProvided
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: Decl.h:2147
getParentOfCapturingContextOrNull
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:15861
Id
int Id
Definition: ASTDiff.cpp:190
clang::ObjCInterfaceDecl::ivar_begin
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1474
clang::VarDecl::hasLocalStorage
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1045
clang::AttributedType::getNullabilityAttrKind
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4606
clang::TargetInfo::getIntWidth
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:396
EvaluatesAsTrue
static bool EvaluatesAsTrue(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;true&#39;.
Definition: SemaExpr.cpp:13261
clang::CPlusPlus
Definition: LangStandard.h:47
clang::DeclContext::containsDecl
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1401
clang::OverloadExpr::find
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2904
clang::UnresolvedMemberExpr::isImplicitAccess
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1531
clang::ObjCRuntime::allowsSizeofAlignof
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:315
clang::Sema::BuildCallExpr
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5734
DeclSpec.h
This file defines the classes used to store parsed information about declaration-specifiers and decla...
clang::Type::isObjCBuiltinType
bool isObjCBuiltinType() const
Definition: Type.h:6669
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
maybeDiagnoseAssignmentToFunction
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:14740
clang::Sema::FindCompositePointerType
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
Definition: SemaExprCXX.cpp:6265
clang::Sema::ActOnStmtExprResult
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:13952
clang::NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:167
V
#define V(N, I)
Definition: ASTContext.h:2941
clang::BlockExpr
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5579
clang::TypeLoc::getAs
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
clang::ASTContext::OMPArraySectionTy
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1055
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2663
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::Sema::isOpenMPCapturedDecl
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP constructs.
Definition: SemaOpenMP.cpp:1978
clang::DeclarationName::getAsString
std::string getAsString() const
Retrieve the human-readable string for this name.
Definition: DeclarationName.cpp:223
Lookup.h
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:126
clang::Expr::MLV_SubObjCPropertySetting
Definition: Expr.h:292
Preprocessor.h
Defines the clang::Preprocessor interface.
clang::OMF_dealloc
Definition: IdentifierTable.h:640
clang::Type::isNullPtrType
bool isNullPtrType() const
Definition: Type.h:6802
clang::Sema::VerifyIntegerConstantExpression
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:15009
clang::Sema::LK_String
Definition: Sema.h:3110
clang::CharLiteralParser
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Definition: LiteralSupport.h:175
DelayedDiagnostic.h
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
bool
#define bool
Definition: stdbool.h:15
clang::MemberExpr::performsVirtualDispatch
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3054
clang::Qualifiers::getObjCLifetime
ObjCLifetime getObjCLifetime() const
Definition: Type.h:333
clang::ConstantExpr::Create
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:294
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:452
clang::Sema::LookupIvarInObjCMethod
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we&#39;re currently inside an ObjC method...
Definition: SemaExpr.cpp:2607
clang::Type::isObjCClassType
bool isObjCClassType() const
Definition: Type.h:6657
DiagnoseShiftCompare
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13344
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
clang::Sema::ExpressionEvaluationContextRecord::SavedMaybeODRUseExprs
MaybeODRUseExprSet SavedMaybeODRUseExprs
Definition: Sema.h:1060
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:438
clang::ParenListExpr::getLParenLoc
SourceLocation getLParenLoc() const
Definition: Expr.h:5188
clang::StringLiteral::getCodeUnit
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1809
clang::OR_Success
Overload resolution succeeded.
Definition: Overload.h:53
clang::ConstraintSatisfaction::IsSatisfied
bool IsSatisfied
Definition: ASTConcept.h:47
clang::ObjCObjectPointerType::isObjCIdType
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:6013
clang::Type::isAnyComplexType
bool isAnyComplexType() const
Definition: Type.h:6602
isVector
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:8261
clang::UnaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1318
BuildOverloadedBinOp
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:13421
clang::ObjCInterfaceDecl::getSuperClass
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:337
clang::CXXDependentScopeMemberExpr::Create
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1446
clang::Sema::DiagnoseAssignmentResult
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:14759
clang::CXXRecordDecl::hasAnyDependentBases
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:543
clang::ASTContext::ShortTy
CanQualType ShortTy
Definition: ASTContext.h:1025
clang::ASTMutationListener
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Definition: ASTMutationListener.h:46
clang::AsTypeExpr
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:5642
diagnoseUncapturableValueReference
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, ValueDecl *var, DeclContext *DC)
Definition: SemaExpr.cpp:15788
Scope.h
clang::Sema::IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don&#39;t permit to be...
Definition: Sema.h:10634
clang::Sema::CheckPlaceholderExpr
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:17989
clang::Type::getScalarTypeKind
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2051
clang::CallExpr::getDirectCallee
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2681
clang::DeclRefExpr::refersToEnclosingVariableOrCapture
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1377
clang::FloatingLiteral::Create
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:984
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
isMSPropertySubscriptExpr
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4444
clang::Sema::FullExprArg
Definition: Sema.h:4063
clang::Sema::RequireCompleteType
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7919
TypeLoc.h
Defines the clang::TypeLoc interface and its subclasses.
clang::ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:143
clang::UnqualifiedId::getKind
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1042
clang::Sema::ExpressionEvaluationContext::Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
clang::Sema::DiscardCleanupsInEvaluationContext
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:15346
clang::DeclarationName::getAsIdentifierInfo
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn&#39;t...
Definition: DeclarationName.h:410
clang::Expr::NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:739
checkForArray
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:10401
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2859
clang::Expr::getType
QualType getType() const
Definition: Expr.h:137
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1836
clang::VarDecl::hasDefinition
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2203
clang::LangOptions::LaxVectorConversionKind::All
Permit vector bitcasts between all vectors with the same total bit-width.
clang::Type::STK_Bool
Definition: Type.h:2137
clang::Sema::ExpressionEvaluationContextRecord::ParentCleanup
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:1047
clang::sema::CapturingScopeInfo::getCapture
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:697
clang::ObjCInterfaceDecl::lookupInstanceVariable
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:620
clang::Sema::TooManyArguments
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:11929
clang::Expr::setValueKind
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:431
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:257
clang::transformer::remove
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.cpp:82
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
clang::Sema::BuildLiteralOperatorCall
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
Definition: SemaOverload.cpp:14444
clang::Qualifiers::setAddressSpace
void setAddressSpace(LangAS space)
Definition: Type.h:379
clang::PredefinedExpr::Create
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:633
clang::Sema::ConvertArgumentsForCall
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr *> Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:5148
clang::Type::ScalarTypeKind
ScalarTypeKind
Definition: Type.h:2132
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:950
clang::MultiLevelTemplateArgumentList
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:64
clang::Sema::ExpressionEvaluationContextRecord::PossibleDerefs
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:1079
clang::Sema::ConditionKind
ConditionKind
Definition: Sema.h:11026
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:166
ConvertTokenKindToUnaryOpcode
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:12742
clang::Sema::OffsetOfComponent
Definition: Sema.h:4933
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:217
clang::UnaryOperator
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:2046
clang::ObjCMethodDecl::isInstanceMethod
bool isInstanceMethod() const
Definition: DeclObjC.h:423
clang::ASTContext::getFunctionType
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1401
clang::Sema::getPreprocessor
Preprocessor & getPreprocessor() const
Definition: Sema.h:1330
clang::MemberExpr::getMemberLoc
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of &#39;F&#39;...
Definition: Expr.h:3025
clang::VectorType
Represents a GCC generic vector type.
Definition: Type.h:3235
clang::ArrayType::getSizeModifier
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2912
clang::Sema::ActOnChooseExpr
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14165
clang::Expr::LV_MemberFunction
Definition: Expr.h:270
clang::CXXConversionDecl::isLambdaToBlockPointerConversion
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2675
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1091
clang::Sema::CleanupVarDeclMarking
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:16792
clang::sema::Capture
Definition: ScopeInfo.h:496
clang::Type::getAsPlaceholderType
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6757
ASTConsumer.h
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1247
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:167
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2713
RecursiveASTVisitor.h
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1417
clang::TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
clang::FunctionDecl::isTrivial
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2122
clang::QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:6386
clang::Sema::LookupSingleName
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
Definition: SemaLookup.cpp:3049
clang::PredefinedExpr::IdentKind
IdentKind
Definition: Expr.h:1914
clang::CXXDeleteExpr::getDestroyedType
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:301
clang::ParenExpr::getSubExpr
const Expr * getSubExpr() const
Definition: Expr.h:2010
clang::CXXBindTemporaryExpr::getSubExpr
const Expr * getSubExpr() const
Definition: ExprCXX.h:1396
clang::sema::CapturedRegionScopeInfo::CapRegionKind
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:757
clang::sema::Capture::getLocation
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:616
clang::Sema::BuildCompoundLiteralExpr
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:6173
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
clang::ObjCMethodDecl::getSelfDecl
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:415
clang::BlockDecl::setBlockMangling
void setBlockMangling(unsigned Number, Decl *Ctx)
Definition: Decl.h:4207
clang::Qualifiers::removeCVRQualifiers
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:283
clang::Sema::checkDeclIsAllowedInOpenMPTarget
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
Definition: SemaOpenMP.cpp:16929
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:199
ConstMethod
Definition: SemaExpr.cpp:11624
checkArgsForPlaceholders
static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args)
Check an argument list for placeholders that we won&#39;t try to handle later.
Definition: SemaExpr.cpp:5500
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
clang::TypeLoc::getAsAdjusted
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2435
OEK_LValue
Definition: SemaExpr.cpp:11755
hasAnyExplicitStorageClass
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:124
clang::VarDecl::getCanonicalDecl
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2088
CorrectDelayedTyposInBinOp
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12889
clang::CXXOperatorCallExpr::getSourceRange
SourceRange getSourceRange() const
Definition: ExprCXX.h:141
clang::ImaginaryLiteral
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1...
Definition: Expr.h:1662
clang::Sema::BuildInitList
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:6340
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
clang::Sema::ActOnSourceLocExpr
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14691
clang::Sema::LookupDestructor
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
Definition: SemaLookup.cpp:3392
clang::Stmt::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
clang::Builtin::Context::hasPtrArgsOrResult
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:163
clang::InitializationKind::CreateCopy
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Definition: Initialization.h:648
DiagnoseCalleeStaticArrayParam
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5370
clang::Expr::getObjectKind
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:421
clang::NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:241
isPlaceholderToRemoveAsArg
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing...
Definition: SemaExpr.cpp:5446
clang::Type::isSignedFixedPointType
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6848
clang::LookupResult::isUnresolvableResult
bool isUnresolvableResult() const
Definition: Lookup.h:317
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:262
clang::ASTContext::getAttributedType
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
Definition: ASTContext.cpp:4199
clang::FunctionType::ExtInfo::withNoReturn
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3604
clang::ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:110
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6315
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:521
clang::Sema::ActOnParenExpr
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3850
clang::Sema::areLaxCompatibleVectorTypes
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector...
Definition: SemaExpr.cpp:6631
clang::FunctionProtoType::ExtProtoInfo::HasTrailingReturn
bool HasTrailingReturn
Definition: Type.h:3840
clang::BinaryOperator::isComparisonOp
bool isComparisonOp() const
Definition: Expr.h:3525
clang::StandardConversionSequence::getNarrowingKind
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
Definition: SemaOverload.cpp:307
diagnoseAddressOfInvalidType
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:12393
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4505
clang::CXXOperatorCallExpr::getOperatorLoc
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:129
clang::CXXScopeSpec::getScopeRep
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
MarkExprReferenced
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse)
Definition: SemaExpr.cpp:16996
clang::BinaryOperator::isBitwiseOp
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3515
clang::TargetInfo::useFP16ConversionIntrinsics
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:754
clang::ASTContext::getWideCharType
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1590
clang::BinaryOperator::getOverloadedOpcode
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2051
clang::ObjCIvarDecl::Private
Definition: DeclObjC.h:1964
checkConditionalObjectPointersCompatibility
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:7200
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1484
captureInLambda
static bool captureInLambda(LambdaScopeInfo *LSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:16055
clang::Expr::IgnoreConversionOperator
Expr * IgnoreConversionOperator() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:2999
clang::TargetInfo::getIntMaxTWidth
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:661
clang::Expr::EvaluateAsRValue
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Definition: ExprConstant.cpp:13752
clang::ASTContext::OverloadTy
CanQualType OverloadTy
Definition: ASTContext.h:1045
checkArithmeticIncompletePointerType
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:9516
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:1075
clang::ASTContext::getBuiltinMSVaListType
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:1943
clang::ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:134
clang::OverloadCandidateSet::iterator
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1053
clang::ASTContext::getObjCIdRedefinitionType
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1661
clang::Sema::MaybeBindToTemporary
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
Definition: SemaExprCXX.cpp:6598
clang::ASTContext::BuiltinFnTy
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
clang::Qualifiers::OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:171
AnalysisBasedWarnings.h
Kind
Kind
Definition: ChrootChecker.cpp:29
clang::OverloadExpr
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2844
clang::ImplicitConversionSequence
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:513
clang::getRewrittenOverloadedOperator
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6295
clang::Sema::CheckCaseExpression
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:18099
clang::VectorType::GenericVector
not a target-specific vector type
Definition: Type.h:3239
clang::ActionResult
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
clang::Sema::LookupInObjCMethod
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we&#39;re currently inside an ObjC method...
Definition: SemaExpr.cpp:2745
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5715
clang::FunctionProtoType::param_types
param_type_range param_types() const
Definition: Type.h:4119
clang::Sema::InstantiatingTemplate
A stack object to be created when performing template instantiation.
Definition: Sema.h:8243
clang::FunctionProtoType::getExtParameterInfo
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4167
clang::sema::Capture::getVariable
VarDecl * getVariable() const
Definition: ScopeInfo.h:605
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3975
clang::Expr::MLV_NotObjectType
Definition: Expr.h:280
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1331
clang::LangOptions::LaxVectorConversionKind::None
Permit no implicit vector bitcasts.
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:294
clang::Sema::runWithSufficientStackSpace
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:423
clang::ParenListExpr::getNumExprs
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5169
clang::LangAS::Default
clang::Expr::isNullPointerConstant
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3738
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Sema::ActOnConvertVectorExpr
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:5897
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3680
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:529
clang::NumericLiteralParser::GetFloatValue
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result)
GetFloatValue - Convert this numeric literal to a floating value, using the specified APFloat fltSema...
Definition: LiteralSupport.cpp:1040
clang::Expr::MLV_ConstQualifiedField
Definition: Expr.h:287
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4521
clang::BinaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
Definition: Expr.h:3466
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:18
clang::Sema::PrepareCastToObjCObjectPointer
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:6381
clang::QualType::getAddressSpace
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6377
clang::OMPDeclareReductionDecl
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:102
clang::DependentScopeDeclRefExpr::Create
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:556
clang::Expr::NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:712
clang::QualType::getSingleStepDesugaredType
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:967
clang::Sema::isValidVarArgType
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:828
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2076
clang::ObjCInterfaceType
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5894
SuggestParentheses
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:7731
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
clang::sema::LambdaScopeInfo::Lambda
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:797
clang::ASTContext::getObjCSelRedefinitionType
QualType getObjCSelRedefinitionType() const
Retrieve the type that &#39;SEL&#39; has been defined to, which may be different from the built-in &#39;SEL&#39; if &#39;...
Definition: ASTContext.h:1687
clang::FunctionType::ExtParameterInfo::isNoEscape
bool isNoEscape() const
Definition: Type.h:3487
CheckCommaOperands
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12198
checkArithmeticOrEnumeralCompare
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10704
clang::Sema::ConversionToObjCStringLiteralCheck
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:14705
captureInCapturedRegion
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:16018
clang::Type::getAsComplexIntegerType
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:550
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3196
clang::LangOptions::FPR_ToNearest
Rounding to nearest, corresponds to "round.tonearest".
Definition: LangOptions.h:200
clang::CSK_unspecified
Definition: Specifiers.h:33
clang::Expr::MLV_NoSetterProperty
Definition: Expr.h:290
MarkVarDeclODRUsed
static void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:15757
clang::CXXNewExpr
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:2100
clang::CXXNewExpr::getBeginLoc
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2339
getPrimaryDecl
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:12336
warnOnSizeofOnArrayDecay
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:3921
clang::Sema::ArithConvKind
ArithConvKind
Context in which we&#39;re performing a usual arithmetic conversion.
Definition: Sema.h:10575
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:713
IgnoreCommaOperand
static bool IgnoreCommaOperand(const Expr *E)
Definition: SemaExpr.cpp:12128
clang::ASTContext::CreateTypeSourceInfo
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
Definition: ASTContext.cpp:2802
clang::TargetInfo::getLongLongWidth
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:406
clang::VectorType::getElementType
QualType getElementType() const
Definition: Type.h:3270
clang::Decl::setReferenced
void setReferenced(bool R=true)
Definition: DeclBase.h:588
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:451
clang::Sema::IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible, but we accept them as an extension.
Definition: Sema.h:10619
clang::CC_X86FastCall
Definition: Specifiers.h:268
clang::Sema::ActOnCharacterConstant
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3390
clang::LookupResult::isOverloadedResult
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:313
clang::ExprObjectKind
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:139
clang::Sema::isExternalWithNoLinkageType
bool isExternalWithNoLinkageType(ValueDecl *VD)
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can&#39;t b...
Definition: Sema.cpp:672
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:5822
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
Definition: PartialDiagnostic.h:418
clang::OffsetOfExpr::Create
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr *> exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1550
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1844
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
clang::prec::Shift
Definition: OperatorPrecedence.h:39
Initialization.h
convertVector
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type...
Definition: SemaExpr.cpp:8950
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:188
clang::PredefinedExpr::FuncSig
Definition: Expr.h:1919
clang::ASTContext::getAsConstantArrayType
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2466
clang::OverloadExpr::FindResult
Definition: ExprCXX.h:2893
clang::Sema::TransformToPotentiallyEvaluated
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:15187
clang::ASTContext::getExtVectorType
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
Definition: ASTContext.cpp:3722
clang::PredefinedExpr::ComputeName
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl)
Definition: Expr.cpp:673
clang::StmtVisitor
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
clang::ASTContext::getNameForTemplate
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Definition: ASTContext.cpp:5502
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:48
clang::Sema::DefaultLvalueConversion
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:592
clang::InitializedEntity::InitializeCompoundLiteralInit
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
Definition: Initialization.h:398
clang::ASTContext::FloatTy
CanQualType FloatTy
Definition: ASTContext.h:1028
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2422
clang::OverloadExpr::FindResult::IsAddressOfOperand
bool IsAddressOfOperand
Definition: ExprCXX.h:2895
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:5711
clang::Sema::TryCapture_ExplicitByRef
Definition: Sema.h:4480
clang::Sema::ActOnInitList
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:6272
clang::Expr::NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:743
clang::OverloadCandidateSet::BestViableFunction
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
Definition: SemaOverload.cpp:9728
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1016
Paren
Definition: PPMacroExpansion.cpp:629
CheckBoolLikeConversion
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
Definition: SemaChecking.cpp:12115
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:24
clang::ParenListExpr::getExpr
Expr * getExpr(unsigned Init)
Definition: Expr.h:5171
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1519
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:541
clang::Expr::isValueDependent
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
clang::VarTemplateSpecializationDecl::getTemplateArgsInfo
const TemplateArgumentListInfo & getTemplateArgsInfo() const
Definition: DeclTemplate.h:2751
clang::CharacterLiteral::UTF8
Definition: Expr.h:1535
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Definition: SemaLookup.cpp:4999
clang::Sema::ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:10585
clang::StringLiteral::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1886
clang::Qualifiers::withoutObjCLifetime
Qualifiers withoutObjCLifetime() const
Definition: Type.h:321
clang::Sema::CheckTransparentUnionArgumentConstraints
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8616
clang::ASTContext::Float16Ty
CanQualType Float16Ty
Definition: ASTContext.h:1041
llvm::SmallVector
Definition: LLVM.h:35
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6508
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6618
clang::Sema::MarkFunctionParmPackReferenced
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:17063
clang::Sema::TryCapture_Implicit
Definition: Sema.h:4480
clang::VarDecl::DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1156
clang::VectorType::AltiVecBool
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3248
clang::sema::CapturingScopeInfo::Captures
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:651
clang::StandardConversionSequence::setAsIdentityConversion
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
Definition: SemaOverload.cpp:188
clang::Sema::MarkCaptureUsedInEnclosingContext
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:15781
clang::TargetInfo::getBuiltinVaListKind
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::CorrectionCandidateCallback::IsAddressOfOperand
bool IsAddressOfOperand
Definition: TypoCorrection.h:337
clang::Sema::ExpressionEvaluationContextRecord::NumTypos
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:1058
clang::Sema::tryCaptureOpenMPLambdas
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda&#39;s captured variables in the OpenMP region before the original lambda...
Definition: SemaOpenMP.cpp:3804
clang::ObjCPropertyDecl
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:741
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3274
clang::QualType::isDestructedType
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1174
clang::Expr::findBoundMemberType
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:2795
clang::FunctionProtoTypeLoc
Definition: TypeLoc.h:1466
clang::Expr::isLValue
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:258
clang::Expr::isModifiableLvalue
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
Definition: ExprClassification.cpp:679
clang::VectorType::AltiVecVector
is AltiVec vector
Definition: Type.h:3242
clang::ParmVarDecl::hasUninstantiatedDefaultArg
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1713
SemaFixItUtils.h
clang::Sema::VerifyICEDiagnoser::diagnoseFold
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR)
Definition: SemaExpr.cpp:15003
clang::Sema::DiagnoseUseOfDecl
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:207
clang::Sema::ActOnOMPArraySectionExpr
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4586
clang::PointerType::isAddressSpaceOverlapping
bool isAddressSpaceOverlapping(const PointerType &other) const
Returns true if address spaces of pointers overlap.
Definition: Type.h:2637
clang::sema::LambdaScopeInfo::addPotentialThisCapture
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:914
clang::Type::isFixedPointOrIntegerType
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:6832
clang::Type::getTypeClass
TypeClass getTypeClass() const
Definition: Type.h:1876
clang::UETT_AlignOf
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:100
clang::FunctionDecl::getMinRequiredArguments
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3263
clang::Decl::isUsed
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:398
clang::TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:178
clang::ASTContext::typesAreBlockPointerCompatible
bool typesAreBlockPointerCompatible(QualType, QualType)
Definition: ASTContext.cpp:8765
clang::Type::isAnyCharacterType
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1907
clang::AtomicType
Definition: Type.h:6125
clang::CharacterLiteral
Definition: Expr.h:1530
clang::isTargetAddressSpace
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:62
clang::EnumType::getDecl
EnumDecl * getDecl() const
Definition: Type.h:4528
clang::ObjCMessageExpr::getMethodDecl
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
ExprOpenMP.h
clang::Type::isVectorType
bool isVectorType() const
Definition: Type.h:6606
clang::ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:167
clang::getComparisonCategoryForBuiltinCmp
Optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
Definition: ComparisonCategories.cpp:23
clang::Qualifiers::OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:177
clang::StmtExpr
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3954
clang::PredefinedExpr::LFuncSig
Definition: Expr.h:1920
clang::OverloadCandidateSet
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:896
clang::TypeLoc::getFullDataSize
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:163
clang::UnresolvedMemberExpr::getNamingClass
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1569
clang::Sema::HandleExprEvaluationContextForTypeof
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:15354
clang::QualType::isCanonical
bool isCanonical() const
Definition: Type.h:6300
clang::TemplateArgumentListInfo::setLAngleLoc
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:573
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
clang::TemplateArgumentListInfo::addArgument
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:594
clang::ASTContext::hasSameUnqualifiedType
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2345
checkVectorShift
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:10013
clang::CXXNewExpr::getOperatorDelete
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2220
isEnabled
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
Definition: AnalysisBasedWarnings.cpp:1982
clang::Type::isInstantiationDependentType
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2156
clang::MultiVersionKind::None
FixedPoint.h
Defines the fixed point number interface.
clang::Sema::ActOnStmtExpr
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13914
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
clang::ASTContext::getArrayDecayedType
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
Definition: ASTContext.cpp:5800
clang::ASTContext::getFloatTypeSemantics
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
Definition: ASTContext.cpp:1704
DiagnoseBadShiftValues
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:9927
PerformCastFn
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1174
convertHalfVecBinOp
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptions FPFeatures)
Definition: SemaExpr.cpp:12856
clang::Sema::checkUnknownAnyCast
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:17897
clang::CompoundAssignOperator
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3654
clang::DeclAccessPair
A POD class for pairing a NamedDecl* with an access specifier.
Definition: DeclAccessPair.h:29
clang::ImplicitParamDecl
Definition: Decl.h:1531
clang::Type::isRealType
bool isRealType() const
Definition: Type.cpp:2027
clang::Type::isPlaceholderType
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6751
clang::AvailabilitySpec::getVersion
VersionTuple getVersion() const
Definition: Availability.h:51
clang::Sema::maybeExtendBlockObject
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we&#39;re in ARC.
Definition: SemaExpr.cpp:6366
clang::Sema::ReuseLambdaContextDecl_t
ReuseLambdaContextDecl_t
Definition: Sema.h:4437
clang::VarDecl::setTemplateSpecializationKind
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2633
clang::Preprocessor::isMacroDefined
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:1020
clang::CXXBasePathElement
Represents an element in a path from a derived class to a base class.
Definition: CXXInheritance.h:44
clang::AddrLabelExpr
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3910
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5296
clang::Sema::MarkMemberReferenced
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:17044
clang::FunctionParmPackExpr
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4337
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1018
clang::Expr::LV_ArrayTemporary
Definition: Expr.h:273
clang::TemplateArgument
Represents a template argument.
Definition: TemplateBase.h:50
ConstVariable
Definition: SemaExpr.cpp:11622
clang::Type::isPipeType
bool isPipeType() const
Definition: Type.h:6710
clang::Sema::DecomposeUnqualifiedId
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:1978
isInvalid
static bool isInvalid(LocType Loc, bool *Invalid)
Definition: SourceManager.cpp:1199
clang::NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:170
NonConstCaptureKind
NonConstCaptureKind
Is the given expression (which must be &#39;const&#39;) a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:11574
ConstructTransparentUnion
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union...
Definition: SemaExpr.cpp:8597
clang::ParmVarDecl::Create
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2672
clang::Expr::isKnownToHaveBooleanValue
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:130
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:21
clang::ASTContext::getFloatingTypeOrder
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i...
Definition: ASTContext.cpp:5903
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:106
clang::StringLiteral::Wide
Definition: Expr.h:1733
clang::FunctionType::getExtInfo
ExtInfo getExtInfo() const
Definition: Type.h:3691
clang::StringLiteral::UTF32
Definition: Expr.h:1733
clang::Sema::BuildParmVarDeclForTypedef
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:13238
clang::LangOptions::FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:214
isScopedEnumerationType
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:9921
clang::ASTContext::mergeTypes
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
Definition: ASTContext.cpp:9010
clang::VarDecl::getMemberSpecializationInfo
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2624
clang::UnaryOperatorKind
UnaryOperatorKind
Definition: OperationKinds.h:30
clang::ASTContext::hasDirectOwnershipQualifier
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
Definition: ASTContext.cpp:8132
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
clang::Sema::ActOnUnaryOp
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:13887
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:586
clang::Sema::getCurObjCLexicalContext
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:11919
clang::CXXDeleteExpr
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2359
TryImplicitConversion
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
Definition: SemaOverload.cpp:1421
clang::BlockDecl::captures
ArrayRef< Capture > captures() const
Definition: Decl.h:4164
diagnoseStringPlusInt
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:9624
clang::ASTContext::isSentinelNullExpr
bool isSentinelNullExpr(const Expr *E)
Definition: ASTContext.cpp:2706
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:402
clang::OverloadedOperatorKind
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
clang::CharacterLiteral::CharacterKind
CharacterKind
Definition: Expr.h:1532
clang::Sema::GetSignedVectorType
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:11200
clang::Sema::ImpCastExprToType
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:529
clang::TargetInfo::CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:228
unsupportedTypeConversion
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128 and long double if there is no support for such conve...
Definition: SemaExpr.cpp:1136
clang::TypeLoc::getType
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:132
clang::Sema::CheckVectorCompareOperands
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:11240
clang::FunctionDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3756
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:1863
clang::BinaryOperator::isShiftOp
bool isShiftOp() const
Definition: Expr.h:3513
clang::Sema::ExpressionEvaluationContext::UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
Definition: ParsedTemplate.h:181
clang::Sema::CheckLiteralKind
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:10267
clang::QualType::isCXX98PODType
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2193
clang::C99
Definition: LangStandard.h:43
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2980
clang::Sema::ComparisonCategoryUsage::OperatorInExpression
The &#39;<=>&#39; operator was used in an expression and a builtin operator was selected. ...
clang::SC_Extern
Definition: Specifiers.h:238
tryVectorConvertAndSplat
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:8903
clang::CastExpr::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:3204
clang::Sema::ActOnAsTypeExpr
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:5876
clang::Sema::DiagRuntimeBehavior
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:17266
type
checkArithmeticNull
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:9303
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
clang::StringLiteral::UTF16
Definition: Expr.h:1733
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
clang::Sema::CheckCompatibleReinterpretCast
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:1807
diagnoseTautologicalComparison
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:10415
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1229
clang::ASTContext::hasCvrSimilarType
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
Definition: ASTContext.cpp:5482
clang::ObjCIvarRefExpr::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
clang::ObjCAvailabilityCheckExpr
A runtime availability query.
Definition: ExprObjC.h:1699
clang::GenericSelectionExpr::Create
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> AssocTypes, ArrayRef< Expr *> AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression.
Definition: Expr.cpp:4238
clang::ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:113
clang::TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
ShouldLookupResultBeMultiVersionOverload
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3029
clang::sema::CapturingScopeInfo::CXXThisCaptureIndex
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of &#39;this&#39;; zero if &#39;this&#39; is not captured...
Definition: ScopeInfo.h:648
clang::Sema::CheckUnaryExprOrTypeTraitOperand
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:3944
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:145
clang::Stmt::getStmtClass
StmtClass getStmtClass() const
Definition: Stmt.h:1109
clang::VectorType::getVectorKind
VectorKind getVectorKind() const
Definition: Type.h:3280
clang::CastExpr::getCastKindName
const char * getCastKindName() const
Definition: Expr.h:3200
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:517
clang::ParmVarDecl::getDefaultArg
Expr * getDefaultArg()
Definition: Decl.cpp:2710
clang::FunctionDecl::setInstantiationIsPending
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2228
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:990
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:328
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2046
clang::CXXDefaultArgExpr::getExpr
const Expr * getExpr() const
Definition: ExprCXX.h:1241
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:6894
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:432
rebuildUnknownAnyFunction
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type...
Definition: SemaExpr.cpp:17543
clang::OverloadExpr::FindResult::Expression
OverloadExpr * Expression
Definition: ExprCXX.h:2894
clang::ASTContext::getFunctionNoProtoType
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
Definition: ASTContext.cpp:3836
clang::Expr::NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:719
clang::Sema::prepareVectorSplat
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6706
clang::UnresolvedSet
A set of unresolved declarations.
Definition: UnresolvedSet.h:148
clang::Sema::ExpressionEvaluationContextRecord::isConstantEvaluated
bool isConstantEvaluated() const
Definition: Sema.h:1106
clang::Sema::VerifyICEDiagnoser::diagnoseNotICE
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR)=0
clang::Sema::IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:10658
clang::interp::InitField
bool InitField(InterpState &S, CodePtr OpPC, uint32_t I)
Definition: Interp.h:465
clang::Expr::NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:725
diagnoseLogicalNotOnLHSofCheck
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:10359
clang::FunctionType::getCallResultType
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:3703
EmitDiagnosticForLogicalAndInLogicalOr
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a &#39;&&&#39; expr that is inside a &#39;||&#39; one.
Definition: SemaExpr.cpp:13248
clang::Expr::isIntegerConstantExpr
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
Definition: ExprConstant.cpp:14502
clang::TemplateSpecializationKind
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
clang::DeclarationName::CXXDestructorName
Definition: DeclarationName.h:207
clang::InitializationKind::CreateCStyleCast
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Definition: Initialization.h:629
clang::StringLiteral::Ascii
Definition: Expr.h:1733
clang::Sema::FullExprArg::get
Expr * get() const
Definition: Sema.h:4072
clang::VarDecl::isInitCapture
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1421
clang::DeclarationName::CXXConversionFunctionName
Definition: DeclarationName.h:208
clang::sema::CapturedRegionScopeInfo::OpenMPLevel
unsigned short OpenMPLevel
Definition: ScopeInfo.h:759
clang::ExplicitCastExpr
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3337
checkArithmeticOnObjCPointer
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4430
clang::Sema::ActOnPredefinedExpr
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3373
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:690
clang::InitListExpr::setInitializedFieldInUnion
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4521
diagnoseXorMisusedAsPow
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:11280
clang::Sema::ActOnConstantExpression
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:16779
clang::Token::getLength
unsigned getLength() const
Definition: Token.h:129
clang::TypoCorrection::getCorrectionAsIdentifierInfo
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Definition: TypoCorrection.h:86
clang::TargetInfo::hasFeature
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1143
clang::ASTContext::areComparableObjCPointerTypes
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
Definition: ASTContext.cpp:8731
clang::Sema::GatherArgumentsForCall
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr *> Args, SmallVectorImpl< Expr *> &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5264
clang::Sema::CreateGenericSelectionExpr
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> Types, ArrayRef< Expr *> Exprs)
Definition: SemaExpr.cpp:1543
clang::CXXScopeSpec::isValid
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
clang::Expr::IgnoreParenImpCasts
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2990
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:263
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:99
clang::Sema::IgnoredValueConversions
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
Definition: SemaExprCXX.cpp:7573
clang::Sema::LookupOverloadedOperatorName
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions)
Definition: SemaLookup.cpp:3067
clang::Sema::VerifyICEDiagnoser::Suppress
bool Suppress
Definition: Sema.h:11092
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:5951
handleFixedPointConversion
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1335
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
clang::BlockPointerType
Pointer to a block type.
Definition: Type.h:2716
clang::ASTContext::ObjCBuiltinBoolTy
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1049
OpenVariant::Open
The standard open() call: int open(const char *path, int oflag, ...);.
clang::Sema::LookupInstanceMethodInGlobalPool
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures...
Definition: Sema.h:4035
EvaluatesAsFalse
static bool EvaluatesAsFalse(Sema &S, Expr *E)
Returns true if the given expression can be evaluated as a constant &#39;false&#39;.
Definition: SemaExpr.cpp:13269
clang::CXXDeleteExpr::getBeginLoc
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2410
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:9465
DiagnoseBadDivideOrRemainderValues
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:9387
clang::Expr::IgnoreImplicit
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2978
clang::Sema::NTCUC_LValueToRValueVolatile
Definition: Sema.h:2284
clang::Type::isUnscopedEnumerationType
bool isUnscopedEnumerationType() const
Definition: Type.cpp:1864
clang::OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
clang::Sema::ActOnUnaryExprOrTypeTraitExpr
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4356
clang::Expr::EvalStatus::HasSideEffects
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:559
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4495
clang::ComplexType
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
clang::TemplateArgumentLoc
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:449
clang::CharacterLiteral::Wide
Definition: Expr.h:1534
clang::ParmVarDecl::getUninstantiatedDefaultArg
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2752
clang::ASTContext::getStringLiteralArrayType
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length...
Definition: ASTContext.cpp:10494
clang::ASTContext::UnknownAnyTy
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
clang::FunctionDecl::setTemplateSpecializationKind
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3806
clang::CompoundStmt::body_empty
bool body_empty() const
Definition: Stmt.h:1359
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:6007
clang::ArraySubscriptExpr
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2462
clang::CXXMethodDecl::getDevirtualizedMethod
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it&#39;s possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2075
clang::Sema::ObjCLiteralKind
ObjCLiteralKind
Definition: Sema.h:3105
OpenCLCheckVectorConditional
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator"...
Definition: SemaExpr.cpp:7406
clang::Type::isIntegerType
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6811
clang::Sema::BuildQualifiedDeclarationNameExpr
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2527
clang::ASTContext::UnsignedLongTy
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
clang::DeclaratorDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1829
clang::ASTContext::areCompatibleVectorTypes
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
Definition: ASTContext.cpp:8109
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:538
clang::Sema::CheckExtVectorCast
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6739
clang::ObjCIvarRefExpr::getLocation
SourceLocation getLocation() const
Definition: ExprObjC.h:589
DiagnoseAdditionInShift
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:13330
clang::ConstantArrayType::getSize
const llvm::APInt & getSize() const
Definition: Type.h:2958
clang::ASTContext::getCharWidth
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2108
clang::QualType::DK_none
Definition: Type.h:1163
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1045
clang::Type::isImageType
bool isImageType() const
Definition: Type.h:6703
clang::Sema::getCurFunctionDecl
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
Definition: Sema.cpp:1304
checkArithmeticBinOpPointerOperands
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:9569
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:6631
clang::DeclRefExpr::Create
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:545
checkThreeWayNarrowingConversion
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:10579
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6500
clang::Type::isObjCQualifiedIdType
bool isObjCQualifiedIdType() const
Definition: Type.h:6639
getUDSuffixLoc
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1689
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:700
clang::ExtVectorType
ExtVectorType - Extended vector type.
Definition: Type.h:3354
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2071
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2750
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1747
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2321
clang::ASTContext::BoundMemberTy
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
clang::Expr::LValueClassification
LValueClassification
Definition: Expr.h:263
clang::Sema::ExprEvalContexts
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1112
checkBlockPointerTypesForAssignment
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:8161
clang::Sema::isInOpenMPDeclareTargetContext
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:9834
clang::Sema::CreateBuiltinUnaryOp
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:13578
CheckIncrementDecrementOperand
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn&#39;t need to call Usual...
Definition: SemaExpr.cpp:12234
clang::ASTContext::getConstantArrayType
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
Definition: ASTContext.cpp:3325
clang::ObjCObjectPointerType::quals
qual_range quals() const
Definition: Type.h:6074
clang::InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
CheckDeclInExpr
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3005
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
clang::ASTContext::canAssignObjCInterfaces
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Definition: ASTContext.cpp:8307
clang::Sema::ExpressionEvaluationContextRecord::isUnevaluated
bool isUnevaluated() const
Definition: Sema.h:1101
PartialDiagnostic.h
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
clang::LookupResult::getLookupKind
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
clang::ObjCIvarRefExpr::getBase
const Expr * getBase() const
Definition: ExprObjC.h:580
clang::Type::getNullability
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3828
clang::FunctionDecl::getTemplateSpecializationKindForInstantiation
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition: Decl.cpp:3772
clang::QualType::getNonLValueExprType
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2915
clang::Type::isConstantArrayType
bool isConstantArrayType() const
Definition: Type.h:6574
clang::QualType::hasAddressSpace
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:6372
clang::sema::CapturingScopeInfo::CaptureMap
llvm::DenseMap< VarDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:644
clang::APValue
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:115
NCCK_Lambda
Definition: SemaExpr.cpp:11574
clang::Sema::ActOnBuiltinOffsetOf
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:14146
clang::OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:144
tryGCCVectorConvertAndSplat
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:9051
clang::Sema::CheckComparisonCategoryType
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Definition: SemaDeclCXX.cpp:10687
clang::Decl::markUsed
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:413
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
clang::ObjCIvarRefExpr
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:546
clang::Scope::DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:59
clang::InitializedEntity::InitializeStmtExprResult
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
Definition: Initialization.h:290
diagnoseDistinctPointerComparison
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:10158
clang::Sema::InvalidOperands
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:8840
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:6622
clang::Type::isIncompleteType
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
clang::ASTContext::Char8Ty
CanQualType Char8Ty
Definition: ASTContext.h:1022
clang::FunctionDecl::isInlined
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2513
clang::Sema::checkAddressOfFunctionIsAvailable
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function&#39;s address can be taken or not, optionally emitting a diagnostic if...
Definition: SemaOverload.cpp:9994
clang::QualType::withCVRQualifiers
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:846
clang::PredefinedExpr::Func
Definition: Expr.h:1915
clang::Sema::getScopeForContext
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1652
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
clang::Sema::IsDependentFunctionNameExpr
bool IsDependentFunctionNameExpr(Expr *E)
Check whether the given type-dependent expression will be the name of a function or another callable ...
Definition: SemaExpr.cpp:18153
clang::CXXScopeSpec::isSet
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
clang::TypeSourceInfo::getTypeLoc
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
clang::Sema::CheckUnusedVolatileAssignment
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, and if so, remove it from the list of volatile-qualified assignments that we are going to warn are deprecated.
Definition: SemaExpr.cpp:15265
clang::UnaryOperator::isArithmeticOp
bool isArithmeticOp() const
Definition: Expr.h:2127
clang::LookupResult::getNamingClass
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:403
clang::BlockDecl::Create
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4724
clang::Qualifiers::OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:174
clang::Type::isQueueT
bool isQueueT() const
Definition: Type.h:6695
clang::Sema::CreateUnaryExprOrTypeTraitExpr
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4267
clang::TemplateArgument::getKind
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
clang::DeclarationNameTable::getCXXLiteralOperatorName
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
Definition: DeclarationName.cpp:362
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:3966
clang::Sema::DefaultVariadicArgumentPromotion
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:925
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
Definition: ExprConstant.cpp:13770
clang::Expr::NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:722
clang::ASTContext::typesAreCompatible
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Definition: ASTContext.cpp:8753
DoMarkVarDeclReferenced
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E)
Definition: SemaExpr.cpp:16817
clang::ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:116
clang::ASTContext::getTranslationUnitDecl
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
clang::Sema::ActOnGenericSelectionExpr
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr *> ArgExprs)
Definition: SemaExpr.cpp:1517
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2836
clang::Expr::MLV_ConstQualified
Definition: Expr.h:286
clang::UETT_SizeOf
Definition: TypeTraits.h:97
clang::Sema::ExpressionEvaluationContextRecord
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:1042
clang::Sema::CheckBitwiseOperands
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11416
clang::sema::CapturingScopeInfo::addCapture
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:661
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:760
clang::StringLiteral::UTF8
Definition: Expr.h:1733
clang::ExprResult
ActionResult< Expr * > ExprResult
Definition: Ownership.h:263
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6336
clang::sema::PossiblyUnreachableDiag
Definition: ScopeInfo.h:85
handleFloatConversion
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1097
clang::ParmVarDecl::setDefaultArg
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2722
isObjCObjectLiteral
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:10208
clang::Type::hasSignedIntegerRepresentation
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1958
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
clang::Sema::Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:10603
clang::ASTContext::getRValueReferenceType
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
Definition: ASTContext.cpp:3261
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6777
clang::ASTContext::getTypeInfo
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
Definition: ASTContext.cpp:1907
clang::Sema::CUDAFunctionTarget
CUDAFunctionTarget
Definition: Sema.h:11315
clang::sema::Capture::markUsed
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:598
clang::Sema::getCurFunction
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1493
clang::OMPArraySectionExpr::getBaseOriginalType
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4707
clang::ParenExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2014
clang::ChooseExpr
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4130
clang::Expr::hasAnyTypeDependentArguments
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3176
clang::sema::Capture::isNested
bool isNested() const
Definition: ScopeInfo.h:589
clang::Sema::LK_None
Definition: Sema.h:3112
IsArithmeticBinaryExpr
static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:7761
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3808
clang::Type::hasIntegerRepresentation
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:1818
clang::ParenListExpr::getRParenLoc
SourceLocation getRParenLoc() const
Definition: Expr.h:5189
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6283
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:107
clang::Sema::LookupLiteralOperator
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal...
Definition: SemaLookup.cpp:3405
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1959
clang::UETT_VecStep
Definition: TypeTraits.h:101
clang::ASTContext::Char16Ty
CanQualType Char16Ty
Definition: ASTContext.h:1023
clang::BinaryOperator::isMultiplicativeOp
bool isMultiplicativeOp() const
Definition: Expr.h:3509
clang::ASTContext::removeAddrSpaceQualType
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that&#39;s ...
Definition: ASTContext.cpp:2888
clang::Sema::isLaxVectorConversion
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type...
Definition: SemaExpr.cpp:6658
clang::sema::LambdaScopeInfo
Definition: ScopeInfo.h:793
clang::Sema::TryCaptureKind
TryCaptureKind
Definition: Sema.h:4479
clang::Sema::NeedToCaptureVariable
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:16386
clang::Sema::PoppedFunctionScopePtr
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:1486
clang::Sema::CheckCompareOperands
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10758
clang::Sema::CheckMultiplyDivideOperands
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:9400
clang::sema::BlockScopeInfo::TheDecl
BlockDecl * TheDecl
Definition: ScopeInfo.h:718
clang::Sema::AddOverloadCandidate
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=None, OverloadCandidateParamOrder PO={})
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Definition: SemaOverload.cpp:6124
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:582
clang::TemplateArgumentLocInfo
Location information for a TemplateArgument.
Definition: TemplateBase.h:392
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:397
clang::Type::isSamplerT
bool isSamplerT() const
Definition: Type.h:6683
clang::sema::CapturingScopeInfo::isCXXThisCaptured
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:679
clang::Sema::MaybeSuggestAddingStaticToDecl
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:184
clang::Expr::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:223
clang::Expr::isRValue
bool isRValue() const
Definition: Expr.h:259
clang::Qualifiers::isAddressSpaceSupersetOf
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:476
clang::DeclContext::getLookupParent
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1042
clang::StringLiteralParser
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Definition: LiteralSupport.h:205
Expr.h
clang::ASTContext::getPointerType
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Definition: ASTContext.cpp:3102
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
clang::BuiltinType
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
clang::Sema::DiagnoseEmptyLookup
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr *> Args=None, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2036
clang::Sema::getSourceManager
SourceManager & getSourceManager() const
Definition: Sema.h:1329
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:336
clang::UnqualifiedIdKind::IK_TemplateId
A template-id, e.g., f<int>.
clang::CXXDefaultArgExpr::Create
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, DeclContext *UsedContext)
Definition: ExprCXX.h:1229
clang::sema::CapturingScopeInfo
Definition: ScopeInfo.h:628
clang::OMPDeclareMapperDecl
This represents &#39;#pragma omp declare mapper ...&#39; directive.
Definition: DeclOpenMP.h:217
clang::InitializedEntity::setParameterCFAudited
void setParameterCFAudited()
Definition: Initialization.h:524
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:263
clang::OMF_init
Definition: IdentifierTable.h:633
clang::Sema::DiagnoseCommaOperator
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12149
clang::Sema::ExpressionEvaluationContext
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all...
Definition: Sema.h:995
BuildFloatingLiteral
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3453
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
TargetInfo.h
Defines the clang::TargetInfo interface.
clang::Type::isComplexIntegerType
bool isComplexIntegerType() const
Definition: Type.cpp:539
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2546
castKindToImplicitConversionKind
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:10542
clang::Sema::CheckVectorOperands
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:9132
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:160
clang::Expr::MLV_Valid
Definition: Expr.h:279
clang::CUDAKernelCallExpr::Create
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1746
clang::FunctionDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3868
clang::sema::CapturingScopeInfo::HasImplicitReturnType
bool HasImplicitReturnType
Definition: ScopeInfo.h:655
clang::NamedDecl::getName
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:250
clang::Qualifiers::getCVRQualifiers
unsigned getCVRQualifiers() const
Definition: Type.h:276
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:279
clang::NumericLiteralParser
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber...
Definition: LiteralSupport.h:42
clang::Sema::PerformObjectMemberConversion
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member&#39;s actual type.
Definition: SemaExpr.cpp:2780
clang::TypeInfo::Width
uint64_t Width
Definition: ASTContext.h:157
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1025
clang::CR_OpenMP
Definition: CapturedStmt.h:19
clang::NonOdrUseReason
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:160
clang::VectorType::getNumElements
unsigned getNumElements() const
Definition: Type.h:3271
clang::SC_Register
Definition: Specifiers.h:244
clang::ObjCBoolLiteralExpr
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:85
clang::Sema::AssumedTemplateKind
AssumedTemplateKind
Definition: Sema.h:6845
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
clang::TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2150
clang::CallExpr::ADLCallKind
ADLCallKind
Definition: Expr.h:2593
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:5669
clang::MemberExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1746
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:825
clang::ConversionFixItGenerator
The class facilities generation and storage of conversion FixIts.
Definition: SemaFixItUtils.h:32
clang::sema::AnalysisBasedWarnings::Policy
Definition: AnalysisBasedWarnings.h:34
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3476
clang::Sema::BuildVAArgExpr
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:14559
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2259
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6504
clang::BinaryOperator::isBitwiseOp
bool isBitwiseOp() const
Definition: Expr.h:3516
clang::UnaryOperator::isIncrementDecrementOp
bool isIncrementDecrementOp() const
Definition: Expr.h:2120
clang::TypedefType
Definition: Type.h:4240
clang::Sema::ActOnStringLiteral
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e.g.
Definition: SemaExpr.cpp:1733
clang::BinaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2089
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:118
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2383
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
clang::prec::Comma
Definition: OperatorPrecedence.h:28
clang::CPlusPlus14
Definition: LangStandard.h:49
clang::TypeLoc::initializeFullCopy
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:202
clang::Declarator::getContext
DeclaratorContext getContext() const
Definition: DeclSpec.h:1920
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1144
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:134
clang::ActionResult::getAs
T * getAs()
Definition: Ownership.h:171
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:630
clang::Expr::MLV_DuplicateVectorComponents
Definition: Expr.h:282
clang::VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:129
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
clang::Type::isFloatingType
bool isFloatingType() const
Definition: Type.cpp:2005
clang::isUnresolvedExceptionSpec
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
Definition: ExceptionSpecificationType.h:49
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:207
clang::FunctionProtoType::ExtProtoInfo::Variadic
bool Variadic
Definition: Type.h:3839
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:385
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3158
clang::CallExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1531
clang::Sema::IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:10663
clang::Sema::CheckBooleanCondition
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:17400
clang::DeclarationName::CXXOperatorName
Definition: DeclarationName.h:209
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:223
clang::UnqualifiedId::setIdentifier
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1049
clang::ASTContext::getObjCObjectPointerType
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Definition: ASTContext.cpp:4973
clang::Builtin::Context::hasCustomTypechecking
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:157
clang::Sema::BuildVectorLiteral
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:6848
clang::DeclRefExpr::getQualifier
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1274
clang::Sema::ExpressionEvaluationContextRecord::VolatileAssignmentLHSs
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:1084
clang::interp::Opcode
Opcode
Definition: Opcode.h:21
clang::ASTContext::BoolTy
CanQualType BoolTy
Definition: ASTContext.h:1017
clang::VariableArrayType
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3039
clang::sema::CapturedRegionScopeInfo::OpenMPCaptureLevel
unsigned short OpenMPCaptureLevel
Definition: ScopeInfo.h:760
clang::Sema::CheckCallReturnType
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression&#39;s return type is complete.
Definition: SemaExpr.cpp:17272
clang::ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5227
clang::Sema::getCurLambda
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1882
clang::Sema::BuildBinOp
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:13462
clang::VarDecl::isInline
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1394
clang::DeclaratorContext::BlockLiteralContext
clang::APValue::getInt
APSInt & getInt()
Definition: APValue.h:380
clang::ObjCIvarDecl::getAccessControl
AccessControl getAccessControl() const
Definition: DeclObjC.h:1998
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:335
clang::ASTContext::DoubleTy
CanQualType DoubleTy
Definition: ASTContext.h:1028
clang::Expr::IgnoreParenNoopCasts
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parenthese and casts which do not change the value (including ptr->int casts of the sam...
Definition: Expr.cpp:3017
clang::LookupResult::getNameLoc
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:606
clang::Expr::MLV_ConstAddrSpace
Definition: Expr.h:288
clang::ASTContext::isObjCNSObjectType
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2084
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:48
clang::Type::isFunctionPointerType
bool isFunctionPointerType() const
Definition: Type.h:6538
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:184
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:524
clang::Sema::DiagnoseSentinelCalls
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr *> Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:372
clang::StandardConversionSequence::setToType
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:332
clang::Sema::CheckEnableIf
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, ArrayRef< Expr *> Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
Definition: SemaOverload.cpp:6513
DiagnoseUnusedOfDecl
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:85
checkOpenCLConditionVector
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:7358
clang::FunctionDecl::getNumParams
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3242
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:631
clang::Qualifiers::removeAddressSpace
void removeAddressSpace()
Definition: Type.h:384
CheckCompleteParameterTypesForMangler
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:15429
clang::BinaryOperator::isComparisonOp
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3524
clang::OpaquePtr< QualType >::getFromOpaquePtr
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
clang::VarDecl::hasInit
bool hasInit() const
Definition: Decl.cpp:2226
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:216
clang::Sema::AssignmentAction
AssignmentAction
Definition: Sema.h:2894
ColonLoc
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:107
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
clang::DeclContext::getInnermostBlockDecl
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1058
clang::TypoCorrection::WillReplaceSpecifier
void WillReplaceSpecifier(bool ForceReplacement)
Definition: TypoCorrection.h:100
captureInBlock
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:15944
clang::sema::Capture::isBlockCapture
bool isBlockCapture() const
Definition: ScopeInfo.h:586
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
An implicit &#39;self&#39; parameter.
clang::Sema::LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:3509
checkObjCPointerIntrospection
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:12800
clang::ConstantArrayType
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2935
IsArithmeticOp
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:7746
clang::Sema::IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types...
Definition: Sema.h:10646
clang::ASTContext::isPromotableBitField
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Definition: ASTContext.cpp:5958
Builtins.h
Defines enum values for all the target-independent builtin functions.
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:977
clang::ObjCIvarRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:592
clang::DeclResult
ActionResult< Decl * > DeclResult
Definition: Ownership.h:269
clang::FunctionType::ExtInfo
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3533
clang::interp::Sub
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:140
isImplicitlyDefinableConstexprFunction
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:15514
clang::Sema::ExpressionEvaluationContext::UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
clang::Expr::NullPointerConstantKind
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Definition: Expr.h:710
clang::Sema::ConditionResult
Definition: Sema.h:10992
clang::AvailabilitySpec
One specifier in an expression.
Definition: Availability.h:30
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2096
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:45
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:429
clang::Type::isIncompleteOrObjectType
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1926
CastType
CastType
Definition: SemaCast.cpp:45
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:171
clang::Sema::ActOnAddrLabel
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:13893
clang::NamedDecl::isExternallyVisible
bool isExternallyVisible() const
Definition: Decl.h:362
clang::UETT_OpenMPRequiredSimdAlign
Definition: TypeTraits.h:102
checkEnumArithmeticConversions
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1374
clang::Sema::CheckAddressOfOperand
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:12405
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6238
clang::IdentifierInfo::isEditorPlaceholder
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
Definition: IdentifierTable.h:383
clang::TemplateIdAnnotation::Template
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Definition: ParsedTemplate.h:170
clang::ObjCMethodDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:368
diagnoseArithmeticOnNullPointer
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:9475
clang::ASTContext::getComplexType
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
Definition: ASTContext.cpp:3074
clang::ASTContext::getIntTypeForBitwidth
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
Definition: ASTContext.cpp:10377
clang::Sema::ActOnBlockError
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:14355
diagnoseUseOfInternalDeclInInlineFunction
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we&#39;re in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:140
clang::Sema::SemaDiagnosticBuilder
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1364
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2986
OriginalExprKind
OriginalExprKind
Definition: SemaExpr.cpp:11752
clang::ASTContext::UnsignedIntTy
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
clang::FunctionDecl::getPointOfInstantiation
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:3833
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:5254
clang::Type::STK_Integral
Definition: Type.h:2138
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1080
RecordModifiableNonNullParam
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:12621
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:797
clang::Sema::getVariadicCallType
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5059
clang::ObjCObjectPointerType::getPointeeType
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5967
clang::StandardConversionSequence
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:256
CheckRealImagOperand
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4373