clang 8.0.0

SemaExpr.cpp
Go to the documentation of this file.
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/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->isDeleted());
102
103 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
104
105 if (Method && Method->isDeleted() && Method->isDefaulted()) {
106 // If the method was explicitly defaulted, point at that declaration.
107 if (!Method->isImplicit())
108 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
109
110 // Try to diagnose why this special member function was implicitly
111 // deleted. This might fail, if that reason no longer applies.
112 CXXSpecialMember CSM = getSpecialMember(Method);
113 if (CSM != CXXInvalid)
114 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
115
116 return;
117 }
118
119 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
120 if (Ctor && Ctor->isInheritingConstructor())
121 return NoteDeletedInheritingConstructor(Ctor);
122
123 Diag(Decl->getLocation(), diag::note_availability_specified_here)
124 << Decl << 1;
125 }
126
127 /// Determine whether a FunctionDecl was ever declared with an
128 /// explicit storage class.
129 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
130 for (auto I : D->redecls()) {
131 if (I->getStorageClass() != SC_None)
132 return true;
133 }
134 return false;
135 }
136
137 /// Check whether we're in an extern inline function and referring to a
138 /// variable or function with internal linkage (C11 6.7.4p3).
139 ///
140 /// This is only a warning because we used to silently accept this code, but
141 /// in many cases it will not behave correctly. This is not enabled in C++ mode
142 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
143 /// and so while there may still be user mistakes, most of the time we can't
144 /// prove that there are errors.
145 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
146 const NamedDecl *D,
147 SourceLocation Loc) {
148 // This is disabled under C++; there are too many ways for this to fire in
149 // contexts where the warning is a false positive, or where it is technically
150 // correct but benign.
151 if (S.getLangOpts().CPlusPlus)
152 return;
153
154 // Check if this is an inlined function or method.
155 FunctionDecl *Current = S.getCurFunctionDecl();
156 if (!Current)
157 return;
158 if (!Current->isInlined())
159 return;
160 if (!Current->isExternallyVisible())
161 return;
162
163 // Check if the decl has internal linkage.
164 if (D->getFormalLinkage() != InternalLinkage)
165 return;
166
167 // Downgrade from ExtWarn to Extension if
168 // (1) the supposedly external inline function is in the main file,
169 // and probably won't be included anywhere else.
170 // (2) the thing we're referencing is a pure function.
171 // (3) the thing we're referencing is another inline function.
172 // This last can give us false negatives, but it's better than warning on
173 // wrappers for simple C library functions.
174 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
175 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
176 if (!DowngradeWarning && UsedFn)
177 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
178
179 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
180 : diag::ext_internal_in_extern_inline)
181 << /*IsVar=*/!UsedFn << D;
182
183 S.MaybeSuggestAddingStaticToDecl(Current);
184
185 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
186 << D;
187 }
188
189 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
190 const FunctionDecl *First = Cur->getFirstDecl();
191
192 // Suggest "static" on the function, if possible.
193 if (!hasAnyExplicitStorageClass(First)) {
194 SourceLocation DeclBegin = First->getSourceRange().getBegin();
195 Diag(DeclBegin, diag::note_convert_inline_to_static)
196 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
197 }
198 }
199
200 /// Determine whether the use of this declaration is valid, and
201 /// emit any corresponding diagnostics.
202 ///
203 /// This routine diagnoses various problems with referencing
204 /// declarations that can occur when using a declaration. For example,
205 /// it might warn if a deprecated or unavailable declaration is being
206 /// used, or produce an error (and return true) if a C++0x deleted
207 /// function is being used.
208 ///
209 /// \returns true if there was an error (this declaration cannot be
210 /// referenced), false otherwise.
211 ///
212 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
213 const ObjCInterfaceDecl *UnknownObjCClass,
214 bool ObjCPropertyAccess,
215 bool AvoidPartialAvailabilityChecks,
216 ObjCInterfaceDecl *ClassReceiver) {
217 SourceLocation Loc = Locs.front();
218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
219 // If there were any diagnostics suppressed by template argument deduction,
220 // emit them now.
221 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
222 if (Pos != SuppressedDiagnostics.end()) {
223 for (const PartialDiagnosticAt &Suppressed : Pos->second)
224 Diag(Suppressed.first, Suppressed.second);
225
226 // Clear out the list of suppressed diagnostics, so that we don't emit
227 // them again for this specialization. However, we don't obsolete this
228 // entry from the table, because we want to avoid ever emitting these
229 // diagnostics again.
230 Pos->second.clear();
231 }
232
233 // C++ [basic.start.main]p3:
234 // The function 'main' shall not be used within a program.
235 if (cast<FunctionDecl>(D)->isMain())
236 Diag(Loc, diag::ext_main_used);
237
238 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
239 }
240
241 // See if this is an auto-typed variable whose initializer we are parsing.
242 if (ParsingInitForAutoVars.count(D)) {
243 if (isa<BindingDecl>(D)) {
244 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
245 << D->getDeclName();
246 } else {
247 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
248 << D->getDeclName() << cast<VarDecl>(D)->getType();
249 }
250 return true;
251 }
252
253 // See if this is a deleted function.
254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
255 if (FD->isDeleted()) {
256 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
257 if (Ctor && Ctor->isInheritingConstructor())
258 Diag(Loc, diag::err_deleted_inherited_ctor_use)
259 << Ctor->getParent()
260 << Ctor->getInheritedConstructor().getConstructor()->getParent();
261 else
262 Diag(Loc, diag::err_deleted_function_use);
263 NoteDeletedFunction(FD);
264 return true;
265 }
266
267 // If the function has a deduced return type, and we can't deduce it,
268 // then we can't use it either.
269 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
270 DeduceReturnType(FD, Loc))
271 return true;
272
273 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
274 return true;
275 }
276
277 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
278 // Lambdas are only default-constructible or assignable in C++2a onwards.
279 if (MD->getParent()->isLambda() &&
280 ((isa<CXXConstructorDecl>(MD) &&
281 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
282 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
283 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
284 << !isa<CXXConstructorDecl>(MD);
285 }
286 }
287
288 auto getReferencedObjCProp = [](const NamedDecl *D) ->
289 const ObjCPropertyDecl * {
290 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
291 return MD->findPropertyDecl();
292 return nullptr;
293 };
294 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
295 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
296 return true;
297 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
298 return true;
299 }
300
301 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
302 // Only the variables omp_in and omp_out are allowed in the combiner.
303 // Only the variables omp_priv and omp_orig are allowed in the
304 // initializer-clause.
305 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
306 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
307 isa<VarDecl>(D)) {
308 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
309 << getCurFunction()->HasOMPDeclareReductionCombiner;
310 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
311 return true;
312 }
313
314 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
315 AvoidPartialAvailabilityChecks, ClassReceiver);
316
317 DiagnoseUnusedOfDecl(*this, D, Loc);
318
319 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
320
321 return false;
322 }
323
324 /// Retrieve the message suffix that should be added to a
325 /// diagnostic complaining about the given function being deleted or
326 /// unavailable.
327 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
328 std::string Message;
329 if (FD->getAvailability(&Message))
330 return ": " + Message;
331
332 return std::string();
333 }
334
335 /// DiagnoseSentinelCalls - This routine checks whether a call or
336 /// message-send is to a declaration with the sentinel attribute, and
337 /// if so, it checks that the requirements of the sentinel are
338 /// satisfied.
339 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
340 ArrayRef<Expr *> Args) {
341 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
342 if (!attr)
343 return;
344
345 // The number of formal parameters of the declaration.
346 unsigned numFormalParams;
347
348 // The kind of declaration. This is also an index into a %select in
349 // the diagnostic.
350 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
351
352 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
353 numFormalParams = MD->param_size();
354 calleeType = CT_Method;
355 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
356 numFormalParams = FD->param_size();
357 calleeType = CT_Function;
358 } else if (isa<VarDecl>(D)) {
359 QualType type = cast<ValueDecl>(D)->getType();
360 const FunctionType *fn = nullptr;
361 if (const PointerType *ptr = type->getAs<PointerType>()) {
362 fn = ptr->getPointeeType()->getAs<FunctionType>();
363 if (!fn) return;
364 calleeType = CT_Function;
365 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
366 fn = ptr->getPointeeType()->castAs<FunctionType>();
367 calleeType = CT_Block;
368 } else {
369 return;
370 }
371
372 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
373 numFormalParams = proto->getNumParams();
374 } else {
375 numFormalParams = 0;
376 }
377 } else {
378 return;
379 }
380
381 // "nullPos" is the number of formal parameters at the end which
382 // effectively count as part of the variadic arguments. This is
383 // useful if you would prefer to not have *any* formal parameters,
384 // but the language forces you to have at least one.
385 unsigned nullPos = attr->getNullPos();
386 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
387 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
388
389 // The number of arguments which should follow the sentinel.
390 unsigned numArgsAfterSentinel = attr->getSentinel();
391
392 // If there aren't enough arguments for all the formal parameters,
393 // the sentinel, and the args after the sentinel, complain.
394 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
395 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
396 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
397 return;
398 }
399
400 // Otherwise, find the sentinel expression.
401 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
402 if (!sentinelExpr) return;
403 if (sentinelExpr->isValueDependent()) return;
404 if (Context.isSentinelNullExpr(sentinelExpr)) return;
405
406 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
407 // or 'NULL' if those are actually defined in the context. Only use
408 // 'nil' for ObjC methods, where it's much more likely that the
409 // variadic arguments form a list of object pointers.
410 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
411 std::string NullValue;
412 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
413 NullValue = "nil";
414 else if (getLangOpts().CPlusPlus11)
415 NullValue = "nullptr";
416 else if (PP.isMacroDefined("NULL"))
417 NullValue = "NULL";
418 else
419 NullValue = "(void*) 0";
420
421 if (MissingNilLoc.isInvalid())
422 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
423 else
424 Diag(MissingNilLoc, diag::warn_missing_sentinel)
425 << int(calleeType)
426 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
427 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
428 }
429
430 SourceRange Sema::getExprRange(Expr *E) const {
431 return E ? E->getSourceRange() : SourceRange();
432 }
433
434 //===----------------------------------------------------------------------===//
435 // Standard Promotions and Conversions
436 //===----------------------------------------------------------------------===//
437
438 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
439 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
440 // Handle any placeholder expressions which made it here.
441 if (E->getType()->isPlaceholderType()) {
442 ExprResult result = CheckPlaceholderExpr(E);
443 if (result.isInvalid()) return ExprError();
444 E = result.get();
445 }
446
447 QualType Ty = E->getType();
448 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
449
450 if (Ty->isFunctionType()) {
451 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
452 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
453 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
454 return ExprError();
455
456 E = ImpCastExprToType(E, Context.getPointerType(Ty),
457 CK_FunctionToPointerDecay).get();
458 } else if (Ty->isArrayType()) {
459 // In C90 mode, arrays only promote to pointers if the array expression is
460 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
461 // type 'array of type' is converted to an expression that has type 'pointer
462 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
463 // that has type 'array of type' ...". The relevant change is "an lvalue"
464 // (C90) to "an expression" (C99).
465 //
466 // C++ 4.2p1:
467 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
468 // T" can be converted to an rvalue of type "pointer to T".
469 //
470 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
471 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
472 CK_ArrayToPointerDecay).get();
473 }
474 return E;
475 }
476
477 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
478 // Check to see if we are dereferencing a null pointer. If so,
479 // and if not volatile-qualified, this is undefined behavior that the
480 // optimizer will delete, so warn about it. People sometimes try to use this
481 // to get a deterministic trap and are surprised by clang's behavior. This
482 // only handles the pattern "*null", which is a very syntactic check.
483 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
484 if (UO->getOpcode() == UO_Deref &&
485 UO->getSubExpr()->IgnoreParenCasts()->
486 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
487 !UO->getType().isVolatileQualified()) {
488 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
489 S.PDiag(diag::warn_indirection_through_null)
490 << UO->getSubExpr()->getSourceRange());
491 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
492 S.PDiag(diag::note_indirection_through_null));
493 }
494 }
495
496 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
497 SourceLocation AssignLoc,
498 const Expr* RHS) {
499 const ObjCIvarDecl *IV = OIRE->getDecl();
500 if (!IV)
501 return;
502
503 DeclarationName MemberName = IV->getDeclName();
504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
505 if (!Member || !Member->isStr("isa"))
506 return;
507
508 const Expr *Base = OIRE->getBase();
509 QualType BaseType = Base->getType();
510 if (OIRE->isArrow())
511 BaseType = BaseType->getPointeeType();
512 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
513 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
514 ObjCInterfaceDecl *ClassDeclared = nullptr;
515 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
516 if (!ClassDeclared->getSuperClass()
517 && (*ClassDeclared->ivar_begin()) == IV) {
518 if (RHS) {
519 NamedDecl *ObjectSetClass =
520 S.LookupSingleName(S.TUScope,
521 &S.Context.Idents.get("object_setClass"),
522 SourceLocation(), S.LookupOrdinaryName);
523 if (ObjectSetClass) {
524 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
525 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
526 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
527 "object_setClass(")
528 << FixItHint::CreateReplacement(
529 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
530 << FixItHint::CreateInsertion(RHSLocEnd, ")");
531 }
532 else
533 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
534 } else {
535 NamedDecl *ObjectGetClass =
536 S.LookupSingleName(S.TUScope,
537 &S.Context.Idents.get("object_getClass"),
538 SourceLocation(), S.LookupOrdinaryName);
539 if (ObjectGetClass)
540 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
541 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
542 "object_getClass(")
543 << FixItHint::CreateReplacement(
544 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
545 else
546 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
547 }
548 S.Diag(IV->getLocation(), diag::note_ivar_decl);
549 }
550 }
551 }
552
553 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
554 // Handle any placeholder expressions which made it here.
555 if (E->getType()->isPlaceholderType()) {
556 ExprResult result = CheckPlaceholderExpr(E);
557 if (result.isInvalid()) return ExprError();
558 E = result.get();
559 }
560
561 // C++ [conv.lval]p1:
562 // A glvalue of a non-function, non-array type T can be
563 // converted to a prvalue.
564 if (!E->isGLValue()) return E;
565
566 QualType T = E->getType();
567 assert(!T.isNull() && "r-value conversion on typeless expression?");
568
569 // We don't want to throw lvalue-to-rvalue casts on top of
570 // expressions of certain types in C++.
571 if (getLangOpts().CPlusPlus &&
572 (E->getType() == Context.OverloadTy ||
573 T->isDependentType() ||
574 T->isRecordType()))
575 return E;
576
577 // The C standard is actually really unclear on this point, and
578 // DR106 tells us what the result should be but not why. It's
579 // generally best to say that void types just doesn't undergo
580 // lvalue-to-rvalue at all. Note that expressions of unqualified
581 // 'void' type are never l-values, but qualified void can be.
582 if (T->isVoidType())
583 return E;
584
585 // OpenCL usually rejects direct accesses to values of 'half' type.
586 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
587 T->isHalfType()) {
588 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
589 << 0 << T;
590 return ExprError();
591 }
592
593 CheckForNullPointerDereference(*this, E);
594 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
595 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
596 &Context.Idents.get("object_getClass"),
597 SourceLocation(), LookupOrdinaryName);
598 if (ObjectGetClass)
599 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
600 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
601 << FixItHint::CreateReplacement(
602 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
603 else
604 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
605 }
606 else if (const ObjCIvarRefExpr *OIRE =
607 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
608 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
609
610 // C++ [conv.lval]p1:
611 // [...] If T is a non-class type, the type of the prvalue is the
612 // cv-unqualified version of T. Otherwise, the type of the
613 // rvalue is T.
614 //
615 // C99 6.3.2.1p2:
616 // If the lvalue has qualified type, the value has the unqualified
617 // version of the type of the lvalue; otherwise, the value has the
618 // type of the lvalue.
619 if (T.hasQualifiers())
620 T = T.getUnqualifiedType();
621
622 // Under the MS ABI, lock down the inheritance model now.
623 if (T->isMemberPointerType() &&
624 Context.getTargetInfo().getCXXABI().isMicrosoft())
625 (void)isCompleteType(E->getExprLoc(), T);
626
627 UpdateMarkingForLValueToRValue(E);
628
629 // Loading a __weak object implicitly retains the value, so we need a cleanup to
630 // balance that.
631 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
632 Cleanup.setExprNeedsCleanups(true);
633
634 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
635 nullptr, VK_RValue);
636
637 // C11 6.3.2.1p2:
638 // ... if the lvalue has atomic type, the value has the non-atomic version
639 // of the type of the lvalue ...
640 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
641 T = Atomic->getValueType().getUnqualifiedType();
642 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
643 nullptr, VK_RValue);
644 }
645
646 return Res;
647 }
648
649 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
650 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
651 if (Res.isInvalid())
652 return ExprError();
653 Res = DefaultLvalueConversion(Res.get());
654 if (Res.isInvalid())
655 return ExprError();
656 return Res;
657 }
658
659 /// CallExprUnaryConversions - a special case of an unary conversion
660 /// performed on a function designator of a call expression.
661 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
662 QualType Ty = E->getType();
663 ExprResult Res = E;
664 // Only do implicit cast for a function type, but not for a pointer
665 // to function type.
666 if (Ty->isFunctionType()) {
667 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
668 CK_FunctionToPointerDecay).get();
669 if (Res.isInvalid())
670 return ExprError();
671 }
672 Res = DefaultLvalueConversion(Res.get());
673 if (Res.isInvalid())
674 return ExprError();
675 return Res.get();
676 }
677
678 /// UsualUnaryConversions - Performs various conversions that are common to most
679 /// operators (C99 6.3). The conversions of array and function types are
680 /// sometimes suppressed. For example, the array->pointer conversion doesn't
681 /// apply if the array is an argument to the sizeof or address (&) operators.
682 /// In these instances, this routine should *not* be called.
683 ExprResult Sema::UsualUnaryConversions(Expr *E) {
684 // First, convert to an r-value.
685 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
686 if (Res.isInvalid())
687 return ExprError();
688 E = Res.get();
689
690 QualType Ty = E->getType();
691 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
692
693 // Half FP have to be promoted to float unless it is natively supported
694 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
695 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
696
697 // Try to perform integral promotions if the object has a theoretically
698 // promotable type.
699 if (Ty->isIntegralOrUnscopedEnumerationType()) {
700 // C99 6.3.1.1p2:
701 //
702 // The following may be used in an expression wherever an int or
703 // unsigned int may be used:
704 // - an object or expression with an integer type whose integer
705 // conversion rank is less than or equal to the rank of int
706 // and unsigned int.
707 // - A bit-field of type _Bool, int, signed int, or unsigned int.
708 //
709 // If an int can represent all values of the original type, the
710 // value is converted to an int; otherwise, it is converted to an
711 // unsigned int. These are called the integer promotions. All
712 // other types are unchanged by the integer promotions.
713
714 QualType PTy = Context.isPromotableBitField(E);
715 if (!PTy.isNull()) {
716 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
717 return E;
718 }
719 if (Ty->isPromotableIntegerType()) {
720 QualType PT = Context.getPromotedIntegerType(Ty);
721 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
722 return E;
723 }
724 }
725 return E;
726 }
727
728 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
729 /// do not have a prototype. Arguments that have type float or __fp16
730 /// are promoted to double. All other argument types are converted by
731 /// UsualUnaryConversions().
732 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
733 QualType Ty = E->getType();
734 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
735
736 ExprResult Res = UsualUnaryConversions(E);
737 if (Res.isInvalid())
738 return ExprError();
739 E = Res.get();
740
741 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
742 // promote to double.
743 // Note that default argument promotion applies only to float (and
744 // half/fp16); it does not apply to _Float16.
745 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
746 if (BTy && (BTy->getKind() == BuiltinType::Half ||
747 BTy->getKind() == BuiltinType::Float)) {
748 if (getLangOpts().OpenCL &&
749 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
750 if (BTy->getKind() == BuiltinType::Half) {
751 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
752 }
753 } else {
754 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
755 }
756 }
757
758 // C++ performs lvalue-to-rvalue conversion as a default argument
759 // promotion, even on class types, but note:
760 // C++11 [conv.lval]p2:
761 // When an lvalue-to-rvalue conversion occurs in an unevaluated
762 // operand or a subexpression thereof the value contained in the
763 // referenced object is not accessed. Otherwise, if the glvalue
764 // has a class type, the conversion copy-initializes a temporary
765 // of type T from the glvalue and the result of the conversion
766 // is a prvalue for the temporary.
767 // FIXME: add some way to gate this entire thing for correctness in
768 // potentially potentially evaluated contexts.
769 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
770 ExprResult Temp = PerformCopyInitialization(
771 InitializedEntity::InitializeTemporary(E->getType()),
772 E->getExprLoc(), E);
773 if (Temp.isInvalid())
774 return ExprError();
775 E = Temp.get();
776 }
777
778 return E;
779 }
780
781 /// Determine the degree of POD-ness for an expression.
782 /// Incomplete types are considered POD, since this check can be performed
783 /// when we're in an unevaluated context.
784 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
785 if (Ty->isIncompleteType()) {
786 // C++11 [expr.call]p7:
787 // After these conversions, if the argument does not have arithmetic,
788 // enumeration, pointer, pointer to member, or class type, the program
789 // is ill-formed.
790 //
791 // Since we've already performed array-to-pointer and function-to-pointer
792 // decay, the only such type in C++ is cv void. This also handles
793 // initializer lists as variadic arguments.
794 if (Ty->isVoidType())
795 return VAK_Invalid;
796
797 if (Ty->isObjCObjectType())
798 return VAK_Invalid;
799 return VAK_Valid;
800 }
801
802 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
803 return VAK_Invalid;
804
805 if (Ty.isCXX98PODType(Context))
806 return VAK_Valid;
807
808 // C++11 [expr.call]p7:
809 // Passing a potentially-evaluated argument of class type (Clause 9)
810 // having a non-trivial copy constructor, a non-trivial move constructor,
811 // or a non-trivial destructor, with no corresponding parameter,
812 // is conditionally-supported with implementation-defined semantics.
813 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
814 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
815 if (!Record->hasNonTrivialCopyConstructor() &&
816 !Record->hasNonTrivialMoveConstructor() &&
817 !Record->hasNonTrivialDestructor())
818 return VAK_ValidInCXX11;
819
820 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
821 return VAK_Valid;
822
823 if (Ty->isObjCObjectType())
824 return VAK_Invalid;
825
826 if (getLangOpts().MSVCCompat)
827 return VAK_MSVCUndefined;
828
829 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
830 // permitted to reject them. We should consider doing so.
831 return VAK_Undefined;
832 }
833
834 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
835 // Don't allow one to pass an Objective-C interface to a vararg.
836 const QualType &Ty = E->getType();
837 VarArgKind VAK = isValidVarArgType(Ty);
838
839 // Complain about passing non-POD types through varargs.
840 switch (VAK) {
841 case VAK_ValidInCXX11:
842 DiagRuntimeBehavior(
843 E->getBeginLoc(), nullptr,
844 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
845 LLVM_FALLTHROUGH;
846 case VAK_Valid:
847 if (Ty->isRecordType()) {
848 // This is unlikely to be what the user intended. If the class has a
849 // 'c_str' member function, the user probably meant to call that.
850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
851 PDiag(diag::warn_pass_class_arg_to_vararg)
852 << Ty << CT << hasCStrMethod(E) << ".c_str()");
853 }
854 break;
855
856 case VAK_Undefined:
857 case VAK_MSVCUndefined:
858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
859 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
860 << getLangOpts().CPlusPlus11 << Ty << CT);
861 break;
862
863 case VAK_Invalid:
864 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
865 Diag(E->getBeginLoc(),
866 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
867 << Ty << CT;
868 else if (Ty->isObjCObjectType())
869 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
870 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
871 << Ty << CT);
872 else
873 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
874 << isa<InitListExpr>(E) << Ty << CT;
875 break;
876 }
877 }
878
879 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
880 /// will create a trap if the resulting type is not a POD type.
881 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
882 FunctionDecl *FDecl) {
883 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
884 // Strip the unbridged-cast placeholder expression off, if applicable.
885 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
886 (CT == VariadicMethod ||
887 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
888 E = stripARCUnbridgedCast(E);
889
890 // Otherwise, do normal placeholder checking.
891 } else {
892 ExprResult ExprRes = CheckPlaceholderExpr(E);
893 if (ExprRes.isInvalid())
894 return ExprError();
895 E = ExprRes.get();
896 }
897 }
898
899 ExprResult ExprRes = DefaultArgumentPromotion(E);
900 if (ExprRes.isInvalid())
901 return ExprError();
902 E = ExprRes.get();
903
904 // Diagnostics regarding non-POD argument types are
905 // emitted along with format string checking in Sema::CheckFunctionCall().
906 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
907 // Turn this into a trap.
908 CXXScopeSpec SS;
909 SourceLocation TemplateKWLoc;
910 UnqualifiedId Name;
911 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
912 E->getBeginLoc());
913 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
914 Name, true, false);
915 if (TrapFn.isInvalid())
916 return ExprError();
917
918 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
919 None, E->getEndLoc());
920 if (Call.isInvalid())
921 return ExprError();
922
923 ExprResult Comma =
924 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
925 if (Comma.isInvalid())
926 return ExprError();
927 return Comma.get();
928 }
929
930 if (!getLangOpts().CPlusPlus &&
931 RequireCompleteType(E->getExprLoc(), E->getType(),
932 diag::err_call_incomplete_argument))
933 return ExprError();
934
935 return E;
936 }
937
938 /// Converts an integer to complex float type. Helper function of
939 /// UsualArithmeticConversions()
940 ///
941 /// \return false if the integer expression is an integer type and is
942 /// successfully converted to the complex type.
943 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
944 ExprResult &ComplexExpr,
945 QualType IntTy,
946 QualType ComplexTy,
947 bool SkipCast) {
948 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
949 if (SkipCast) return false;
950 if (IntTy->isIntegerType()) {
951 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
952 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
953 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
954 CK_FloatingRealToComplex);
955 } else {
956 assert(IntTy->isComplexIntegerType());
957 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
958 CK_IntegralComplexToFloatingComplex);
959 }
960 return false;
961 }
962
963 /// Handle arithmetic conversion with complex types. Helper function of
964 /// UsualArithmeticConversions()
965 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
966 ExprResult &RHS, QualType LHSType,
967 QualType RHSType,
968 bool IsCompAssign) {
969 // if we have an integer operand, the result is the complex type.
970 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
971 /*skipCast*/false))
972 return LHSType;
973 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
974 /*skipCast*/IsCompAssign))
975 return RHSType;
976
977 // This handles complex/complex, complex/float, or float/complex.
978 // When both operands are complex, the shorter operand is converted to the
979 // type of the longer, and that is the type of the result. This corresponds
980 // to what is done when combining two real floating-point operands.
981 // The fun begins when size promotion occur across type domains.
982 // From H&S 6.3.4: When one operand is complex and the other is a real
983 // floating-point type, the less precise type is converted, within it's
984 // real or complex domain, to the precision of the other type. For example,
985 // when combining a "long double" with a "double _Complex", the
986 // "double _Complex" is promoted to "long double _Complex".
987
988 // Compute the rank of the two types, regardless of whether they are complex.
989 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
990
991 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
992 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
993 QualType LHSElementType =
994 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
995 QualType RHSElementType =
996 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
997
998 QualType ResultType = S.Context.getComplexType(LHSElementType);
999 if (Order < 0) {
1000 // Promote the precision of the LHS if not an assignment.
1001 ResultType = S.Context.getComplexType(RHSElementType);
1002 if (!IsCompAssign) {
1003 if (LHSComplexType)
1004 LHS =
1005 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1006 else
1007 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1008 }
1009 } else if (Order > 0) {
1010 // Promote the precision of the RHS.
1011 if (RHSComplexType)
1012 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1013 else
1014 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1015 }
1016 return ResultType;
1017 }
1018
1019 /// Handle arithmetic conversion from integer to float. Helper function
1020 /// of UsualArithmeticConversions()
1021 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1022 ExprResult &IntExpr,
1023 QualType FloatTy, QualType IntTy,
1024 bool ConvertFloat, bool ConvertInt) {
1025 if (IntTy->isIntegerType()) {
1026 if (ConvertInt)
1027 // Convert intExpr to the lhs floating point type.
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1029 CK_IntegralToFloating);
1030 return FloatTy;
1031 }
1032
1033 // Convert both sides to the appropriate complex float.
1034 assert(IntTy->isComplexIntegerType());
1035 QualType result = S.Context.getComplexType(FloatTy);
1036
1037 // _Complex int -> _Complex float
1038 if (ConvertInt)
1039 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1040 CK_IntegralComplexToFloatingComplex);
1041
1042 // float -> _Complex float
1043 if (ConvertFloat)
1044 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1045 CK_FloatingRealToComplex);
1046
1047 return result;
1048 }
1049
1050 /// Handle arithmethic conversion with floating point types. Helper
1051 /// function of UsualArithmeticConversions()
1052 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1053 ExprResult &RHS, QualType LHSType,
1054 QualType RHSType, bool IsCompAssign) {
1055 bool LHSFloat = LHSType->isRealFloatingType();
1056 bool RHSFloat = RHSType->isRealFloatingType();
1057
1058 // If we have two real floating types, convert the smaller operand
1059 // to the bigger result.
1060 if (LHSFloat && RHSFloat) {
1061 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1062 if (order > 0) {
1063 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1064 return LHSType;
1065 }
1066
1067 assert(order < 0 && "illegal float comparison");
1068 if (!IsCompAssign)
1069 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1070 return RHSType;
1071 }
1072
1073 if (LHSFloat) {
1074 // Half FP has to be promoted to float unless it is natively supported
1075 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1076 LHSType = S.Context.FloatTy;
1077
1078 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1079 /*convertFloat=*/!IsCompAssign,
1080 /*convertInt=*/ true);
1081 }
1082 assert(RHSFloat);
1083 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1084 /*convertInt=*/ true,
1085 /*convertFloat=*/!IsCompAssign);
1086 }
1087
1088 /// Diagnose attempts to convert between __float128 and long double if
1089 /// there is no support for such conversion. Helper function of
1090 /// UsualArithmeticConversions().
1091 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1092 QualType RHSType) {
1093 /* No issue converting if at least one of the types is not a floating point
1094 type or the two types have the same rank.
1095 */
1096 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1097 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1098 return false;
1099
1100 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1101 "The remaining types must be floating point types.");
1102
1103 auto *LHSComplex = LHSType->getAs<ComplexType>();
1104 auto *RHSComplex = RHSType->getAs<ComplexType>();
1105
1106 QualType LHSElemType = LHSComplex ?
1107 LHSComplex->getElementType() : LHSType;
1108 QualType RHSElemType = RHSComplex ?
1109 RHSComplex->getElementType() : RHSType;
1110
1111 // No issue if the two types have the same representation
1112 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1113 &S.Context.getFloatTypeSemantics(RHSElemType))
1114 return false;
1115
1116 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1117 RHSElemType == S.Context.LongDoubleTy);
1118 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1119 RHSElemType == S.Context.Float128Ty);
1120
1121 // We've handled the situation where __float128 and long double have the same
1122 // representation. We allow all conversions for all possible long double types
1123 // except PPC's double double.
1124 return Float128AndLongDouble &&
1125 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1126 &llvm::APFloat::PPCDoubleDouble());
1127 }
1128
1129 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1130
1131 namespace {
1132 /// These helper callbacks are placed in an anonymous namespace to
1133 /// permit their use as function template parameters.
1134 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1135 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1136 }
1137
1138 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1139 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1140 CK_IntegralComplexCast);
1141 }
1142 }
1143
1144 /// Handle integer arithmetic conversions. Helper function of
1145 /// UsualArithmeticConversions()
1146 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1147 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1148 ExprResult &RHS, QualType LHSType,
1149 QualType RHSType, bool IsCompAssign) {
1150 // The rules for this case are in C99 6.3.1.8
1151 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1152 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1153 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1154 if (LHSSigned == RHSSigned) {
1155 // Same signedness; use the higher-ranked type
1156 if (order >= 0) {
1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1158 return LHSType;
1159 } else if (!IsCompAssign)
1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1161 return RHSType;
1162 } else if (order != (LHSSigned ? 1 : -1)) {
1163 // The unsigned type has greater than or equal rank to the
1164 // signed type, so use the unsigned type
1165 if (RHSSigned) {
1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1167 return LHSType;
1168 } else if (!IsCompAssign)
1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1170 return RHSType;
1171 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1172 // The two types are different widths; if we are here, that
1173 // means the signed type is larger than the unsigned type, so
1174 // use the signed type.
1175 if (LHSSigned) {
1176 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1177 return LHSType;
1178 } else if (!IsCompAssign)
1179 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1180 return RHSType;
1181 } else {
1182 // The signed type is higher-ranked than the unsigned type,
1183 // but isn't actually any bigger (like unsigned int and long
1184 // on most 32-bit systems). Use the unsigned type corresponding
1185 // to the signed type.
1186 QualType result =
1187 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1188 RHS = (*doRHSCast)(S, RHS.get(), result);
1189 if (!IsCompAssign)
1190 LHS = (*doLHSCast)(S, LHS.get(), result);
1191 return result;
1192 }
1193 }
1194
1195 /// Handle conversions with GCC complex int extension. Helper function
1196 /// of UsualArithmeticConversions()
1197 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1198 ExprResult &RHS, QualType LHSType,
1199 QualType RHSType,
1200 bool IsCompAssign) {
1201 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1202 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1203
1204 if (LHSComplexInt && RHSComplexInt) {
1205 QualType LHSEltType = LHSComplexInt->getElementType();
1206 QualType RHSEltType = RHSComplexInt->getElementType();
1207 QualType ScalarType =
1208 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1209 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1210
1211 return S.Context.getComplexType(ScalarType);
1212 }
1213
1214 if (LHSComplexInt) {
1215 QualType LHSEltType = LHSComplexInt->getElementType();
1216 QualType ScalarType =
1217 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1218 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1219 QualType ComplexType = S.Context.getComplexType(ScalarType);
1220 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1221 CK_IntegralRealToComplex);
1222
1223 return ComplexType;
1224 }
1225
1226 assert(RHSComplexInt);
1227
1228 QualType RHSEltType = RHSComplexInt->getElementType();
1229 QualType ScalarType =
1230 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1231 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1232 QualType ComplexType = S.Context.getComplexType(ScalarType);
1233
1234 if (!IsCompAssign)
1235 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1236 CK_IntegralRealToComplex);
1237 return ComplexType;
1238 }
1239
1240 /// UsualArithmeticConversions - Performs various conversions that are common to
1241 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1242 /// routine returns the first non-arithmetic type found. The client is
1243 /// responsible for emitting appropriate error diagnostics.
1244 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1245 bool IsCompAssign) {
1246 if (!IsCompAssign) {
1247 LHS = UsualUnaryConversions(LHS.get());
1248 if (LHS.isInvalid())
1249 return QualType();
1250 }
1251
1252 RHS = UsualUnaryConversions(RHS.get());
1253 if (RHS.isInvalid())
1254 return QualType();
1255
1256 // For conversion purposes, we ignore any qualifiers.
1257 // For example, "const float" and "float" are equivalent.
1258 QualType LHSType =
1259 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1260 QualType RHSType =
1261 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1262
1263 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1264 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1265 LHSType = AtomicLHS->getValueType();
1266
1267 // If both types are identical, no conversion is needed.
1268 if (LHSType == RHSType)
1269 return LHSType;
1270
1271 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1272 // The caller can deal with this (e.g. pointer + int).
1273 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1274 return QualType();
1275
1276 // Apply unary and bitfield promotions to the LHS's type.
1277 QualType LHSUnpromotedType = LHSType;
1278 if (LHSType->isPromotableIntegerType())
1279 LHSType = Context.getPromotedIntegerType(LHSType);
1280 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1281 if (!LHSBitfieldPromoteTy.isNull())
1282 LHSType = LHSBitfieldPromoteTy;
1283 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1284 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1285
1286 // If both types are identical, no conversion is needed.
1287 if (LHSType == RHSType)
1288 return LHSType;
1289
1290 // At this point, we have two different arithmetic types.
1291
1292 // Diagnose attempts to convert between __float128 and long double where
1293 // such conversions currently can't be handled.
1294 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1295 return QualType();
1296
1297 // Handle complex types first (C99 6.3.1.8p1).
1298 if (LHSType->isComplexType() || RHSType->isComplexType())
1299 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1300 IsCompAssign);
1301
1302 // Now handle "real" floating types (i.e. float, double, long double).
1303 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1304 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1305 IsCompAssign);
1306
1307 // Handle GCC complex int extension.
1308 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1309 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1310 IsCompAssign);
1311
1312 // Finally, we have two differing integer types.
1313 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1314 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1315 }
1316
1317
1318 //===----------------------------------------------------------------------===//
1319 // Semantic Analysis for various Expression Types
1320 //===----------------------------------------------------------------------===//
1321
1322
1323 ExprResult
1324 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1325 SourceLocation DefaultLoc,
1326 SourceLocation RParenLoc,
1327 Expr *ControllingExpr,
1328 ArrayRef<ParsedType> ArgTypes,
1329 ArrayRef<Expr *> ArgExprs) {
1330 unsigned NumAssocs = ArgTypes.size();
1331 assert(NumAssocs == ArgExprs.size());
1332
1333 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1334 for (unsigned i = 0; i < NumAssocs; ++i) {
1335 if (ArgTypes[i])
1336 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1337 else
1338 Types[i] = nullptr;
1339 }
1340
1341 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1342 ControllingExpr,
1343 llvm::makeArrayRef(Types, NumAssocs),
1344 ArgExprs);
1345 delete [] Types;
1346 return ER;
1347 }
1348
1349 ExprResult
1350 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1351 SourceLocation DefaultLoc,
1352 SourceLocation RParenLoc,
1353 Expr *ControllingExpr,
1354 ArrayRef<TypeSourceInfo *> Types,
1355 ArrayRef<Expr *> Exprs) {
1356 unsigned NumAssocs = Types.size();
1357 assert(NumAssocs == Exprs.size());
1358
1359 // Decay and strip qualifiers for the controlling expression type, and handle
1360 // placeholder type replacement. See committee discussion from WG14 DR423.
1361 {
1362 EnterExpressionEvaluationContext Unevaluated(
1363 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1364 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1365 if (R.isInvalid())
1366 return ExprError();
1367 ControllingExpr = R.get();
1368 }
1369
1370 // The controlling expression is an unevaluated operand, so side effects are
1371 // likely unintended.
1372 if (!inTemplateInstantiation() &&
1373 ControllingExpr->HasSideEffects(Context, false))
1374 Diag(ControllingExpr->getExprLoc(),
1375 diag::warn_side_effects_unevaluated_context);
1376
1377 bool TypeErrorFound = false,
1378 IsResultDependent = ControllingExpr->isTypeDependent(),
1379 ContainsUnexpandedParameterPack
1380 = ControllingExpr->containsUnexpandedParameterPack();
1381
1382 for (unsigned i = 0; i < NumAssocs; ++i) {
1383 if (Exprs[i]->containsUnexpandedParameterPack())
1384 ContainsUnexpandedParameterPack = true;
1385
1386 if (Types[i]) {
1387 if (Types[i]->getType()->containsUnexpandedParameterPack())
1388 ContainsUnexpandedParameterPack = true;
1389
1390 if (Types[i]->getType()->isDependentType()) {
1391 IsResultDependent = true;
1392 } else {
1393 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1394 // complete object type other than a variably modified type."
1395 unsigned D = 0;
1396 if (Types[i]->getType()->isIncompleteType())
1397 D = diag::err_assoc_type_incomplete;
1398 else if (!Types[i]->getType()->isObjectType())
1399 D = diag::err_assoc_type_nonobject;
1400 else if (Types[i]->getType()->isVariablyModifiedType())
1401 D = diag::err_assoc_type_variably_modified;
1402
1403 if (D != 0) {
1404 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1405 << Types[i]->getTypeLoc().getSourceRange()
1406 << Types[i]->getType();
1407 TypeErrorFound = true;
1408 }
1409
1410 // C11 6.5.1.1p2 "No two generic associations in the same generic
1411 // selection shall specify compatible types."
1412 for (unsigned j = i+1; j < NumAssocs; ++j)
1413 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1414 Context.typesAreCompatible(Types[i]->getType(),
1415 Types[j]->getType())) {
1416 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1417 diag::err_assoc_compatible_types)
1418 << Types[j]->getTypeLoc().getSourceRange()
1419 << Types[j]->getType()
1420 << Types[i]->getType();
1421 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1422 diag::note_compat_assoc)
1423 << Types[i]->getTypeLoc().getSourceRange()
1424 << Types[i]->getType();
1425 TypeErrorFound = true;
1426 }
1427 }
1428 }
1429 }
1430 if (TypeErrorFound)
1431 return ExprError();
1432
1433 // If we determined that the generic selection is result-dependent, don't
1434 // try to compute the result expression.
1435 if (IsResultDependent)
1436 return new (Context) GenericSelectionExpr(
1437 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1438 ContainsUnexpandedParameterPack);
1439
1440 SmallVector<unsigned, 1> CompatIndices;
1441 unsigned DefaultIndex = -1U;
1442 for (unsigned i = 0; i < NumAssocs; ++i) {
1443 if (!Types[i])
1444 DefaultIndex = i;
1445 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1446 Types[i]->getType()))
1447 CompatIndices.push_back(i);
1448 }
1449
1450 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1451 // type compatible with at most one of the types named in its generic
1452 // association list."
1453 if (CompatIndices.size() > 1) {
1454 // We strip parens here because the controlling expression is typically
1455 // parenthesized in macro definitions.
1456 ControllingExpr = ControllingExpr->IgnoreParens();
1457 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1458 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1459 << (unsigned)CompatIndices.size();
1460 for (unsigned I : CompatIndices) {
1461 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1462 diag::note_compat_assoc)
1463 << Types[I]->getTypeLoc().getSourceRange()
1464 << Types[I]->getType();
1465 }
1466 return ExprError();
1467 }
1468
1469 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1470 // its controlling expression shall have type compatible with exactly one of
1471 // the types named in its generic association list."
1472 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1473 // We strip parens here because the controlling expression is typically
1474 // parenthesized in macro definitions.
1475 ControllingExpr = ControllingExpr->IgnoreParens();
1476 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1477 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1478 return ExprError();
1479 }
1480
1481 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1482 // type name that is compatible with the type of the controlling expression,
1483 // then the result expression of the generic selection is the expression
1484 // in that generic association. Otherwise, the result expression of the
1485 // generic selection is the expression in the default generic association."
1486 unsigned ResultIndex =
1487 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1488
1489 return new (Context) GenericSelectionExpr(
1490 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1491 ContainsUnexpandedParameterPack, ResultIndex);
1492 }
1493
1494 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1495 /// location of the token and the offset of the ud-suffix within it.
1496 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1497 unsigned Offset) {
1498 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1499 S.getLangOpts());
1500 }
1501
1502 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1503 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1504 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1505 IdentifierInfo *UDSuffix,
1506 SourceLocation UDSuffixLoc,
1507 ArrayRef<Expr*> Args,
1508 SourceLocation LitEndLoc) {
1509 assert(Args.size() <= 2 && "too many arguments for literal operator");
1510
1511 QualType ArgTy[2];
1512 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1513 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1514 if (ArgTy[ArgIdx]->isArrayType())
1515 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1516 }
1517
1518 DeclarationName OpName =
1519 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1520 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1521 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1522
1523 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1524 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1525 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1526 /*AllowStringTemplate*/ false,
1527 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1528 return ExprError();
1529
1530 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1531 }
1532
1533 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1534 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1535 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1536 /// multiple tokens. However, the common case is that StringToks points to one
1537 /// string.
1538 ///
1539 ExprResult
1540 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1541 assert(!StringToks.empty() && "Must have at least one string!");
1542
1543 StringLiteralParser Literal(StringToks, PP);
1544 if (Literal.hadError)
1545 return ExprError();
1546
1547 SmallVector<SourceLocation, 4> StringTokLocs;
1548 for (const Token &Tok : StringToks)
1549 StringTokLocs.push_back(Tok.getLocation());
1550
1551 QualType CharTy = Context.CharTy;
1552 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1553 if (Literal.isWide()) {
1554 CharTy = Context.getWideCharType();
1555 Kind = StringLiteral::Wide;
1556 } else if (Literal.isUTF8()) {
1557 if (getLangOpts().Char8)
1558 CharTy = Context.Char8Ty;
1559 Kind = StringLiteral::UTF8;
1560 } else if (Literal.isUTF16()) {
1561 CharTy = Context.Char16Ty;
1562 Kind = StringLiteral::UTF16;
1563 } else if (Literal.isUTF32()) {
1564 CharTy = Context.Char32Ty;
1565 Kind = StringLiteral::UTF32;
1566 } else if (Literal.isPascal()) {
1567 CharTy = Context.UnsignedCharTy;
1568 }
1569
1570 // Warn on initializing an array of char from a u8 string literal; this
1571 // becomes ill-formed in C++2a.
1572 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1573 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1574 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1575
1576 // Create removals for all 'u8' prefixes in the string literal(s). This
1577 // ensures C++2a compatibility (but may change the program behavior when
1578 // built by non-Clang compilers for which the execution character set is
1579 // not always UTF-8).
1580 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1581 SourceLocation RemovalDiagLoc;
1582 for (const Token &Tok : StringToks) {
1583 if (Tok.getKind() == tok::utf8_string_literal) {
1584 if (RemovalDiagLoc.isInvalid())
1585 RemovalDiagLoc = Tok.getLocation();
1586 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1587 Tok.getLocation(),
1588 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1589 getSourceManager(), getLangOpts())));
1590 }
1591 }
1592 Diag(RemovalDiagLoc, RemovalDiag);
1593 }
1594
1595
1596 QualType CharTyConst = CharTy;
1597 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1598 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1599 CharTyConst.addConst();
1600
1601 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1602
1603 // Get an array type for the string, according to C99 6.4.5. This includes
1604 // the nul terminator character as well as the string length for pascal
1605 // strings.
1606 QualType StrTy = Context.getConstantArrayType(
1607 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1608 ArrayType::Normal, 0);
1609
1610 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1611 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1612 Kind, Literal.Pascal, StrTy,
1613 &StringTokLocs[0],
1614 StringTokLocs.size());
1615 if (Literal.getUDSuffix().empty())
1616 return Lit;
1617
1618 // We're building a user-defined literal.
1619 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1620 SourceLocation UDSuffixLoc =
1621 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1622 Literal.getUDSuffixOffset());
1623
1624 // Make sure we're allowed user-defined literals here.
1625 if (!UDLScope)
1626 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1627
1628 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1629 // operator "" X (str, len)
1630 QualType SizeType = Context.getSizeType();
1631
1632 DeclarationName OpName =
1633 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1634 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1635 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1636
1637 QualType ArgTy[] = {
1638 Context.getArrayDecayedType(StrTy), SizeType
1639 };
1640
1641 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1642 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1643 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1644 /*AllowStringTemplate*/ true,
1645 /*DiagnoseMissing*/ true)) {
1646
1647 case LOLR_Cooked: {
1648 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1649 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1650 StringTokLocs[0]);
1651 Expr *Args[] = { Lit, LenArg };
1652
1653 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1654 }
1655
1656 case LOLR_StringTemplate: {
1657 TemplateArgumentListInfo ExplicitArgs;
1658
1659 unsigned CharBits = Context.getIntWidth(CharTy);
1660 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1661 llvm::APSInt Value(CharBits, CharIsUnsigned);
1662
1663 TemplateArgument TypeArg(CharTy);
1664 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1665 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1666
1667 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1668 Value = Lit->getCodeUnit(I);
1669 TemplateArgument Arg(Context, Value, CharTy);
1670 TemplateArgumentLocInfo ArgInfo;
1671 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1672 }
1673 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1674 &ExplicitArgs);
1675 }
1676 case LOLR_Raw:
1677 case LOLR_Template:
1678 case LOLR_ErrorNoDiagnostic:
1679 llvm_unreachable("unexpected literal operator lookup result");
1680 case LOLR_Error:
1681 return ExprError();
1682 }
1683 llvm_unreachable("unexpected literal operator lookup result");
1684 }
1685
1686 ExprResult
1687 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1688 SourceLocation Loc,
1689 const CXXScopeSpec *SS) {
1690 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1691 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1692 }
1693
1694 /// BuildDeclRefExpr - Build an expression that references a
1695 /// declaration that does not require a closure capture.
1696 ExprResult
1697 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1698 const DeclarationNameInfo &NameInfo,
1699 const CXXScopeSpec *SS, NamedDecl *FoundD,
1700 const TemplateArgumentListInfo *TemplateArgs) {
1701 bool RefersToCapturedVariable =
1702 isa<VarDecl>(D) &&
1703 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1704
1705 DeclRefExpr *E;
1706 if (isa<VarTemplateSpecializationDecl>(D)) {
1707 VarTemplateSpecializationDecl *VarSpec =
1708 cast<VarTemplateSpecializationDecl>(D);
1709
1710 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1711 : NestedNameSpecifierLoc(),
1712 VarSpec->getTemplateKeywordLoc(), D,
1713 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1714 FoundD, TemplateArgs);
1715 } else {
1716 assert(!TemplateArgs && "No template arguments for non-variable"
1717 " template specialization references");
1718 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1719 : NestedNameSpecifierLoc(),
1720 SourceLocation(), D, RefersToCapturedVariable,
1721 NameInfo, Ty, VK, FoundD);
1722 }
1723
1724 MarkDeclRefReferenced(E);
1725
1726 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1727 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1728 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1729 getCurFunction()->recordUseOfWeak(E);
1730
1731 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1732 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1733 FD = IFD->getAnonField();
1734 if (FD) {
1735 UnusedPrivateFields.remove(FD);
1736 // Just in case we're building an illegal pointer-to-member.
1737 if (FD->isBitField())
1738 E->setObjectKind(OK_BitField);
1739 }
1740
1741 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1742 // designates a bit-field.
1743 if (auto *BD = dyn_cast<BindingDecl>(D))
1744 if (auto *BE = BD->getBinding())
1745 E->setObjectKind(BE->getObjectKind());
1746
1747 return E;
1748 }
1749
1750 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1751 /// possibly a list of template arguments.
1752 ///
1753 /// If this produces template arguments, it is permitted to call
1754 /// DecomposeTemplateName.
1755 ///
1756 /// This actually loses a lot of source location information for
1757 /// non-standard name kinds; we should consider preserving that in
1758 /// some way.
1759 void
1760 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1761 TemplateArgumentListInfo &Buffer,
1762 DeclarationNameInfo &NameInfo,
1763 const TemplateArgumentListInfo *&TemplateArgs) {
1764 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1765 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1766 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1767
1768 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1769 Id.TemplateId->NumArgs);
1770 translateTemplateArguments(TemplateArgsPtr, Buffer);
1771
1772 TemplateName TName = Id.TemplateId->Template.get();
1773 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1774 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1775 TemplateArgs = &Buffer;
1776 } else {
1777 NameInfo = GetNameFromUnqualifiedId(Id);
1778 TemplateArgs = nullptr;
1779 }
1780 }
1781
1782 static void emitEmptyLookupTypoDiagnostic(
1783 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1784 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1785 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1786 DeclContext *Ctx =
1787 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1788 if (!TC) {
1789 // Emit a special diagnostic for failed member lookups.
1790 // FIXME: computing the declaration context might fail here (?)
1791 if (Ctx)
1792 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1793 << SS.getRange();
1794 else
1795 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1796 return;
1797 }
1798
1799 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1800 bool DroppedSpecifier =
1801 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1802 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1803 ? diag::note_implicit_param_decl
1804 : diag::note_previous_decl;
1805 if (!Ctx)
1806 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1807 SemaRef.PDiag(NoteID));
1808 else
1809 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1810 << Typo << Ctx << DroppedSpecifier
1811 << SS.getRange(),
1812 SemaRef.PDiag(NoteID));
1813 }
1814
1815 /// Diagnose an empty lookup.
1816 ///
1817 /// \return false if new lookup candidates were found
1818 bool
1819 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1820 std::unique_ptr<CorrectionCandidateCallback> CCC,
1821 TemplateArgumentListInfo *ExplicitTemplateArgs,
1822 ArrayRef<Expr *> Args, TypoExpr **Out) {
1823 DeclarationName Name = R.getLookupName();
1824
1825 unsigned diagnostic = diag::err_undeclared_var_use;
1826 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1827 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1828 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1829 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1830 diagnostic = diag::err_undeclared_use;
1831 diagnostic_suggest = diag::err_undeclared_use_suggest;
1832 }
1833
1834 // If the original lookup was an unqualified lookup, fake an
1835 // unqualified lookup. This is useful when (for example) the
1836 // original lookup would not have found something because it was a
1837 // dependent name.
1838 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1839 while (DC) {
1840 if (isa<CXXRecordDecl>(DC)) {
1841 LookupQualifiedName(R, DC);
1842
1843 if (!R.empty()) {
1844 // Don't give errors about ambiguities in this lookup.
1845 R.suppressDiagnostics();
1846
1847 // During a default argument instantiation the CurContext points
1848 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1849 // function parameter list, hence add an explicit check.
1850 bool isDefaultArgument =
1851 !CodeSynthesisContexts.empty() &&
1852 CodeSynthesisContexts.back().Kind ==
1853 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1854 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1855 bool isInstance = CurMethod &&
1856 CurMethod->isInstance() &&
1857 DC == CurMethod->getParent() && !isDefaultArgument;
1858
1859 // Give a code modification hint to insert 'this->'.
1860 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1861 // Actually quite difficult!
1862 if (getLangOpts().MSVCCompat)
1863 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1864 if (isInstance) {
1865 Diag(R.getNameLoc(), diagnostic) << Name
1866 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1867 CheckCXXThisCapture(R.getNameLoc());
1868 } else {
1869 Diag(R.getNameLoc(), diagnostic) << Name;
1870 }
1871
1872 // Do we really want to note all of these?
1873 for (NamedDecl *D : R)
1874 Diag(D->getLocation(), diag::note_dependent_var_use);
1875
1876 // Return true if we are inside a default argument instantiation
1877 // and the found name refers to an instance member function, otherwise
1878 // the function calling DiagnoseEmptyLookup will try to create an
1879 // implicit member call and this is wrong for default argument.
1880 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1881 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1882 return true;
1883 }
1884
1885 // Tell the callee to try to recover.
1886 return false;
1887 }
1888
1889 R.clear();
1890 }
1891
1892 // In Microsoft mode, if we are performing lookup from within a friend
1893 // function definition declared at class scope then we must set
1894 // DC to the lexical parent to be able to search into the parent
1895 // class.
1896 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1897 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1898 DC->getLexicalParent()->isRecord())
1899 DC = DC->getLexicalParent();
1900 else
1901 DC = DC->getParent();
1902 }
1903
1904 // We didn't find anything, so try to correct for a typo.
1905 TypoCorrection Corrected;
1906 if (S && Out) {
1907 SourceLocation TypoLoc = R.getNameLoc();
1908 assert(!ExplicitTemplateArgs &&
1909 "Diagnosing an empty lookup with explicit template args!");
1910 *Out = CorrectTypoDelayed(
1911 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1912 [=](const TypoCorrection &TC) {
1913 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1914 diagnostic, diagnostic_suggest);
1915 },
1916 nullptr, CTK_ErrorRecovery);
1917 if (*Out)
1918 return true;
1919 } else if (S && (Corrected =
1920 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1921 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1922 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1923 bool DroppedSpecifier =
1924 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1925 R.setLookupName(Corrected.getCorrection());
1926
1927 bool AcceptableWithRecovery = false;
1928 bool AcceptableWithoutRecovery = false;
1929 NamedDecl *ND = Corrected.getFoundDecl();
1930 if (ND) {
1931 if (Corrected.isOverloaded()) {
1932 OverloadCandidateSet OCS(R.getNameLoc(),
1933 OverloadCandidateSet::CSK_Normal);
1934 OverloadCandidateSet::iterator Best;
1935 for (NamedDecl *CD : Corrected) {
1936 if (FunctionTemplateDecl *FTD =
1937 dyn_cast<FunctionTemplateDecl>(CD))
1938 AddTemplateOverloadCandidate(
1939 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1940 Args, OCS);
1941 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1942 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1943 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1944 Args, OCS);
1945 }
1946 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1947 case OR_Success:
1948 ND = Best->FoundDecl;
1949 Corrected.setCorrectionDecl(ND);
1950 break;
1951 default:
1952 // FIXME: Arbitrarily pick the first declaration for the note.
1953 Corrected.setCorrectionDecl(ND);
1954 break;
1955 }
1956 }
1957 R.addDecl(ND);
1958 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1959 CXXRecordDecl *Record = nullptr;
1960 if (Corrected.getCorrectionSpecifier()) {
1961 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1962 Record = Ty->getAsCXXRecordDecl();
1963 }
1964 if (!Record)
1965 Record = cast<CXXRecordDecl>(
1966 ND->getDeclContext()->getRedeclContext());
1967 R.setNamingClass(Record);
1968 }
1969
1970 auto *UnderlyingND = ND->getUnderlyingDecl();
1971 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1972 isa<FunctionTemplateDecl>(UnderlyingND);
1973 // FIXME: If we ended up with a typo for a type name or
1974 // Objective-C class name, we're in trouble because the parser
1975 // is in the wrong place to recover. Suggest the typo
1976 // correction, but don't make it a fix-it since we're not going
1977 // to recover well anyway.
1978 AcceptableWithoutRecovery =
1979 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1980 } else {
1981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1982 // because we aren't able to recover.
1983 AcceptableWithoutRecovery = true;
1984 }
1985
1986 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1987 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1988 ? diag::note_implicit_param_decl
1989 : diag::note_previous_decl;
1990 if (SS.isEmpty())
1991 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1992 PDiag(NoteID), AcceptableWithRecovery);
1993 else
1994 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1995 << Name << computeDeclContext(SS, false)
1996 << DroppedSpecifier << SS.getRange(),
1997 PDiag(NoteID), AcceptableWithRecovery);
1998
1999 // Tell the callee whether to try to recover.
2000 return !AcceptableWithRecovery;
2001 }
2002 }
2003 R.clear();
2004
2005 // Emit a special diagnostic for failed member lookups.
2006 // FIXME: computing the declaration context might fail here (?)
2007 if (!SS.isEmpty()) {
2008 Diag(R.getNameLoc(), diag::err_no_member)
2009 << Name << computeDeclContext(SS, false)
2010 << SS.getRange();
2011 return true;
2012 }
2013
2014 // Give up, we can't recover.
2015 Diag(R.getNameLoc(), diagnostic) << Name;
2016 return true;
2017 }
2018
2019 /// In Microsoft mode, if we are inside a template class whose parent class has
2020 /// dependent base classes, and we can't resolve an unqualified identifier, then
2021 /// assume the identifier is a member of a dependent base class. We can only
2022 /// recover successfully in static methods, instance methods, and other contexts
2023 /// where 'this' is available. This doesn't precisely match MSVC's
2024 /// instantiation model, but it's close enough.
2025 static Expr *
2026 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2027 DeclarationNameInfo &NameInfo,
2028 SourceLocation TemplateKWLoc,
2029 const TemplateArgumentListInfo *TemplateArgs) {
2030 // Only try to recover from lookup into dependent bases in static methods or
2031 // contexts where 'this' is available.
2032 QualType ThisType = S.getCurrentThisType();
2033 const CXXRecordDecl *RD = nullptr;
2034 if (!ThisType.isNull())
2035 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2036 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2037 RD = MD->getParent();
2038 if (!RD || !RD->hasAnyDependentBases())
2039 return nullptr;
2040
2041 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2042 // is available, suggest inserting 'this->' as a fixit.
2043 SourceLocation Loc = NameInfo.getLoc();
2044 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2045 DB << NameInfo.getName() << RD;
2046
2047 if (!ThisType.isNull()) {
2048 DB << FixItHint::CreateInsertion(Loc, "this->");
2049 return CXXDependentScopeMemberExpr::Create(
2050 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2051 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2052 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2053 }
2054
2055 // Synthesize a fake NNS that points to the derived class. This will
2056 // perform name lookup during template instantiation.
2057 CXXScopeSpec SS;
2058 auto *NNS =
2059 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2060 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2061 return DependentScopeDeclRefExpr::Create(
2062 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2063 TemplateArgs);
2064 }
2065
2066 ExprResult
2067 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2068 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2069 bool HasTrailingLParen, bool IsAddressOfOperand,
2070 std::unique_ptr<CorrectionCandidateCallback> CCC,
2071 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2072 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2073 "cannot be direct & operand and have a trailing lparen");
2074 if (SS.isInvalid())
2075 return ExprError();
2076
2077 TemplateArgumentListInfo TemplateArgsBuffer;
2078
2079 // Decompose the UnqualifiedId into the following data.
2080 DeclarationNameInfo NameInfo;
2081 const TemplateArgumentListInfo *TemplateArgs;
2082 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2083
2084 DeclarationName Name = NameInfo.getName();
2085 IdentifierInfo *II = Name.getAsIdentifierInfo();
2086 SourceLocation NameLoc = NameInfo.getLoc();
2087
2088 if (II && II->isEditorPlaceholder()) {
2089 // FIXME: When typed placeholders are supported we can create a typed
2090 // placeholder expression node.
2091 return ExprError();
2092 }
2093
2094 // C++ [temp.dep.expr]p3:
2095 // An id-expression is type-dependent if it contains:
2096 // -- an identifier that was declared with a dependent type,
2097 // (note: handled after lookup)
2098 // -- a template-id that is dependent,
2099 // (note: handled in BuildTemplateIdExpr)
2100 // -- a conversion-function-id that specifies a dependent type,
2101 // -- a nested-name-specifier that contains a class-name that
2102 // names a dependent type.
2103 // Determine whether this is a member of an unknown specialization;
2104 // we need to handle these differently.
2105 bool DependentID = false;
2106 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2107 Name.getCXXNameType()->isDependentType()) {
2108 DependentID = true;
2109 } else if (SS.isSet()) {
2110 if (DeclContext *DC = computeDeclContext(SS, false)) {
2111 if (RequireCompleteDeclContext(SS, DC))
2112 return ExprError();
2113 } else {
2114 DependentID = true;
2115 }
2116 }
2117
2118 if (DependentID)
2119 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2120 IsAddressOfOperand, TemplateArgs);
2121
2122 // Perform the required lookup.
2123 LookupResult R(*this, NameInfo,
2124 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2125 ? LookupObjCImplicitSelfParam
2126 : LookupOrdinaryName);
2127 if (TemplateKWLoc.isValid() || TemplateArgs) {
2128 // Lookup the template name again to correctly establish the context in
2129 // which it was found. This is really unfortunate as we already did the
2130 // lookup to determine that it was a template name in the first place. If
2131 // this becomes a performance hit, we can work harder to preserve those
2132 // results until we get here but it's likely not worth it.
2133 bool MemberOfUnknownSpecialization;
2134 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2135 MemberOfUnknownSpecialization, TemplateKWLoc))
2136 return ExprError();
2137
2138 if (MemberOfUnknownSpecialization ||
2139 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2140 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2141 IsAddressOfOperand, TemplateArgs);
2142 } else {
2143 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2144 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2145
2146 // If the result might be in a dependent base class, this is a dependent
2147 // id-expression.
2148 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2149 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2150 IsAddressOfOperand, TemplateArgs);
2151
2152 // If this reference is in an Objective-C method, then we need to do
2153 // some special Objective-C lookup, too.
2154 if (IvarLookupFollowUp) {
2155 ExprResult E(LookupInObjCMethod(R, S, II, true));
2156 if (E.isInvalid())
2157 return ExprError();
2158
2159 if (Expr *Ex = E.getAs<Expr>())
2160 return Ex;
2161 }
2162 }
2163
2164 if (R.isAmbiguous())
2165 return ExprError();
2166
2167 // This could be an implicitly declared function reference (legal in C90,
2168 // extension in C99, forbidden in C++).
2169 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2170 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2171 if (D) R.addDecl(D);
2172 }
2173
2174 // Determine whether this name might be a candidate for
2175 // argument-dependent lookup.
2176 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2177
2178 if (R.empty() && !ADL) {
2179 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2180 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2181 TemplateKWLoc, TemplateArgs))
2182 return E;
2183 }
2184
2185 // Don't diagnose an empty lookup for inline assembly.
2186 if (IsInlineAsmIdentifier)
2187 return ExprError();
2188
2189 // If this name wasn't predeclared and if this is not a function
2190 // call, diagnose the problem.
2191 TypoExpr *TE = nullptr;
2192 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2193 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2194 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2195 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2196 "Typo correction callback misconfigured");
2197 if (CCC) {
2198 // Make sure the callback knows what the typo being diagnosed is.
2199 CCC->setTypoName(II);
2200 if (SS.isValid())
2201 CCC->setTypoNNS(SS.getScopeRep());
2202 }
2203 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2204 // a template name, but we happen to have always already looked up the name
2205 // before we get here if it must be a template name.
2206 if (DiagnoseEmptyLookup(S, SS, R,
2207 CCC ? std::move(CCC) : std::move(DefaultValidator),
2208 nullptr, None, &TE)) {
2209 if (TE && KeywordReplacement) {
2210 auto &State = getTypoExprState(TE);
2211 auto BestTC = State.Consumer->getNextCorrection();
2212 if (BestTC.isKeyword()) {
2213 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2214 if (State.DiagHandler)
2215 State.DiagHandler(BestTC);
2216 KeywordReplacement->startToken();
2217 KeywordReplacement->setKind(II->getTokenID());
2218 KeywordReplacement->setIdentifierInfo(II);
2219 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2220 // Clean up the state associated with the TypoExpr, since it has
2221 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2222 clearDelayedTypo(TE);
2223 // Signal that a correction to a keyword was performed by returning a
2224 // valid-but-null ExprResult.
2225 return (Expr*)nullptr;
2226 }
2227 State.Consumer->resetCorrectionStream();
2228 }
2229 return TE ? TE : ExprError();
2230 }
2231
2232 assert(!R.empty() &&
2233 "DiagnoseEmptyLookup returned false but added no results");
2234
2235 // If we found an Objective-C instance variable, let
2236 // LookupInObjCMethod build the appropriate expression to
2237 // reference the ivar.
2238 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2239 R.clear();
2240 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2241 // In a hopelessly buggy code, Objective-C instance variable
2242 // lookup fails and no expression will be built to reference it.
2243 if (!E.isInvalid() && !E.get())
2244 return ExprError();
2245 return E;
2246 }
2247 }
2248
2249 // This is guaranteed from this point on.
2250 assert(!R.empty() || ADL);
2251
2252 // Check whether this might be a C++ implicit instance member access.
2253 // C++ [class.mfct.non-static]p3:
2254 // When an id-expression that is not part of a class member access
2255 // syntax and not used to form a pointer to member is used in the
2256 // body of a non-static member function of class X, if name lookup
2257 // resolves the name in the id-expression to a non-static non-type
2258 // member of some class C, the id-expression is transformed into a
2259 // class member access expression using (*this) as the
2260 // postfix-expression to the left of the . operator.
2261 //
2262 // But we don't actually need to do this for '&' operands if R
2263 // resolved to a function or overloaded function set, because the
2264 // expression is ill-formed if it actually works out to be a
2265 // non-static member function:
2266 //
2267 // C++ [expr.ref]p4:
2268 // Otherwise, if E1.E2 refers to a non-static member function. . .
2269 // [t]he expression can be used only as the left-hand operand of a
2270 // member function call.
2271 //
2272 // There are other safeguards against such uses, but it's important
2273 // to get this right here so that we don't end up making a
2274 // spuriously dependent expression if we're inside a dependent
2275 // instance method.
2276 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2277 bool MightBeImplicitMember;
2278 if (!IsAddressOfOperand)
2279 MightBeImplicitMember = true;
2280 else if (!SS.isEmpty())
2281 MightBeImplicitMember = false;
2282 else if (R.isOverloadedResult())
2283 MightBeImplicitMember = false;
2284 else if (R.isUnresolvableResult())
2285 MightBeImplicitMember = true;
2286 else
2287 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2288 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2289 isa<MSPropertyDecl>(R.getFoundDecl());
2290
2291 if (MightBeImplicitMember)
2292 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2293 R, TemplateArgs, S);
2294 }
2295
2296 if (TemplateArgs || TemplateKWLoc.isValid()) {
2297
2298 // In C++1y, if this is a variable template id, then check it
2299 // in BuildTemplateIdExpr().
2300 // The single lookup result must be a variable template declaration.
2301 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2302 Id.TemplateId->Kind == TNK_Var_template) {
2303 assert(R.getAsSingle<VarTemplateDecl>() &&
2304 "There should only be one declaration found.");
2305 }
2306
2307 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2308 }
2309
2310 return BuildDeclarationNameExpr(SS, R, ADL);
2311 }
2312
2313 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2314 /// declaration name, generally during template instantiation.
2315 /// There's a large number of things which don't need to be done along
2316 /// this path.
2317 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2318 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2319 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2320 DeclContext *DC = computeDeclContext(SS, false);
2321 if (!DC)
2322 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2323 NameInfo, /*TemplateArgs=*/nullptr);
2324
2325 if (RequireCompleteDeclContext(SS, DC))
2326 return ExprError();
2327
2328 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2329 LookupQualifiedName(R, DC);
2330
2331 if (R.isAmbiguous())
2332 return ExprError();
2333
2334 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2335 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2336 NameInfo, /*TemplateArgs=*/nullptr);
2337
2338 if (R.empty()) {
2339 Diag(NameInfo.getLoc(), diag::err_no_member)
2340 << NameInfo.getName() << DC << SS.getRange();
2341 return ExprError();
2342 }
2343
2344 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2345 // Diagnose a missing typename if this resolved unambiguously to a type in
2346 // a dependent context. If we can recover with a type, downgrade this to
2347 // a warning in Microsoft compatibility mode.
2348 unsigned DiagID = diag::err_typename_missing;
2349 if (RecoveryTSI && getLangOpts().MSVCCompat)
2350 DiagID = diag::ext_typename_missing;
2351 SourceLocation Loc = SS.getBeginLoc();
2352 auto D = Diag(Loc, DiagID);
2353 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2354 << SourceRange(Loc, NameInfo.getEndLoc());
2355
2356 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2357 // context.
2358 if (!RecoveryTSI)
2359 return ExprError();
2360
2361 // Only issue the fixit if we're prepared to recover.
2362 D << FixItHint::CreateInsertion(Loc, "typename ");
2363
2364 // Recover by pretending this was an elaborated type.
2365 QualType Ty = Context.getTypeDeclType(TD);
2366 TypeLocBuilder TLB;
2367 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2368
2369 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2370 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2371 QTL.setElaboratedKeywordLoc(SourceLocation());
2372 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2373
2374 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2375
2376 return ExprEmpty();
2377 }
2378
2379 // Defend against this resolving to an implicit member access. We usually
2380 // won't get here if this might be a legitimate a class member (we end up in
2381 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2382 // a pointer-to-member or in an unevaluated context in C++11.
2383 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2384 return BuildPossibleImplicitMemberExpr(SS,
2385 /*TemplateKWLoc=*/SourceLocation(),
2386 R, /*TemplateArgs=*/nullptr, S);
2387
2388 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2389 }
2390
2391 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2392 /// detected that we're currently inside an ObjC method. Perform some
2393 /// additional lookup.
2394 ///
2395 /// Ideally, most of this would be done by lookup, but there's
2396 /// actually quite a lot of extra work involved.
2397 ///
2398 /// Returns a null sentinel to indicate trivial success.
2399 ExprResult
2400 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2401 IdentifierInfo *II, bool AllowBuiltinCreation) {
2402 SourceLocation Loc = Lookup.getNameLoc();
2403 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2404
2405 // Check for error condition which is already reported.
2406 if (!CurMethod)
2407 return ExprError();
2408
2409 // There are two cases to handle here. 1) scoped lookup could have failed,
2410 // in which case we should look for an ivar. 2) scoped lookup could have
2411 // found a decl, but that decl is outside the current instance method (i.e.
2412 // a global variable). In these two cases, we do a lookup for an ivar with
2413 // this name, if the lookup sucedes, we replace it our current decl.
2414
2415 // If we're in a class method, we don't normally want to look for
2416 // ivars. But if we don't find anything else, and there's an
2417 // ivar, that's an error.
2418 bool IsClassMethod = CurMethod->isClassMethod();
2419
2420 bool LookForIvars;
2421 if (Lookup.empty())
2422 LookForIvars = true;
2423 else if (IsClassMethod)
2424 LookForIvars = false;
2425 else
2426 LookForIvars = (Lookup.isSingleResult() &&
2427 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2428 ObjCInterfaceDecl *IFace = nullptr;
2429 if (LookForIvars) {
2430 IFace = CurMethod->getClassInterface();
2431 ObjCInterfaceDecl *ClassDeclared;
2432 ObjCIvarDecl *IV = nullptr;
2433 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2434 // Diagnose using an ivar in a class method.
2435 if (IsClassMethod)
2436 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2437 << IV->getDeclName());
2438
2439 // If we're referencing an invalid decl, just return this as a silent
2440 // error node. The error diagnostic was already emitted on the decl.
2441 if (IV->isInvalidDecl())
2442 return ExprError();
2443
2444 // Check if referencing a field with __attribute__((deprecated)).
2445 if (DiagnoseUseOfDecl(IV, Loc))
2446 return ExprError();
2447
2448 // Diagnose the use of an ivar outside of the declaring class.
2449 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2450 !declaresSameEntity(ClassDeclared, IFace) &&
2451 !getLangOpts().DebuggerSupport)
2452 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2453
2454 // FIXME: This should use a new expr for a direct reference, don't
2455 // turn this into Self->ivar, just return a BareIVarExpr or something.
2456 IdentifierInfo &II = Context.Idents.get("self");
2457 UnqualifiedId SelfName;
2458 SelfName.setIdentifier(&II, SourceLocation());
2459 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2460 CXXScopeSpec SelfScopeSpec;
2461 SourceLocation TemplateKWLoc;
2462 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2463 SelfName, false, false);
2464 if (SelfExpr.isInvalid())
2465 return ExprError();
2466
2467 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2468 if (SelfExpr.isInvalid())
2469 return ExprError();
2470
2471 MarkAnyDeclReferenced(Loc, IV, true);
2472
2473 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2474 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2475 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2476 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2477
2478 ObjCIvarRefExpr *Result = new (Context)
2479 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2480 IV->getLocation(), SelfExpr.get(), true, true);
2481
2482 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2483 if (!isUnevaluatedContext() &&
2484 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2485 getCurFunction()->recordUseOfWeak(Result);
2486 }
2487 if (getLangOpts().ObjCAutoRefCount) {
2488 if (CurContext->isClosure())
2489 Diag(Loc, diag::warn_implicitly_retains_self)
2490 << FixItHint::CreateInsertion(Loc, "self->");
2491 }
2492
2493 return Result;
2494 }
2495 } else if (CurMethod->isInstanceMethod()) {
2496 // We should warn if a local variable hides an ivar.
2497 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2498 ObjCInterfaceDecl *ClassDeclared;
2499 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2500 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2501 declaresSameEntity(IFace, ClassDeclared))
2502 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2503 }
2504 }
2505 } else if (Lookup.isSingleResult() &&
2506 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2507 // If accessing a stand-alone ivar in a class method, this is an error.
2508 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2509 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2510 << IV->getDeclName());
2511 }
2512
2513 if (Lookup.empty() && II && AllowBuiltinCreation) {
2514 // FIXME. Consolidate this with similar code in LookupName.
2515 if (unsigned BuiltinID = II->getBuiltinID()) {
2516 if (!(getLangOpts().CPlusPlus &&
2517 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2518 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2519 S, Lookup.isForRedeclaration(),
2520 Lookup.getNameLoc());
2521 if (D) Lookup.addDecl(D);
2522 }
2523 }
2524 }
2525 // Sentinel value saying that we didn't do anything special.
2526 return ExprResult((Expr *)nullptr);
2527 }
2528
2529 /// Cast a base object to a member's actual type.
2530 ///
2531 /// Logically this happens in three phases:
2532 ///
2533 /// * First we cast from the base type to the naming class.
2534 /// The naming class is the class into which we were looking
2535 /// when we found the member; it's the qualifier type if a
2536 /// qualifier was provided, and otherwise it's the base type.
2537 ///
2538 /// * Next we cast from the naming class to the declaring class.
2539 /// If the member we found was brought into a class's scope by
2540 /// a using declaration, this is that class; otherwise it's
2541 /// the class declaring the member.
2542 ///
2543 /// * Finally we cast from the declaring class to the "true"
2544 /// declaring class of the member. This conversion does not
2545 /// obey access control.
2546 ExprResult
2547 Sema::PerformObjectMemberConversion(Expr *From,
2548 NestedNameSpecifier *Qualifier,
2549 NamedDecl *FoundDecl,
2550 NamedDecl *Member) {
2551 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2552 if (!RD)
2553 return From;
2554
2555 QualType DestRecordType;
2556 QualType DestType;
2557 QualType FromRecordType;
2558 QualType FromType = From->getType();
2559 bool PointerConversions = false;
2560 if (isa<FieldDecl>(Member)) {
2561 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2562
2563 if (FromType->getAs<PointerType>()) {
2564 DestType = Context.getPointerType(DestRecordType);
2565 FromRecordType = FromType->getPointeeType();
2566 PointerConversions = true;
2567 } else {
2568 DestType = DestRecordType;
2569 FromRecordType = FromType;
2570 }
2571 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2572 if (Method->isStatic())
2573 return From;
2574
2575 DestType = Method->getThisType();
2576 DestRecordType = DestType->getPointeeType();
2577
2578 if (FromType->getAs<PointerType>()) {
2579 FromRecordType = FromType->getPointeeType();
2580 PointerConversions = true;
2581 } else {
2582 FromRecordType = FromType;
2583 DestType = DestRecordType;
2584 }
2585 } else {
2586 // No conversion necessary.
2587 return From;
2588 }
2589
2590 if (DestType->isDependentType() || FromType->isDependentType())
2591 return From;
2592
2593 // If the unqualified types are the same, no conversion is necessary.
2594 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2595 return From;
2596
2597 SourceRange FromRange = From->getSourceRange();
2598 SourceLocation FromLoc = FromRange.getBegin();
2599
2600 ExprValueKind VK = From->getValueKind();
2601
2602 // C++ [class.member.lookup]p8:
2603 // [...] Ambiguities can often be resolved by qualifying a name with its
2604 // class name.
2605 //
2606 // If the member was a qualified name and the qualified referred to a
2607 // specific base subobject type, we'll cast to that intermediate type
2608 // first and then to the object in which the member is declared. That allows
2609 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2610 //
2611 // class Base { public: int x; };
2612 // class Derived1 : public Base { };
2613 // class Derived2 : public Base { };
2614 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2615 //
2616 // void VeryDerived::f() {
2617 // x = 17; // error: ambiguous base subobjects
2618 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2619 // }
2620 if (Qualifier && Qualifier->getAsType()) {
2621 QualType QType = QualType(Qualifier->getAsType(), 0);
2622 assert(QType->isRecordType() && "lookup done with non-record type");
2623
2624 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2625
2626 // In C++98, the qualifier type doesn't actually have to be a base
2627 // type of the object type, in which case we just ignore it.
2628 // Otherwise build the appropriate casts.
2629 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2630 CXXCastPath BasePath;
2631 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2632 FromLoc, FromRange, &BasePath))
2633 return ExprError();
2634
2635 if (PointerConversions)
2636 QType = Context.getPointerType(QType);
2637 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2638 VK, &BasePath).get();
2639
2640 FromType = QType;
2641 FromRecordType = QRecordType;
2642
2643 // If the qualifier type was the same as the destination type,
2644 // we're done.
2645 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2646 return From;
2647 }
2648 }
2649
2650 bool IgnoreAccess = false;
2651
2652 // If we actually found the member through a using declaration, cast
2653 // down to the using declaration's type.
2654 //
2655 // Pointer equality is fine here because only one declaration of a
2656 // class ever has member declarations.
2657 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2658 assert(isa<UsingShadowDecl>(FoundDecl));
2659 QualType URecordType = Context.getTypeDeclType(
2660 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2661
2662 // We only need to do this if the naming-class to declaring-class
2663 // conversion is non-trivial.
2664 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2665 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2666 CXXCastPath BasePath;
2667 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2668 FromLoc, FromRange, &BasePath))
2669 return ExprError();
2670
2671 QualType UType = URecordType;
2672 if (PointerConversions)
2673 UType = Context.getPointerType(UType);
2674 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2675 VK, &BasePath).get();
2676 FromType = UType;
2677 FromRecordType = URecordType;
2678 }
2679
2680 // We don't do access control for the conversion from the
2681 // declaring class to the true declaring class.
2682 IgnoreAccess = true;
2683 }
2684
2685 CXXCastPath BasePath;
2686 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2687 FromLoc, FromRange, &BasePath,
2688 IgnoreAccess))
2689 return ExprError();
2690
2691 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2692 VK, &BasePath);
2693 }
2694
2695 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2696 const LookupResult &R,
2697 bool HasTrailingLParen) {
2698 // Only when used directly as the postfix-expression of a call.
2699 if (!HasTrailingLParen)
2700 return false;
2701
2702 // Never if a scope specifier was provided.
2703 if (SS.isSet())
2704 return false;
2705
2706 // Only in C++ or ObjC++.
2707 if (!getLangOpts().CPlusPlus)
2708 return false;
2709
2710 // Turn off ADL when we find certain kinds of declarations during
2711 // normal lookup:
2712 for (NamedDecl *D : R) {
2713 // C++0x [basic.lookup.argdep]p3:
2714 // -- a declaration of a class member
2715 // Since using decls preserve this property, we check this on the
2716 // original decl.
2717 if (D->isCXXClassMember())
2718 return false;
2719
2720 // C++0x [basic.lookup.argdep]p3:
2721 // -- a block-scope function declaration that is not a
2722 // using-declaration
2723 // NOTE: we also trigger this for function templates (in fact, we
2724 // don't check the decl type at all, since all other decl types
2725 // turn off ADL anyway).
2726 if (isa<UsingShadowDecl>(D))
2727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2728 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2729 return false;
2730
2731 // C++0x [basic.lookup.argdep]p3:
2732 // -- a declaration that is neither a function or a function
2733 // template
2734 // And also for builtin functions.
2735 if (isa<FunctionDecl>(D)) {
2736 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2737
2738 // But also builtin functions.
2739 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2740 return false;
2741 } else if (!isa<FunctionTemplateDecl>(D))
2742 return false;
2743 }
2744
2745 return true;
2746 }
2747
2748
2749 /// Diagnoses obvious problems with the use of the given declaration
2750 /// as an expression. This is only actually called for lookups that
2751 /// were not overloaded, and it doesn't promise that the declaration
2752 /// will in fact be used.
2753 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2754 if (D->isInvalidDecl())
2755 return true;
2756
2757 if (isa<TypedefNameDecl>(D)) {
2758 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2759 return true;
2760 }
2761
2762 if (isa<ObjCInterfaceDecl>(D)) {
2763 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2764 return true;
2765 }
2766
2767 if (isa<NamespaceDecl>(D)) {
2768 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2769 return true;
2770 }
2771
2772 return false;
2773 }
2774
2775 // Certain multiversion types should be treated as overloaded even when there is
2776 // only one result.
2777 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2778 assert(R.isSingleResult() && "Expected only a single result");
2779 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2780 return FD &&
2781 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2782 }
2783
2784 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2785 LookupResult &R, bool NeedsADL,
2786 bool AcceptInvalidDecl) {
2787 // If this is a single, fully-resolved result and we don't need ADL,
2788 // just build an ordinary singleton decl ref.
2789 if (!NeedsADL && R.isSingleResult() &&
2790 !R.getAsSingle<FunctionTemplateDecl>() &&
2791 !ShouldLookupResultBeMultiVersionOverload(R))
2792 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2793 R.getRepresentativeDecl(), nullptr,
2794 AcceptInvalidDecl);
2795
2796 // We only need to check the declaration if there's exactly one
2797 // result, because in the overloaded case the results can only be
2798 // functions and function templates.
2799 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2800 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2801 return ExprError();
2802
2803 // Otherwise, just build an unresolved lookup expression. Suppress
2804 // any lookup-related diagnostics; we'll hash these out later, when
2805 // we've picked a target.
2806 R.suppressDiagnostics();
2807
2808 UnresolvedLookupExpr *ULE
2809 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2810 SS.getWithLocInContext(Context),
2811 R.getLookupNameInfo(),
2812 NeedsADL, R.isOverloadedResult(),
2813 R.begin(), R.end());
2814
2815 return ULE;
2816 }
2817
2818 static void
2819 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2820 ValueDecl *var, DeclContext *DC);
2821
2822 /// Complete semantic analysis for a reference to the given declaration.
2823 ExprResult Sema::BuildDeclarationNameExpr(
2824 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2825 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2826 bool AcceptInvalidDecl) {
2827 assert(D && "Cannot refer to a NULL declaration");
2828 assert(!isa<FunctionTemplateDecl>(D) &&
2829 "Cannot refer unambiguously to a function template");
2830
2831 SourceLocation Loc = NameInfo.getLoc();
2832 if (CheckDeclInExpr(*this, Loc, D))
2833 return ExprError();
2834
2835 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2836 // Specifically diagnose references to class templates that are missing
2837 // a template argument list.
2838 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2839 return ExprError();
2840 }
2841
2842 // Make sure that we're referring to a value.
2843 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2844 if (!VD) {
2845 Diag(Loc, diag::err_ref_non_value)
2846 << D << SS.getRange();
2847 Diag(D->getLocation(), diag::note_declared_at);
2848 return ExprError();
2849 }
2850
2851 // Check whether this declaration can be used. Note that we suppress
2852 // this check when we're going to perform argument-dependent lookup
2853 // on this function name, because this might not be the function
2854 // that overload resolution actually selects.
2855 if (DiagnoseUseOfDecl(VD, Loc))
2856 return ExprError();
2857
2858 // Only create DeclRefExpr's for valid Decl's.
2859 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2860 return ExprError();
2861
2862 // Handle members of anonymous structs and unions. If we got here,
2863 // and the reference is to a class member indirect field, then this
2864 // must be the subject of a pointer-to-member expression.
2865 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2866 if (!indirectField->isCXXClassMember())
2867 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2868 indirectField);
2869
2870 {
2871 QualType type = VD->getType();
2872 if (type.isNull())
2873 return ExprError();
2874 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2875 // C++ [except.spec]p17:
2876 // An exception-specification is considered to be needed when:
2877 // - in an expression, the function is the unique lookup result or
2878 // the selected member of a set of overloaded functions.
2879 ResolveExceptionSpec(Loc, FPT);
2880 type = VD->getType();
2881 }
2882 ExprValueKind valueKind = VK_RValue;
2883
2884 switch (D->getKind()) {
2885 // Ignore all the non-ValueDecl kinds.
2886 #define ABSTRACT_DECL(kind)
2887 #define VALUE(type, base)
2888 #define DECL(type, base) \
2889 case Decl::type:
2890 #include "clang/AST/DeclNodes.inc"
2891 llvm_unreachable("invalid value decl kind");
2892
2893 // These shouldn't make it here.
2894 case Decl::ObjCAtDefsField:
2895 case Decl::ObjCIvar:
2896 llvm_unreachable("forming non-member reference to ivar?");
2897
2898 // Enum constants are always r-values and never references.
2899 // Unresolved using declarations are dependent.
2900 case Decl::EnumConstant:
2901 case Decl::UnresolvedUsingValue:
2902 case Decl::OMPDeclareReduction:
2903 valueKind = VK_RValue;
2904 break;
2905
2906 // Fields and indirect fields that got here must be for
2907 // pointer-to-member expressions; we just call them l-values for
2908 // internal consistency, because this subexpression doesn't really
2909 // exist in the high-level semantics.
2910 case Decl::Field:
2911 case Decl::IndirectField:
2912 assert(getLangOpts().CPlusPlus &&
2913 "building reference to field in C?");
2914
2915 // These can't have reference type in well-formed programs, but
2916 // for internal consistency we do this anyway.
2917 type = type.getNonReferenceType();
2918 valueKind = VK_LValue;
2919 break;
2920
2921 // Non-type template parameters are either l-values or r-values
2922 // depending on the type.
2923 case Decl::NonTypeTemplateParm: {
2924 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2925 type = reftype->getPointeeType();
2926 valueKind = VK_LValue; // even if the parameter is an r-value reference
2927 break;
2928 }
2929
2930 // For non-references, we need to strip qualifiers just in case
2931 // the template parameter was declared as 'const int' or whatever.
2932 valueKind = VK_RValue;
2933 type = type.getUnqualifiedType();
2934 break;
2935 }
2936
2937 case Decl::Var:
2938 case Decl::VarTemplateSpecialization:
2939 case Decl::VarTemplatePartialSpecialization:
2940 case Decl::Decomposition:
2941 case Decl::OMPCapturedExpr:
2942 // In C, "extern void blah;" is valid and is an r-value.
2943 if (!getLangOpts().CPlusPlus &&
2944 !type.hasQualifiers() &&
2945 type->isVoidType()) {
2946 valueKind = VK_RValue;
2947 break;
2948 }
2949 LLVM_FALLTHROUGH;
2950
2951 case Decl::ImplicitParam:
2952 case Decl::ParmVar: {
2953 // These are always l-values.
2954 valueKind = VK_LValue;
2955 type = type.getNonReferenceType();
2956
2957 // FIXME: Does the addition of const really only apply in
2958 // potentially-evaluated contexts? Since the variable isn't actually
2959 // captured in an unevaluated context, it seems that the answer is no.
2960 if (!isUnevaluatedContext()) {
2961 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2962 if (!CapturedType.isNull())
2963 type = CapturedType;
2964 }
2965
2966 break;
2967 }
2968
2969 case Decl::Binding: {
2970 // These are always lvalues.
2971 valueKind = VK_LValue;
2972 type = type.getNonReferenceType();
2973 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2974 // decides how that's supposed to work.
2975 auto *BD = cast<BindingDecl>(VD);
2976 if (BD->getDeclContext()->isFunctionOrMethod() &&
2977 BD->getDeclContext() != CurContext)
2978 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2979 break;
2980 }
2981
2982 case Decl::Function: {
2983 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2984 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2985 type = Context.BuiltinFnTy;
2986 valueKind = VK_RValue;
2987 break;
2988 }
2989 }
2990
2991 const FunctionType *fty = type->castAs<FunctionType>();
2992
2993 // If we're referring to a function with an __unknown_anytype
2994 // result type, make the entire expression __unknown_anytype.
2995 if (fty->getReturnType() == Context.UnknownAnyTy) {
2996 type = Context.UnknownAnyTy;
2997 valueKind = VK_RValue;
2998 break;
2999 }
3000
3001 // Functions are l-values in C++.
3002 if (getLangOpts().CPlusPlus) {
3003 valueKind = VK_LValue;
3004 break;
3005 }
3006
3007 // C99 DR 316 says that, if a function type comes from a
3008 // function definition (without a prototype), that type is only
3009 // used for checking compatibility. Therefore, when referencing
3010 // the function, we pretend that we don't have the full function
3011 // type.
3012 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3013 isa<FunctionProtoType>(fty))
3014 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3015 fty->getExtInfo());
3016
3017 // Functions are r-values in C.
3018 valueKind = VK_RValue;
3019 break;
3020 }
3021
3022 case Decl::CXXDeductionGuide:
3023 llvm_unreachable("building reference to deduction guide");
3024
3025 case Decl::MSProperty:
3026 valueKind = VK_LValue;
3027 break;
3028
3029 case Decl::CXXMethod:
3030 // If we're referring to a method with an __unknown_anytype
3031 // result type, make the entire expression __unknown_anytype.
3032 // This should only be possible with a type written directly.
3033 if (const FunctionProtoType *proto
3034 = dyn_cast<FunctionProtoType>(VD->getType()))
3035 if (proto->getReturnType() == Context.UnknownAnyTy) {
3036 type = Context.UnknownAnyTy;
3037 valueKind = VK_RValue;
3038 break;
3039 }
3040
3041 // C++ methods are l-values if static, r-values if non-static.
3042 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3043 valueKind = VK_LValue;
3044 break;
3045 }
3046 LLVM_FALLTHROUGH;
3047
3048 case Decl::CXXConversion:
3049 case Decl::CXXDestructor:
3050 case Decl::CXXConstructor:
3051 valueKind = VK_RValue;
3052 break;
3053 }
3054
3055 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3056 TemplateArgs);
3057 }
3058 }
3059
3060 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3061 SmallString<32> &Target) {
3062 Target.resize(CharByteWidth * (Source.size() + 1));
3063 char *ResultPtr = &Target[0];
3064 const llvm::UTF8 *ErrorPtr;
3065 bool success =
3066 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3067 (void)success;
3068 assert(success);
3069 Target.resize(ResultPtr - &Target[0]);
3070 }
3071
3072 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3073 PredefinedExpr::IdentKind IK) {
3074 // Pick the current block, lambda, captured statement or function.
3075 Decl *currentDecl = nullptr;
3076 if (const BlockScopeInfo *BSI = getCurBlock())
3077 currentDecl = BSI->TheDecl;
3078 else if (const LambdaScopeInfo *LSI = getCurLambda())
3079 currentDecl = LSI->CallOperator;
3080 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3081 currentDecl = CSI->TheCapturedDecl;
3082 else
3083 currentDecl = getCurFunctionOrMethodDecl();
3084
3085 if (!currentDecl) {
3086 Diag(Loc, diag::ext_predef_outside_function);
3087 currentDecl = Context.getTranslationUnitDecl();
3088 }
3089
3090 QualType ResTy;
3091 StringLiteral *SL = nullptr;
3092 if (cast<DeclContext>(currentDecl)->isDependentContext())
3093 ResTy = Context.DependentTy;
3094 else {
3095 // Pre-defined identifiers are of type char[x], where x is the length of
3096 // the string.
3097 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3098 unsigned Length = Str.length();
3099
3100 llvm::APInt LengthI(32, Length + 1);
3101 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3102 ResTy =
3103 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3104 SmallString<32> RawChars;
3105 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3106 Str, RawChars);
3107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3108 /*IndexTypeQuals*/ 0);
3109 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3110 /*Pascal*/ false, ResTy, Loc);
3111 } else {
3112 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3114 /*IndexTypeQuals*/ 0);
3115 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3116 /*Pascal*/ false, ResTy, Loc);
3117 }
3118 }
3119
3120 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3121 }
3122
3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3124 PredefinedExpr::IdentKind IK;
3125
3126 switch (Kind) {
3127 default: llvm_unreachable("Unknown simple primary expr!");
3128 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3129 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3130 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3131 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3132 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3133 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3134 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3135 }
3136
3137 return BuildPredefinedExpr(Loc, IK);
3138 }
3139
3140 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3141 SmallString<16> CharBuffer;
3142 bool Invalid = false;
3143 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3144 if (Invalid)
3145 return ExprError();
3146
3147 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3148 PP, Tok.getKind());
3149 if (Literal.hadError())
3150 return ExprError();
3151
3152 QualType Ty;
3153 if (Literal.isWide())
3154 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3155 else if (Literal.isUTF8() && getLangOpts().Char8)
3156 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3157 else if (Literal.isUTF16())
3158 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3159 else if (Literal.isUTF32())
3160 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3161 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3162 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3163 else
3164 Ty = Context.CharTy; // 'x' -> char in C++
3165
3166 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3167 if (Literal.isWide())
3168 Kind = CharacterLiteral::Wide;
3169 else if (Literal.isUTF16())
3170 Kind = CharacterLiteral::UTF16;
3171 else if (Literal.isUTF32())
3172 Kind = CharacterLiteral::UTF32;
3173 else if (Literal.isUTF8())
3174 Kind = CharacterLiteral::UTF8;
3175
3176 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3177 Tok.getLocation());
3178
3179 if (Literal.getUDSuffix().empty())
3180 return Lit;
3181
3182 // We're building a user-defined literal.
3183 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3184 SourceLocation UDSuffixLoc =
3185 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3186
3187 // Make sure we're allowed user-defined literals here.
3188 if (!UDLScope)
3189 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3190
3191 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3192 // operator "" X (ch)
3193 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3194 Lit, Tok.getLocation());
3195 }
3196
3197 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3198 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3199 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3200 Context.IntTy, Loc);
3201 }
3202
3203 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3204 QualType Ty, SourceLocation Loc) {
3205 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3206
3207 using llvm::APFloat;
3208 APFloat Val(Format);
3209
3210 APFloat::opStatus result = Literal.GetFloatValue(Val);
3211
3212 // Overflow is always an error, but underflow is only an error if
3213 // we underflowed to zero (APFloat reports denormals as underflow).
3214 if ((result & APFloat::opOverflow) ||
3215 ((result & APFloat::opUnderflow) && Val.isZero())) {
3216 unsigned diagnostic;
3217 SmallString<20> buffer;
3218 if (result & APFloat::opOverflow) {
3219 diagnostic = diag::warn_float_overflow;
3220 APFloat::getLargest(Format).toString(buffer);
3221 } else {
3222 diagnostic = diag::warn_float_underflow;
3223 APFloat::getSmallest(Format).toString(buffer);
3224 }
3225
3226 S.Diag(Loc, diagnostic)
3227 << Ty
3228 << StringRef(buffer.data(), buffer.size());
3229 }
3230
3231 bool isExact = (result == APFloat::opOK);
3232 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3233 }
3234
3235 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3236 assert(E && "Invalid expression");
3237
3238 if (E->isValueDependent())
3239 return false;
3240
3241 QualType QT = E->getType();
3242 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3243 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3244 return true;
3245 }
3246
3247 llvm::APSInt ValueAPS;
3248 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3249
3250 if (R.isInvalid())
3251 return true;
3252
3253 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3254 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3255 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3256 << ValueAPS.toString(10) << ValueIsPositive;
3257 return true;
3258 }
3259
3260 return false;
3261 }
3262
3263 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3264 // Fast path for a single digit (which is quite common). A single digit
3265 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3266 if (Tok.getLength() == 1) {
3267 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3268 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3269 }
3270
3271 SmallString<128> SpellingBuffer;
3272 // NumericLiteralParser wants to overread by one character. Add padding to
3273 // the buffer in case the token is copied to the buffer. If getSpelling()
3274 // returns a StringRef to the memory buffer, it should have a null char at
3275 // the EOF, so it is also safe.
3276 SpellingBuffer.resize(Tok.getLength() + 1);
3277
3278 // Get the spelling of the token, which eliminates trigraphs, etc.
3279 bool Invalid = false;
3280 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3281 if (Invalid)
3282 return ExprError();
3283
3284 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3285 if (Literal.hadError)
3286 return ExprError();
3287
3288 if (Literal.hasUDSuffix()) {
3289 // We're building a user-defined literal.
3290 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3291 SourceLocation UDSuffixLoc =
3292 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3293
3294 // Make sure we're allowed user-defined literals here.
3295 if (!UDLScope)
3296 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3297
3298 QualType CookedTy;
3299 if (Literal.isFloatingLiteral()) {
3300 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3301 // long double, the literal is treated as a call of the form
3302 // operator "" X (f L)
3303 CookedTy = Context.LongDoubleTy;
3304 } else {
3305 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3306 // unsigned long long, the literal is treated as a call of the form
3307 // operator "" X (n ULL)
3308 CookedTy = Context.UnsignedLongLongTy;
3309 }
3310
3311 DeclarationName OpName =
3312 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3313 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3314 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3315
3316 SourceLocation TokLoc = Tok.getLocation();
3317
3318 // Perform literal operator lookup to determine if we're building a raw
3319 // literal or a cooked one.
3320 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3321 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3322 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3323 /*AllowStringTemplate*/ false,
3324 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3325 case LOLR_ErrorNoDiagnostic:
3326 // Lookup failure for imaginary constants isn't fatal, there's still the
3327 // GNU extension producing _Complex types.
3328 break;
3329 case LOLR_Error:
3330 return ExprError();
3331 case LOLR_Cooked: {
3332 Expr *Lit;
3333 if (Literal.isFloatingLiteral()) {
3334 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3335 } else {
3336 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3337 if (Literal.GetIntegerValue(ResultVal))
3338 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3339 << /* Unsigned */ 1;
3340 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3341 Tok.getLocation());
3342 }
3343 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3344 }
3345
3346 case LOLR_Raw: {
3347 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3348 // literal is treated as a call of the form
3349 // operator "" X ("n")
3350 unsigned Length = Literal.getUDSuffixOffset();
3351 QualType StrTy = Context.getConstantArrayType(
3352 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3353 llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3354 Expr *Lit = StringLiteral::Create(
3355 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3356 /*Pascal*/false, StrTy, &TokLoc, 1);
3357 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3358 }
3359
3360 case LOLR_Template: {
3361 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3362 // template), L is treated as a call fo the form
3363 // operator "" X <'c1', 'c2', ... 'ck'>()
3364 // where n is the source character sequence c1 c2 ... ck.
3365 TemplateArgumentListInfo ExplicitArgs;
3366 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3367 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3368 llvm::APSInt Value(CharBits, CharIsUnsigned);
3369 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3370 Value = TokSpelling[I];
3371 TemplateArgument Arg(Context, Value, Context.CharTy);
3372 TemplateArgumentLocInfo ArgInfo;
3373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3374 }
3375 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3376 &ExplicitArgs);
3377 }
3378 case LOLR_StringTemplate:
3379 llvm_unreachable("unexpected literal operator lookup result");
3380 }
3381 }
3382
3383 Expr *Res;
3384
3385 if (Literal.isFixedPointLiteral()) {
3386 QualType Ty;
3387
3388 if (Literal.isAccum) {
3389 if (Literal.isHalf) {
3390 Ty = Context.ShortAccumTy;
3391 } else if (Literal.isLong) {
3392 Ty = Context.LongAccumTy;
3393 } else {
3394 Ty = Context.AccumTy;
3395 }
3396 } else if (Literal.isFract) {
3397 if (Literal.isHalf) {
3398 Ty = Context.ShortFractTy;
3399 } else if (Literal.isLong) {
3400 Ty = Context.LongFractTy;
3401 } else {
3402 Ty = Context.FractTy;
3403 }
3404 }
3405
3406 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3407
3408 bool isSigned = !Literal.isUnsigned;
3409 unsigned scale = Context.getFixedPointScale(Ty);
3410 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3411
3412 llvm::APInt Val(bit_width, 0, isSigned);
3413 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3414 bool ValIsZero = Val.isNullValue() && !Overflowed;
3415
3416 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3417 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3418 // Clause 6.4.4 - The value of a constant shall be in the range of
3419 // representable values for its type, with exception for constants of a
3420 // fract type with a value of exactly 1; such a constant shall denote
3421 // the maximal value for the type.
3422 --Val;
3423 else if (Val.ugt(MaxVal) || Overflowed)
3424 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3425
3426 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3427 Tok.getLocation(), scale);
3428 } else if (Literal.isFloatingLiteral()) {
3429 QualType Ty;
3430 if (Literal.isHalf){
3431 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3432 Ty = Context.HalfTy;
3433 else {
3434 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3435 return ExprError();
3436 }
3437 } else if (Literal.isFloat)
3438 Ty = Context.FloatTy;
3439 else if (Literal.isLong)
3440 Ty = Context.LongDoubleTy;
3441 else if (Literal.isFloat16)
3442 Ty = Context.Float16Ty;
3443 else if (Literal.isFloat128)
3444 Ty = Context.Float128Ty;
3445 else
3446 Ty = Context.DoubleTy;
3447
3448 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3449
3450 if (Ty == Context.DoubleTy) {
3451 if (getLangOpts().SinglePrecisionConstants) {
3452 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3453 if (BTy->getKind() != BuiltinType::Float) {
3454 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3455 }
3456 } else if (getLangOpts().OpenCL &&
3457 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3458 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3459 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3460 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3461 }
3462 }
3463 } else if (!Literal.isIntegerLiteral()) {
3464 return ExprError();
3465 } else {
3466 QualType Ty;
3467
3468 // 'long long' is a C99 or C++11 feature.
3469 if (!getLangOpts().C99 && Literal.isLongLong) {
3470 if (getLangOpts().CPlusPlus)
3471 Diag(Tok.getLocation(),
3472 getLangOpts().CPlusPlus11 ?
3473 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3474 else
3475 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3476 }
3477
3478 // Get the value in the widest-possible width.
3479 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3480 llvm::APInt ResultVal(MaxWidth, 0);
3481
3482 if (Literal.GetIntegerValue(ResultVal)) {
3483 // If this value didn't fit into uintmax_t, error and force to ull.
3484 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3485 << /* Unsigned */ 1;
3486 Ty = Context.UnsignedLongLongTy;
3487 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3488 "long long is not intmax_t?");
3489 } else {
3490 // If this value fits into a ULL, try to figure out what else it fits into
3491 // according to the rules of C99 6.4.4.1p5.
3492
3493 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3494 // be an unsigned int.
3495 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3496
3497 // Check from smallest to largest, picking the smallest type we can.
3498 unsigned Width = 0;
3499
3500 // Microsoft specific integer suffixes are explicitly sized.
3501 if (Literal.MicrosoftInteger) {
3502 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3503 Width = 8;
3504 Ty = Context.CharTy;
3505 } else {
3506 Width = Literal.MicrosoftInteger;
3507 Ty = Context.getIntTypeForBitwidth(Width,
3508 /*Signed=*/!Literal.isUnsigned);
3509 }
3510 }
3511
3512 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3513 // Are int/unsigned possibilities?
3514 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3515
3516 // Does it fit in a unsigned int?
3517 if (ResultVal.isIntN(IntSize)) {
3518 // Does it fit in a signed int?
3519 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3520 Ty = Context.IntTy;
3521 else if (AllowUnsigned)
3522 Ty = Context.UnsignedIntTy;
3523 Width = IntSize;
3524 }
3525 }
3526
3527 // Are long/unsigned long possibilities?
3528 if (Ty.isNull() && !Literal.isLongLong) {
3529 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3530
3531 // Does it fit in a unsigned long?
3532 if (ResultVal.isIntN(LongSize)) {
3533 // Does it fit in a signed long?
3534 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3535 Ty = Context.LongTy;
3536 else if (AllowUnsigned)
3537 Ty = Context.UnsignedLongTy;
3538 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3539 // is compatible.
3540 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3541 const unsigned LongLongSize =
3542 Context.getTargetInfo().getLongLongWidth();
3543 Diag(Tok.getLocation(),
3544 getLangOpts().CPlusPlus
3545 ? Literal.isLong
3546 ? diag::warn_old_implicitly_unsigned_long_cxx
3547 : /*C++98 UB*/ diag::
3548 ext_old_implicitly_unsigned_long_cxx
3549 : diag::warn_old_implicitly_unsigned_long)
3550 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3551 : /*will be ill-formed*/ 1);
3552 Ty = Context.UnsignedLongTy;
3553 }
3554 Width = LongSize;
3555 }
3556 }
3557
3558 // Check long long if needed.
3559 if (Ty.isNull()) {
3560 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3561
3562 // Does it fit in a unsigned long long?
3563 if (ResultVal.isIntN(LongLongSize)) {
3564 // Does it fit in a signed long long?
3565 // To be compatible with MSVC, hex integer literals ending with the
3566 // LL or i64 suffix are always signed in Microsoft mode.
3567 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3568 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3569 Ty = Context.LongLongTy;
3570 else if (AllowUnsigned)
3571 Ty = Context.UnsignedLongLongTy;
3572 Width = LongLongSize;
3573 }
3574 }
3575
3576 // If we still couldn't decide a type, we probably have something that
3577 // does not fit in a signed long long, but has no U suffix.
3578 if (Ty.isNull()) {
3579 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3580 Ty = Context.UnsignedLongLongTy;
3581 Width = Context.getTargetInfo().getLongLongWidth();
3582 }
3583
3584 if (ResultVal.getBitWidth() != Width)
3585 ResultVal = ResultVal.trunc(Width);
3586 }
3587 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3588 }
3589
3590 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3591 if (Literal.isImaginary) {
3592 Res = new (Context) ImaginaryLiteral(Res,
3593 Context.getComplexType(Res->getType()));
3594
3595 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3596 }
3597 return Res;
3598 }
3599
3600 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3601 assert(E && "ActOnParenExpr() missing expr");
3602 return new (Context) ParenExpr(L, R, E);
3603 }
3604
3605 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3606 SourceLocation Loc,
3607 SourceRange ArgRange) {
3608 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3609 // scalar or vector data type argument..."
3610 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3611 // type (C99 6.2.5p18) or void.
3612 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3613 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3614 << T << ArgRange;
3615 return true;
3616 }
3617
3618 assert((T->isVoidType() || !T->isIncompleteType()) &&
3619 "Scalar types should always be complete");
3620 return false;
3621 }
3622
3623 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3624 SourceLocation Loc,
3625 SourceRange ArgRange,
3626 UnaryExprOrTypeTrait TraitKind) {
3627 // Invalid types must be hard errors for SFINAE in C++.
3628 if (S.LangOpts.CPlusPlus)
3629 return true;
3630
3631 // C99 6.5.3.4p1:
3632 if (T->isFunctionType() &&
3633 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3634 TraitKind == UETT_PreferredAlignOf)) {
3635 // sizeof(function)/alignof(function) is allowed as an extension.
3636 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3637 << TraitKind << ArgRange;
3638 return false;
3639 }
3640
3641 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3642 // this is an error (OpenCL v1.1 s6.3.k)
3643 if (T->isVoidType()) {
3644 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3645 : diag::ext_sizeof_alignof_void_type;
3646 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3647 return false;
3648 }
3649
3650 return true;
3651 }
3652
3653 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3654 SourceLocation Loc,
3655 SourceRange ArgRange,
3656 UnaryExprOrTypeTrait TraitKind) {
3657 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3658 // runtime doesn't allow it.
3659 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3660 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3661 << T << (TraitKind == UETT_SizeOf)
3662 << ArgRange;
3663 return true;
3664 }
3665
3666 return false;
3667 }
3668
3669 /// Check whether E is a pointer from a decayed array type (the decayed
3670 /// pointer type is equal to T) and emit a warning if it is.
3671 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3672 Expr *E) {
3673 // Don't warn if the operation changed the type.
3674 if (T != E->getType())
3675 return;
3676
3677 // Now look for array decays.
3678 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3679 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3680 return;
3681
3682 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3683 << ICE->getType()
3684 << ICE->getSubExpr()->getType();
3685 }
3686
3687 /// Check the constraints on expression operands to unary type expression
3688 /// and type traits.
3689 ///
3690 /// Completes any types necessary and validates the constraints on the operand
3691 /// expression. The logic mostly mirrors the type-based overload, but may modify
3692 /// the expression as it completes the type for that expression through template
3693 /// instantiation, etc.
3694 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3695 UnaryExprOrTypeTrait ExprKind) {
3696 QualType ExprTy = E->getType();
3697 assert(!ExprTy->isReferenceType());
3698
3699 if (ExprKind == UETT_VecStep)
3700 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3701 E->getSourceRange());
3702
3703 // Whitelist some types as extensions
3704 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3705 E->getSourceRange(), ExprKind))
3706 return false;
3707
3708 // 'alignof' applied to an expression only requires the base element type of
3709 // the expression to be complete. 'sizeof' requires the expression's type to
3710 // be complete (and will attempt to complete it if it's an array of unknown
3711 // bound).
3712 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3713 if (RequireCompleteType(E->getExprLoc(),
3714 Context.getBaseElementType(E->getType()),
3715 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3716 E->getSourceRange()))
3717 return true;
3718 } else {
3719 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3720 ExprKind, E->getSourceRange()))
3721 return true;
3722 }
3723
3724 // Completing the expression's type may have changed it.
3725 ExprTy = E->getType();
3726 assert(!ExprTy->isReferenceType());
3727
3728 if (ExprTy->isFunctionType()) {
3729 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3730 << ExprKind << E->getSourceRange();
3731 return true;
3732 }
3733
3734 // The operand for sizeof and alignof is in an unevaluated expression context,
3735 // so side effects could result in unintended consequences.
3736 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3737 ExprKind == UETT_PreferredAlignOf) &&
3738 !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3739 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3740
3741 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3742 E->getSourceRange(), ExprKind))
3743 return true;
3744
3745 if (ExprKind == UETT_SizeOf) {
3746 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3747 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3748 QualType OType = PVD->getOriginalType();
3749 QualType Type = PVD->getType();
3750 if (Type->isPointerType() && OType->isArrayType()) {
3751 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3752 << Type << OType;
3753 Diag(PVD->getLocation(), diag::note_declared_at);
3754 }
3755 }
3756 }
3757
3758 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3759 // decays into a pointer and returns an unintended result. This is most
3760 // likely a typo for "sizeof(array) op x".
3761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3762 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3763 BO->getLHS());
3764 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3765 BO->getRHS());
3766 }
3767 }
3768
3769 return false;
3770 }
3771
3772 /// Check the constraints on operands to unary expression and type
3773 /// traits.
3774 ///
3775 /// This will complete any types necessary, and validate the various constraints
3776 /// on those operands.
3777 ///
3778 /// The UsualUnaryConversions() function is *not* called by this routine.
3779 /// C99 6.3.2.1p[2-4] all state:
3780 /// Except when it is the operand of the sizeof operator ...
3781 ///
3782 /// C++ [expr.sizeof]p4
3783 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3784 /// standard conversions are not applied to the operand of sizeof.
3785 ///
3786 /// This policy is followed for all of the unary trait expressions.
3787 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3788 SourceLocation OpLoc,
3789 SourceRange ExprRange,
3790 UnaryExprOrTypeTrait ExprKind) {
3791 if (ExprType->isDependentType())
3792 return false;
3793
3794 // C++ [expr.sizeof]p2:
3795 // When applied to a reference or a reference type, the result
3796 // is the size of the referenced type.
3797 // C++11 [expr.alignof]p3:
3798 // When alignof is applied to a reference type, the result
3799 // shall be the alignment of the referenced type.
3800 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3801 ExprType = Ref->getPointeeType();
3802
3803 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3804 // When alignof or _Alignof is applied to an array type, the result
3805 // is the alignment of the element type.
3806 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3807 ExprKind == UETT_OpenMPRequiredSimdAlign)
3808 ExprType = Context.getBaseElementType(ExprType);
3809
3810 if (ExprKind == UETT_VecStep)
3811 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3812
3813 // Whitelist some types as extensions
3814 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3815 ExprKind))
3816 return false;
3817
3818 if (RequireCompleteType(OpLoc, ExprType,
3819 diag::err_sizeof_alignof_incomplete_type,
3820 ExprKind, ExprRange))
3821 return true;
3822
3823 if (ExprType->isFunctionType()) {
3824 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3825 << ExprKind << ExprRange;
3826 return true;
3827 }
3828
3829 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3830 ExprKind))
3831 return true;
3832
3833 return false;
3834 }
3835
3836 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3837 E = E->IgnoreParens();
3838
3839 // Cannot know anything else if the expression is dependent.
3840 if (E->isTypeDependent())
3841 return false;
3842
3843 if (E->getObjectKind() == OK_BitField) {
3844 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3845 << 1 << E->getSourceRange();
3846 return true;
3847 }
3848
3849 ValueDecl *D = nullptr;
3850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3851 D = DRE->getDecl();
3852 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3853 D = ME->getMemberDecl();
3854 }
3855
3856 // If it's a field, require the containing struct to have a
3857 // complete definition so that we can compute the layout.
3858 //
3859 // This can happen in C++11 onwards, either by naming the member
3860 // in a way that is not transformed into a member access expression
3861 // (in an unevaluated operand, for instance), or by naming the member
3862 // in a trailing-return-type.
3863 //
3864 // For the record, since __alignof__ on expressions is a GCC
3865 // extension, GCC seems to permit this but always gives the
3866 // nonsensical answer 0.
3867 //
3868 // We don't really need the layout here --- we could instead just
3869 // directly check for all the appropriate alignment-lowing
3870 // attributes --- but that would require duplicating a lot of
3871 // logic that just isn't worth duplicating for such a marginal
3872 // use-case.
3873 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3874 // Fast path this check, since we at least know the record has a
3875 // definition if we can find a member of it.
3876 if (!FD->getParent()->isCompleteDefinition()) {
3877 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3878 << E->getSourceRange();
3879 return true;
3880 }
3881
3882 // Otherwise, if it's a field, and the field doesn't have
3883 // reference type, then it must have a complete type (or be a
3884 // flexible array member, which we explicitly want to
3885 // white-list anyway), which makes the following checks trivial.
3886 if (!FD->getType()->isReferenceType())
3887 return false;
3888 }
3889
3890 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3891 }
3892
3893 bool Sema::CheckVecStepExpr(Expr *E) {
3894 E = E->IgnoreParens();
3895
3896 // Cannot know anything else if the expression is dependent.
3897 if (E->isTypeDependent())
3898 return false;
3899
3900 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3901 }
3902
3903 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3904 CapturingScopeInfo *CSI) {
3905 assert(T->isVariablyModifiedType());
3906 assert(CSI != nullptr);
3907
3908 // We're going to walk down into the type and look for VLA expressions.
3909 do {
3910 const Type *Ty = T.getTypePtr();
3911 switch (Ty->getTypeClass()) {
3912 #define TYPE(Class, Base)
3913 #define ABSTRACT_TYPE(Class, Base)
3914 #define NON_CANONICAL_TYPE(Class, Base)
3915 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3917 #include "clang/AST/TypeNodes.def"
3918 T = QualType();
3919 break;
3920 // These types are never variably-modified.
3921 case Type::Builtin:
3922 case Type::Complex:
3923 case Type::Vector:
3924 case Type::ExtVector:
3925 case Type::Record:
3926 case Type::Enum:
3927 case Type::Elaborated:
3928 case Type::TemplateSpecialization:
3929 case Type::ObjCObject:
3930 case Type::ObjCInterface:
3931 case Type::ObjCObjectPointer:
3932 case Type::ObjCTypeParam:
3933 case Type::Pipe:
3934 llvm_unreachable("type class is never variably-modified!");
3935 case Type::Adjusted:
3936 T = cast<AdjustedType>(Ty)->getOriginalType();
3937 break;
3938 case Type::Decayed:
3939 T = cast<DecayedType>(Ty)->getPointeeType();
3940 break;
3941 case Type::Pointer:
3942 T = cast<PointerType>(Ty)->getPointeeType();
3943 break;
3944 case Type::BlockPointer:
3945 T = cast<BlockPointerType>(Ty)->getPointeeType();
3946 break;
3947 case Type::LValueReference:
3948 case Type::RValueReference:
3949 T = cast<ReferenceType>(Ty)->getPointeeType();
3950 break;
3951 case Type::MemberPointer:
3952 T = cast<MemberPointerType>(Ty)->getPointeeType();
3953 break;
3954 case Type::ConstantArray:
3955 case Type::IncompleteArray:
3956 // Losing element qualification here is fine.
3957 T = cast<ArrayType>(Ty)->getElementType();
3958 break;
3959 case Type::VariableArray: {
3960 // Losing element qualification here is fine.
3961 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3962
3963 // Unknown size indication requires no size computation.
3964 // Otherwise, evaluate and record it.
3965 if (auto Size = VAT->getSizeExpr()) {
3966 if (!CSI->isVLATypeCaptured(VAT)) {
3967 RecordDecl *CapRecord = nullptr;
3968 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3969 CapRecord = LSI->Lambda;
3970 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3971 CapRecord = CRSI->TheRecordDecl;
3972 }
3973 if (CapRecord) {
3974 auto ExprLoc = Size->getExprLoc();
3975 auto SizeType = Context.getSizeType();
3976 // Build the non-static data member.
3977 auto Field =
3978 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3979 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3980 /*BW*/ nullptr, /*Mutable*/ false,
3981 /*InitStyle*/ ICIS_NoInit);
3982 Field->setImplicit(true);
3983 Field->setAccess(AS_private);
3984 Field->setCapturedVLAType(VAT);
3985 CapRecord->addDecl(Field);
3986
3987 CSI->addVLATypeCapture(ExprLoc, SizeType);
3988 }
3989 }
3990 }
3991 T = VAT->getElementType();
3992 break;
3993 }
3994 case Type::FunctionProto:
3995 case Type::FunctionNoProto:
3996 T = cast<FunctionType>(Ty)->getReturnType();
3997 break;
3998 case Type::Paren:
3999 case Type::TypeOf:
4000 case Type::UnaryTransform:
4001 case Type::Attributed:
4002 case Type::SubstTemplateTypeParm:
4003 case Type::PackExpansion:
4004 // Keep walking after single level desugaring.
4005 T = T.getSingleStepDesugaredType(Context);
4006 break;
4007 case Type::Typedef:
4008 T = cast<TypedefType>(Ty)->desugar();
4009 break;
4010 case Type::Decltype:
4011 T = cast<DecltypeType>(Ty)->desugar();
4012 break;
4013 case Type::Auto:
4014 case Type::DeducedTemplateSpecialization:
4015 T = cast<DeducedType>(Ty)->getDeducedType();
4016 break;
4017 case Type::TypeOfExpr:
4018 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4019 break;
4020 case Type::Atomic:
4021 T = cast<AtomicType>(Ty)->getValueType();
4022 break;
4023 }
4024 } while (!T.isNull() && T->isVariablyModifiedType());
4025 }
4026
4027 /// Build a sizeof or alignof expression given a type operand.
4028 ExprResult
4029 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4030 SourceLocation OpLoc,
4031 UnaryExprOrTypeTrait ExprKind,
4032 SourceRange R) {
4033 if (!TInfo)
4034 return ExprError();
4035
4036 QualType T = TInfo->getType();
4037
4038 if (!T->isDependentType() &&
4039 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4040 return ExprError();
4041
4042 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4043 if (auto *TT = T->getAs<TypedefType>()) {
4044 for (auto I = FunctionScopes.rbegin(),
4045 E = std::prev(FunctionScopes.rend());
4046 I != E; ++I) {
4047 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4048 if (CSI == nullptr)
4049 break;
4050 DeclContext *DC = nullptr;
4051 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4052 DC = LSI->CallOperator;
4053 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4054 DC = CRSI->TheCapturedDecl;
4055 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4056 DC = BSI->TheDecl;
4057 if (DC) {
4058 if (DC->containsDecl(TT->getDecl()))
4059 break;
4060 captureVariablyModifiedType(Context, T, CSI);
4061 }
4062 }
4063 }
4064 }
4065
4066 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4067 return new (Context) UnaryExprOrTypeTraitExpr(
4068 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4069 }
4070
4071 /// Build a sizeof or alignof expression given an expression
4072 /// operand.
4073 ExprResult
4074 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4075 UnaryExprOrTypeTrait ExprKind) {
4076 ExprResult PE = CheckPlaceholderExpr(E);
4077 if (PE.isInvalid())
4078 return ExprError();
4079
4080 E = PE.get();
4081
4082 // Verify that the operand is valid.
4083 bool isInvalid = false;
4084 if (E->isTypeDependent()) {
4085 // Delay type-checking for type-dependent expressions.
4086 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4087 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4088 } else if (ExprKind == UETT_VecStep) {
4089 isInvalid = CheckVecStepExpr(E);
4090 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4091 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4092 isInvalid = true;
4093 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4094 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4095 isInvalid = true;
4096 } else {
4097 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4098 }
4099
4100 if (isInvalid)
4101 return ExprError();
4102
4103 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4104 PE = TransformToPotentiallyEvaluated(E);
4105 if (PE.isInvalid()) return ExprError();
4106 E = PE.get();
4107 }
4108
4109 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4110 return new (Context) UnaryExprOrTypeTraitExpr(
4111 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4112 }
4113
4114 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4115 /// expr and the same for @c alignof and @c __alignof
4116 /// Note that the ArgRange is invalid if isType is false.
4117 ExprResult
4118 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4119 UnaryExprOrTypeTrait ExprKind, bool IsType,
4120 void *TyOrEx, SourceRange ArgRange) {
4121 // If error parsing type, ignore.
4122 if (!TyOrEx) return ExprError();
4123
4124 if (IsType) {
4125 TypeSourceInfo *TInfo;
4126 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4127 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4128 }
4129
4130 Expr *ArgEx = (Expr *)TyOrEx;
4131 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4132 return Result;
4133 }
4134
4135 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4136 bool IsReal) {
4137 if (V.get()->isTypeDependent())
4138 return S.Context.DependentTy;
4139
4140 // _Real and _Imag are only l-values for normal l-values.
4141 if (V.get()->getObjectKind() != OK_Ordinary) {
4142 V = S.DefaultLvalueConversion(V.get());
4143 if (V.isInvalid())
4144 return QualType();
4145 }
4146
4147 // These operators return the element type of a complex type.
4148 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4149 return CT->getElementType();
4150
4151 // Otherwise they pass through real integer and floating point types here.
4152 if (V.get()->getType()->isArithmeticType())
4153 return V.get()->getType();
4154
4155 // Test for placeholders.
4156 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4157 if (PR.isInvalid()) return QualType();
4158 if (PR.get() != V.get()) {
4159 V = PR;
4160 return CheckRealImagOperand(S, V, Loc, IsReal);
4161 }
4162
4163 // Reject anything else.
4164 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4165 << (IsReal ? "__real" : "__imag");
4166 return QualType();
4167 }
4168
4169
4170
4171 ExprResult
4172 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4173 tok::TokenKind Kind, Expr *Input) {
4174 UnaryOperatorKind Opc;
4175 switch (Kind) {
4176 default: llvm_unreachable("Unknown unary op!");
4177 case tok::plusplus: Opc = UO_PostInc; break;
4178 case tok::minusminus: Opc = UO_PostDec; break;
4179 }
4180
4181 // Since this might is a postfix expression, get rid of ParenListExprs.
4182 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4183 if (Result.isInvalid()) return ExprError();
4184 Input = Result.get();
4185
4186 return BuildUnaryOp(S, OpLoc, Opc, Input);
4187 }
4188
4189 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4190 ///
4191 /// \return true on error
4192 static bool checkArithmeticOnObjCPointer(Sema &S,
4193 SourceLocation opLoc,
4194 Expr *op) {
4195 assert(op->getType()->isObjCObjectPointerType());
4196 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4197 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4198 return false;
4199
4200 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4201 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4202 << op->getSourceRange();
4203 return true;
4204 }
4205
4206 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4207 auto *BaseNoParens = Base->IgnoreParens();
4208 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4209 return MSProp->getPropertyDecl()->getType()->isArrayType();
4210 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4211 }
4212
4213 ExprResult
4214 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4215 Expr *idx, SourceLocation rbLoc) {
4216 if (base && !base->getType().isNull() &&
4217 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4218 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4219 /*Length=*/nullptr, rbLoc);
4220
4221 // Since this might be a postfix expression, get rid of ParenListExprs.
4222 if (isa<ParenListExpr>(base)) {
4223 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4224 if (result.isInvalid()) return ExprError();
4225 base = result.get();
4226 }
4227
4228 // Handle any non-overload placeholder types in the base and index
4229 // expressions. We can't handle overloads here because the other
4230 // operand might be an overloadable type, in which case the overload
4231 // resolution for the operator overload should get the first crack
4232 // at the overload.
4233 bool IsMSPropertySubscript = false;
4234 if (base->getType()->isNonOverloadPlaceholderType()) {
4235 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4236 if (!IsMSPropertySubscript) {
4237 ExprResult result = CheckPlaceholderExpr(base);
4238 if (result.isInvalid())
4239 return ExprError();
4240 base = result.get();
4241 }
4242 }
4243 if (idx->getType()->isNonOverloadPlaceholderType()) {
4244 ExprResult result = CheckPlaceholderExpr(idx);
4245 if (result.isInvalid()) return ExprError();
4246 idx = result.get();
4247 }
4248
4249 // Build an unanalyzed expression if either operand is type-dependent.
4250 if (getLangOpts().CPlusPlus &&
4251 (base->isTypeDependent() || idx->isTypeDependent())) {
4252 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4253 VK_LValue, OK_Ordinary, rbLoc);
4254 }
4255
4256 // MSDN, property (C++)
4257 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4258 // This attribute can also be used in the declaration of an empty array in a
4259 // class or structure definition. For example:
4260 // __declspec(property(get=GetX, put=PutX)) int x[];
4261 // The above statement indicates that x[] can be used with one or more array
4262 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4263 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4264 if (IsMSPropertySubscript) {
4265 // Build MS property subscript expression if base is MS property reference
4266 // or MS property subscript.
4267 return new (Context) MSPropertySubscriptExpr(
4268 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4269 }
4270
4271 // Use C++ overloaded-operator rules if either operand has record
4272 // type. The spec says to do this if either type is *overloadable*,
4273 // but enum types can't declare subscript operators or conversion
4274 // operators, so there's nothing interesting for overload resolution
4275 // to do if there aren't any record types involved.
4276 //
4277 // ObjC pointers have their own subscripting logic that is not tied
4278 // to overload resolution and so should not take this path.
4279 if (getLangOpts().CPlusPlus &&
4280 (base->getType()->isRecordType() ||
4281 (!base->getType()->isObjCObjectPointerType() &&
4282 idx->getType()->isRecordType()))) {
4283 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4284 }
4285
4286 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4287
4288 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4289 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4290
4291 return Res;
4292 }
4293
4294 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4295 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4296 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4297
4298 // For expressions like `&(*s).b`, the base is recorded and what should be
4299 // checked.
4300 const MemberExpr *Member = nullptr;
4301 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4302 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4303
4304 LastRecord.PossibleDerefs.erase(StrippedExpr);
4305 }
4306
4307 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4308 QualType ResultTy = E->getType();
4309 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4310
4311 // Bail if the element is an array since it is not memory access.
4312 if (isa<ArrayType>(ResultTy))
4313 return;
4314
4315 if (ResultTy->hasAttr(attr::NoDeref)) {
4316 LastRecord.PossibleDerefs.insert(E);
4317 return;
4318 }
4319
4320 // Check if the base type is a pointer to a member access of a struct
4321 // marked with noderef.
4322 const Expr *Base = E->getBase();
4323 QualType BaseTy = Base->getType();
4324 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4325 // Not a pointer access
4326 return;
4327
4328 const MemberExpr *Member = nullptr;
4329 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4330 Member->isArrow())
4331 Base = Member->getBase();
4332
4333 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4334 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4335 LastRecord.PossibleDerefs.insert(E);
4336 }
4337 }
4338
4339 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4340 Expr *LowerBound,
4341 SourceLocation ColonLoc, Expr *Length,
4342 SourceLocation RBLoc) {
4343 if (Base->getType()->isPlaceholderType() &&
4344 !Base->getType()->isSpecificPlaceholderType(
4345 BuiltinType::OMPArraySection)) {
4346 ExprResult Result = CheckPlaceholderExpr(Base);
4347 if (Result.isInvalid())
4348 return ExprError();
4349 Base = Result.get();
4350 }
4351 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4352 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4353 if (Result.isInvalid())
4354 return ExprError();
4355 Result = DefaultLvalueConversion(Result.get());
4356 if (Result.isInvalid())
4357 return ExprError();
4358 LowerBound = Result.get();
4359 }
4360 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4361 ExprResult Result = CheckPlaceholderExpr(Length);
4362 if (Result.isInvalid())
4363 return ExprError();
4364 Result = DefaultLvalueConversion(Result.get());
4365 if (Result.isInvalid())
4366 return ExprError();
4367 Length = Result.get();
4368 }
4369
4370 // Build an unanalyzed expression if either operand is type-dependent.
4371 if (Base->isTypeDependent() ||
4372 (LowerBound &&
4373 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4374 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4375 return new (Context)
4376 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4377 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4378 }
4379
4380 // Perform default conversions.
4381 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4382 QualType ResultTy;
4383 if (OriginalTy->isAnyPointerType()) {
4384 ResultTy = OriginalTy->getPointeeType();
4385 } else if (OriginalTy->isArrayType()) {
4386 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4387 } else {
4388 return ExprError(
4389 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4390 << Base->getSourceRange());
4391 }
4392 // C99 6.5.2.1p1
4393 if (LowerBound) {
4394 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4395 LowerBound);
4396 if (Res.isInvalid())
4397 return ExprError(Diag(LowerBound->getExprLoc(),
4398 diag::err_omp_typecheck_section_not_integer)
4399 << 0 << LowerBound->getSourceRange());
4400 LowerBound = Res.get();
4401
4402 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4403 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4404 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4405 << 0 << LowerBound->getSourceRange();
4406 }
4407 if (Length) {
4408 auto Res =
4409 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4410 if (Res.isInvalid())
4411 return ExprError(Diag(Length->getExprLoc(),
4412 diag::err_omp_typecheck_section_not_integer)
4413 << 1 << Length->getSourceRange());
4414 Length = Res.get();
4415
4416 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4417 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4418 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4419 << 1 << Length->getSourceRange();
4420 }
4421
4422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4424 // type. Note that functions are not objects, and that (in C99 parlance)
4425 // incomplete types are not object types.
4426 if (ResultTy->isFunctionType()) {
4427 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4428 << ResultTy << Base->getSourceRange();
4429 return ExprError();
4430 }
4431
4432 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4433 diag::err_omp_section_incomplete_type, Base))
4434 return ExprError();
4435
4436 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4437 Expr::EvalResult Result;
4438 if (LowerBound->EvaluateAsInt(Result, Context)) {
4439 // OpenMP 4.5, [2.4 Array Sections]
4440 // The array section must be a subset of the original array.
4441 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4442 if (LowerBoundValue.isNegative()) {
4443 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4444 << LowerBound->getSourceRange();
4445 return ExprError();
4446 }
4447 }
4448 }
4449
4450 if (Length) {
4451 Expr::EvalResult Result;
4452 if (Length->EvaluateAsInt(Result, Context)) {
4453 // OpenMP 4.5, [2.4 Array Sections]
4454 // The length must evaluate to non-negative integers.
4455 llvm::APSInt LengthValue = Result.Val.getInt();
4456 if (LengthValue.isNegative()) {
4457 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4458 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4459 << Length->getSourceRange();
4460 return ExprError();
4461 }
4462 }
4463 } else if (ColonLoc.isValid() &&
4464 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4465 !OriginalTy->isVariableArrayType()))) {
4466 // OpenMP 4.5, [2.4 Array Sections]
4467 // When the size of the array dimension is not known, the length must be
4468 // specified explicitly.
4469 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4470 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4471 return ExprError();
4472 }
4473
4474 if (!Base->getType()->isSpecificPlaceholderType(
4475 BuiltinType::OMPArraySection)) {
4476 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4477 if (Result.isInvalid())
4478 return ExprError();
4479 Base = Result.get();
4480 }
4481 return new (Context)
4482 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4483 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4484 }
4485
4486 ExprResult
4487 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4488 Expr *Idx, SourceLocation RLoc) {
4489 Expr *LHSExp = Base;
4490 Expr *RHSExp = Idx;
4491
4492 ExprValueKind VK = VK_LValue;
4493 ExprObjectKind OK = OK_Ordinary;
4494
4495 // Per C++ core issue 1213, the result is an xvalue if either operand is
4496 // a non-lvalue array, and an lvalue otherwise.
4497 if (getLangOpts().CPlusPlus11) {
4498 for (auto *Op : {LHSExp, RHSExp}) {
4499 Op = Op->IgnoreImplicit();
4500 if (Op->getType()->isArrayType() && !Op->isLValue())
4501 VK = VK_XValue;
4502 }
4503 }
4504
4505 // Perform default conversions.
4506 if (!LHSExp->getType()->getAs<VectorType>()) {
4507 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4508 if (Result.isInvalid())
4509 return ExprError();
4510 LHSExp = Result.get();
4511 }
4512 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4513 if (Result.isInvalid())
4514 return ExprError();
4515 RHSExp = Result.get();
4516
4517 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4518
4519 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4520 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4521 // in the subscript position. As a result, we need to derive the array base
4522 // and index from the expression types.
4523 Expr *BaseExpr, *IndexExpr;
4524 QualType ResultType;
4525 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4526 BaseExpr = LHSExp;
4527 IndexExpr = RHSExp;
4528 ResultType = Context.DependentTy;
4529 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4530 BaseExpr = LHSExp;
4531 IndexExpr = RHSExp;
4532 ResultType = PTy->getPointeeType();
4533 } else if (const ObjCObjectPointerType *PTy =
4534 LHSTy->getAs<ObjCObjectPointerType>()) {
4535 BaseExpr = LHSExp;
4536 IndexExpr = RHSExp;
4537
4538 // Use custom logic if this should be the pseudo-object subscript
4539 // expression.
4540 if (!LangOpts.isSubscriptPointerArithmetic())
4541 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4542 nullptr);
4543
4544 ResultType = PTy->getPointeeType();
4545 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4546 // Handle the uncommon case of "123[Ptr]".
4547 BaseExpr = RHSExp;
4548 IndexExpr = LHSExp;
4549 ResultType = PTy->getPointeeType();
4550 } else if (const ObjCObjectPointerType *PTy =
4551 RHSTy->getAs<ObjCObjectPointerType>()) {
4552 // Handle the uncommon case of "123[Ptr]".
4553 BaseExpr = RHSExp;
4554 IndexExpr = LHSExp;
4555 ResultType = PTy->getPointeeType();
4556 if (!LangOpts.isSubscriptPointerArithmetic()) {
4557 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4558 << ResultType << BaseExpr->getSourceRange();
4559 return ExprError();
4560 }
4561 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4562 BaseExpr = LHSExp; // vectors: V[123]
4563 IndexExpr = RHSExp;
4564 // We apply C++ DR1213 to vector subscripting too.
4565 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4566 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4567 if (Materialized.isInvalid())
4568 return ExprError();
4569 LHSExp = Materialized.get();
4570 }
4571 VK = LHSExp->getValueKind();
4572 if (VK != VK_RValue)
4573 OK = OK_VectorComponent;
4574
4575 ResultType = VTy->getElementType();
4576 QualType BaseType = BaseExpr->getType();
4577 Qualifiers BaseQuals = BaseType.getQualifiers();
4578 Qualifiers MemberQuals = ResultType.getQualifiers();
4579 Qualifiers Combined = BaseQuals + MemberQuals;
4580 if (Combined != MemberQuals)
4581 ResultType = Context.getQualifiedType(ResultType, Combined);
4582 } else if (LHSTy->isArrayType()) {
4583 // If we see an array that wasn't promoted by
4584 // DefaultFunctionArrayLvalueConversion, it must be an array that
4585 // wasn't promoted because of the C90 rule that doesn't
4586 // allow promoting non-lvalue arrays. Warn, then
4587 // force the promotion here.
4588 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4589 << LHSExp->getSourceRange();
4590 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4591 CK_ArrayToPointerDecay).get();
4592 LHSTy = LHSExp->getType();
4593
4594 BaseExpr = LHSExp;
4595 IndexExpr = RHSExp;
4596 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4597 } else if (RHSTy->isArrayType()) {
4598 // Same as previous, except for 123[f().a] case
4599 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4600 << RHSExp->getSourceRange();
4601 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4602 CK_ArrayToPointerDecay).get();
4603 RHSTy = RHSExp->getType();
4604
4605 BaseExpr = RHSExp;
4606 IndexExpr = LHSExp;
4607 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4608 } else {
4609 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4610 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4611 }
4612 // C99 6.5.2.1p1
4613 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4614 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4615 << IndexExpr->getSourceRange());
4616
4617 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4618 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4619 && !IndexExpr->isTypeDependent())
4620 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4621
4622 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4623 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4624 // type. Note that Functions are not objects, and that (in C99 parlance)
4625 // incomplete types are not object types.
4626 if (ResultType->isFunctionType()) {
4627 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4628 << ResultType << BaseExpr->getSourceRange();
4629 return ExprError();
4630 }
4631
4632 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4633 // GNU extension: subscripting on pointer to void
4634 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4635 << BaseExpr->getSourceRange();
4636
4637 // C forbids expressions of unqualified void type from being l-values.
4638 // See IsCForbiddenLValueType.
4639 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4640 } else if (!ResultType->isDependentType() &&
4641 RequireCompleteType(LLoc, ResultType,
4642 diag::err_subscript_incomplete_type, BaseExpr))
4643 return ExprError();
4644
4645 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4646 !ResultType.isCForbiddenLValueType());
4647
4648 return new (Context)
4649 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4650 }
4651
4652 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4653 ParmVarDecl *Param) {
4654 if (Param->hasUnparsedDefaultArg()) {
4655 Diag(CallLoc,
4656 diag::err_use_of_default_argument_to_function_declared_later) <<
4657 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4658 Diag(UnparsedDefaultArgLocs[Param],
4659 diag::note_default_argument_declared_here);
4660 return true;
4661 }
4662
4663 if (Param->hasUninstantiatedDefaultArg()) {
4664 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4665
4666 EnterExpressionEvaluationContext EvalContext(
4667 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4668
4669 // Instantiate the expression.
4670 //
4671 // FIXME: Pass in a correct Pattern argument, otherwise
4672 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4673 //
4674 // template<typename T>
4675 // struct A {
4676 // static int FooImpl();
4677 //
4678 // template<typename Tp>
4679 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4680 // // template argument list [[T], [Tp]], should be [[Tp]].
4681 // friend A<Tp> Foo(int a);
4682 // };
4683 //
4684 // template<typename T>
4685 // A<T> Foo(int a = A<T>::FooImpl());
4686 MultiLevelTemplateArgumentList MutiLevelArgList
4687 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4688
4689 InstantiatingTemplate Inst(*this, CallLoc, Param,
4690 MutiLevelArgList.getInnermost());
4691 if (Inst.isInvalid())
4692 return true;
4693 if (Inst.isAlreadyInstantiating()) {
4694 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4695 Param->setInvalidDecl();
4696 return true;
4697 }
4698
4699 ExprResult Result;
4700 {
4701 // C++ [dcl.fct.default]p5:
4702 // The names in the [default argument] expression are bound, and
4703 // the semantic constraints are checked, at the point where the
4704 // default argument expression appears.
4705 ContextRAII SavedContext(*this, FD);
4706 LocalInstantiationScope Local(*this);
4707 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4708 /*DirectInit*/false);
4709 }
4710 if (Result.isInvalid())
4711 return true;
4712
4713 // Check the expression as an initializer for the parameter.
4714 InitializedEntity Entity
4715 = InitializedEntity::InitializeParameter(Context, Param);
4716 InitializationKind Kind = InitializationKind::CreateCopy(
4717 Param->getLocation(),
4718 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4719 Expr *ResultE = Result.getAs<Expr>();
4720
4721 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4722 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4723 if (Result.isInvalid())
4724 return true;
4725
4726 Result =
4727 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4728 /*DiscardedValue*/ false);
4729 if (Result.isInvalid())
4730 return true;
4731
4732 // Remember the instantiated default argument.
4733 Param->setDefaultArg(Result.getAs<Expr>());
4734 if (ASTMutationListener *L = getASTMutationListener()) {
4735 L->DefaultArgumentInstantiated(Param);
4736 }
4737 }
4738
4739 // If the default argument expression is not set yet, we are building it now.
4740 if (!Param->hasInit()) {
4741 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4742 Param->setInvalidDecl();
4743 return true;
4744 }
4745
4746 // If the default expression creates temporaries, we need to
4747 // push them to the current stack of expression temporaries so they'll
4748 // be properly destroyed.
4749 // FIXME: We should really be rebuilding the default argument with new
4750 // bound temporaries; see the comment in PR5810.
4751 // We don't need to do that with block decls, though, because
4752 // blocks in default argument expression can never capture anything.
4753 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4754 // Set the "needs cleanups" bit regardless of whether there are
4755 // any explicit objects.
4756 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4757
4758 // Append all the objects to the cleanup list. Right now, this
4759 // should always be a no-op, because blocks in default argument
4760 // expressions should never be able to capture anything.
4761 assert(!Init->getNumObjects() &&
4762 "default argument expression has capturing blocks?");
4763 }
4764
4765 // We already type-checked the argument, so we know it works.
4766 // Just mark all of the declarations in this potentially-evaluated expression
4767 // as being "referenced".
4768 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4769 /*SkipLocalVariables=*/true);
4770 return false;
4771 }
4772
4773 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4774 FunctionDecl *FD, ParmVarDecl *Param) {
4775 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4776 return ExprError();
4777 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4778 }
4779
4780 Sema::VariadicCallType
4781 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4782 Expr *Fn) {
4783 if (Proto && Proto->isVariadic()) {
4784 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4785 return VariadicConstructor;
4786 else if (Fn && Fn->getType()->isBlockPointerType())
4787 return VariadicBlock;
4788 else if (FDecl) {
4789 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4790 if (Method->isInstance())
4791 return VariadicMethod;
4792 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4793 return VariadicMethod;
4794 return VariadicFunction;
4795 }
4796 return VariadicDoesNotApply;
4797 }
4798
4799 namespace {
4800 class FunctionCallCCC : public FunctionCallFilterCCC {
4801 public:
4802 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4803 unsigned NumArgs, MemberExpr *ME)
4804 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4805 FunctionName(FuncName) {}
4806
4807 bool ValidateCandidate(const TypoCorrection &candidate) override {
4808 if (!candidate.getCorrectionSpecifier() ||
4809 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4810 return false;
4811 }
4812
4813 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4814 }
4815
4816 private:
4817 const IdentifierInfo *const FunctionName;
4818 };
4819 }
4820
4821 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4822 FunctionDecl *FDecl,
4823 ArrayRef<Expr *> Args) {
4824 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4825 DeclarationName FuncName = FDecl->getDeclName();
4826 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4827
4828 if (TypoCorrection Corrected = S.CorrectTypo(
4829 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4830 S.getScopeForContext(S.CurContext), nullptr,
4831 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4832 Args.size(), ME),
4833 Sema::CTK_ErrorRecovery)) {
4834 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4835 if (Corrected.isOverloaded()) {
4836 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4837 OverloadCandidateSet::iterator Best;
4838 for (NamedDecl *CD : Corrected) {
4839 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4840 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4841 OCS);
4842 }
4843 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4844 case OR_Success:
4845 ND = Best->FoundDecl;
4846 Corrected.setCorrectionDecl(ND);
4847 break;
4848 default:
4849 break;
4850 }
4851 }
4852 ND = ND->getUnderlyingDecl();
4853 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4854 return Corrected;
4855 }
4856 }
4857 return TypoCorrection();
4858 }
4859
4860 /// ConvertArgumentsForCall - Converts the arguments specified in
4861 /// Args/NumArgs to the parameter types of the function FDecl with
4862 /// function prototype Proto. Call is the call expression itself, and
4863 /// Fn is the function expression. For a C++ member function, this
4864 /// routine does not attempt to convert the object argument. Returns
4865 /// true if the call is ill-formed.
4866 bool
4867 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4868 FunctionDecl *FDecl,
4869 const FunctionProtoType *Proto,
4870 ArrayRef<Expr *> Args,
4871 SourceLocation RParenLoc,
4872 bool IsExecConfig) {
4873 // Bail out early if calling a builtin with custom typechecking.
4874 if (FDecl)
4875 if (unsigned ID = FDecl->getBuiltinID())
4876 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4877 return false;
4878
4879 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4880 // assignment, to the types of the corresponding parameter, ...
4881 unsigned NumParams = Proto->getNumParams();
4882 bool Invalid = false;
4883 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4884 unsigned FnKind = Fn->getType()->isBlockPointerType()
4885 ? 1 /* block */
4886 : (IsExecConfig ? 3 /* kernel function (exec config) */
4887 : 0 /* function */);
4888
4889 // If too few arguments are available (and we don't have default
4890 // arguments for the remaining parameters), don't make the call.
4891 if (Args.size() < NumParams) {
4892 if (Args.size() < MinArgs) {
4893 TypoCorrection TC;
4894 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4895 unsigned diag_id =
4896 MinArgs == NumParams && !Proto->isVariadic()
4897 ? diag::err_typecheck_call_too_few_args_suggest
4898 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4899 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4900 << static_cast<unsigned>(Args.size())
4901 << TC.getCorrectionRange());
4902 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4903 Diag(RParenLoc,
4904 MinArgs == NumParams && !Proto->isVariadic()
4905 ? diag::err_typecheck_call_too_few_args_one
4906 : diag::err_typecheck_call_too_few_args_at_least_one)
4907 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4908 else
4909 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4910 ? diag::err_typecheck_call_too_few_args
4911 : diag::err_typecheck_call_too_few_args_at_least)
4912 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4913 << Fn->getSourceRange();
4914
4915 // Emit the location of the prototype.
4916 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4917 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4918
4919 return true;
4920 }
4921 // We reserve space for the default arguments when we create
4922 // the call expression, before calling ConvertArgumentsForCall.
4923 assert((Call->getNumArgs() == NumParams) &&
4924 "We should have reserved space for the default arguments before!");
4925 }
4926
4927 // If too many are passed and not variadic, error on the extras and drop
4928 // them.
4929 if (Args.size() > NumParams) {
4930 if (!Proto->isVariadic()) {
4931 TypoCorrection TC;
4932 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4933 unsigned diag_id =
4934 MinArgs == NumParams && !Proto->isVariadic()
4935 ? diag::err_typecheck_call_too_many_args_suggest
4936 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4937 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4938 << static_cast<unsigned>(Args.size())
4939 << TC.getCorrectionRange());
4940 } else if (NumParams == 1 && FDecl &&
4941 FDecl->getParamDecl(0)->getDeclName())
4942 Diag(Args[NumParams]->getBeginLoc(),
4943 MinArgs == NumParams
4944 ? diag::err_typecheck_call_too_many_args_one
4945 : diag::err_typecheck_call_too_many_args_at_most_one)
4946 << FnKind << FDecl->getParamDecl(0)
4947 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4948 << SourceRange(Args[NumParams]->getBeginLoc(),
4949 Args.back()->getEndLoc());
4950 else
4951 Diag(Args[NumParams]->getBeginLoc(),
4952 MinArgs == NumParams
4953 ? diag::err_typecheck_call_too_many_args
4954 : diag::err_typecheck_call_too_many_args_at_most)
4955 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4956 << Fn->getSourceRange()
4957 << SourceRange(Args[NumParams]->getBeginLoc(),
4958 Args.back()->getEndLoc());
4959
4960 // Emit the location of the prototype.
4961 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4962 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4963
4964 // This deletes the extra arguments.
4965 Call->shrinkNumArgs(NumParams);
4966 return true;
4967 }
4968 }
4969 SmallVector<Expr *, 8> AllArgs;
4970 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4971
4972 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
4973 AllArgs, CallType);
4974 if (Invalid)
4975 return true;
4976 unsigned TotalNumArgs = AllArgs.size();
4977 for (unsigned i = 0; i < TotalNumArgs; ++i)
4978 Call->setArg(i, AllArgs[i]);
4979
4980 return false;
4981 }
4982
4983 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4984 const FunctionProtoType *Proto,
4985 unsigned FirstParam, ArrayRef<Expr *> Args,
4986 SmallVectorImpl<Expr *> &AllArgs,
4987 VariadicCallType CallType, bool AllowExplicit,
4988 bool IsListInitialization) {
4989 unsigned NumParams = Proto->getNumParams();
4990 bool Invalid = false;
4991 size_t ArgIx = 0;
4992 // Continue to check argument types (even if we have too few/many args).
4993 for (unsigned i = FirstParam; i < NumParams; i++) {
4994 QualType ProtoArgType = Proto->getParamType(i);
4995
4996 Expr *Arg;
4997 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4998 if (ArgIx < Args.size()) {
4999 Arg = Args[ArgIx++];
5000
5001 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5002 diag::err_call_incomplete_argument, Arg))
5003 return true;
5004
5005 // Strip the unbridged-cast placeholder expression off, if applicable.
5006 bool CFAudited = false;
5007 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5008 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5009 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5010 Arg = stripARCUnbridgedCast(Arg);
5011 else if (getLangOpts().ObjCAutoRefCount &&
5012 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5013 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5014 CFAudited = true;
5015
5016 if (Proto->getExtParameterInfo(i).isNoEscape())
5017 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5018 BE->getBlockDecl()->setDoesNotEscape();
5019
5020 InitializedEntity Entity =
5021 Param ? InitializedEntity::InitializeParameter(Context, Param,
5022 ProtoArgType)
5023 : InitializedEntity::InitializeParameter(
5024 Context, ProtoArgType, Proto->isParamConsumed(i));
5025
5026 // Remember that parameter belongs to a CF audited API.
5027 if (CFAudited)
5028 Entity.setParameterCFAudited();
5029
5030 ExprResult ArgE = PerformCopyInitialization(
5031 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5032 if (ArgE.isInvalid())
5033 return true;
5034
5035 Arg = ArgE.getAs<Expr>();
5036 } else {
5037 assert(Param && "can't use default arguments without a known callee");
5038
5039 ExprResult ArgExpr =
5040 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5041 if (ArgExpr.isInvalid())
5042 return true;
5043
5044 Arg = ArgExpr.getAs<Expr>();
5045 }
5046
5047 // Check for array bounds violations for each argument to the call. This
5048 // check only triggers warnings when the argument isn't a more complex Expr
5049 // with its own checking, such as a BinaryOperator.
5050 CheckArrayAccess(Arg);
5051
5052 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5053 CheckStaticArrayArgument(CallLoc, Param, Arg);
5054
5055 AllArgs.push_back(Arg);
5056 }
5057
5058 // If this is a variadic call, handle args passed through "...".
5059 if (CallType != VariadicDoesNotApply) {
5060 // Assume that extern "C" functions with variadic arguments that
5061 // return __unknown_anytype aren't *really* variadic.
5062 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5063 FDecl->isExternC()) {
5064 for (Expr *A : Args.slice(ArgIx)) {
5065 QualType paramType; // ignored
5066 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5067 Invalid |= arg.isInvalid();
5068 AllArgs.push_back(arg.get());
5069 }
5070
5071 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5072 } else {
5073 for (Expr *A : Args.slice(ArgIx)) {
5074 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5075 Invalid |= Arg.isInvalid();
5076 AllArgs.push_back(Arg.get());
5077 }
5078 }
5079
5080 // Check for array bounds violations.
5081 for (Expr *A : Args.slice(ArgIx))
5082 CheckArrayAccess(A);
5083 }
5084 return Invalid;
5085 }
5086
5087 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5088 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5089 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5090 TL = DTL.getOriginalLoc();
5091 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5092 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5093 << ATL.getLocalSourceRange();
5094 }
5095
5096 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5097 /// array parameter, check that it is non-null, and that if it is formed by
5098 /// array-to-pointer decay, the underlying array is sufficiently large.
5099 ///
5100 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5101 /// array type derivation, then for each call to the function, the value of the
5102 /// corresponding actual argument shall provide access to the first element of
5103 /// an array with at least as many elements as specified by the size expression.
5104 void
5105 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5106 ParmVarDecl *Param,
5107 const Expr *ArgExpr) {
5108 // Static array parameters are not supported in C++.
5109 if (!Param || getLangOpts().CPlusPlus)
5110 return;
5111
5112 QualType OrigTy = Param->getOriginalType();
5113
5114 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5115 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5116 return;
5117
5118 if (ArgExpr->isNullPointerConstant(Context,
5119 Expr::NPC_NeverValueDependent)) {
5120 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5121 DiagnoseCalleeStaticArrayParam(*this, Param);
5122 return;
5123 }
5124
5125 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5126 if (!CAT)
5127 return;
5128
5129 const ConstantArrayType *ArgCAT =
5130 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5131 if (!ArgCAT)
5132 return;
5133
5134 if (ArgCAT->getSize().ult(CAT->getSize())) {
5135 Diag(CallLoc, diag::warn_static_array_too_small)
5136 << ArgExpr->getSourceRange()
5137 << (unsigned) ArgCAT->getSize().getZExtValue()
5138 << (unsigned) CAT->getSize().getZExtValue();
5139 DiagnoseCalleeStaticArrayParam(*this, Param);
5140 }
5141 }
5142
5143 /// Given a function expression of unknown-any type, try to rebuild it
5144 /// to have a function type.
5145 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5146
5147 /// Is the given type a placeholder that we need to lower out
5148 /// immediately during argument processing?
5149 static bool isPlaceholderToRemoveAsArg(QualType type) {
5150 // Placeholders are never sugared.
5151 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5152 if (!placeholder) return false;
5153
5154 switch (placeholder->getKind()) {
5155 // Ignore all the non-placeholder types.
5156 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5157 case BuiltinType::Id:
5158 #include "clang/Basic/OpenCLImageTypes.def"
5159 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5160 case BuiltinType::Id:
5161 #include "clang/Basic/OpenCLExtensionTypes.def"
5162 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5163 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5164 #include "clang/AST/BuiltinTypes.def"
5165 return false;
5166
5167 // We cannot lower out overload sets; they might validly be resolved
5168 // by the call machinery.
5169 case BuiltinType::Overload:
5170 return false;
5171
5172 // Unbridged casts in ARC can be handled in some call positions and
5173 // should be left in place.
5174 case BuiltinType::ARCUnbridgedCast:
5175 return false;
5176
5177 // Pseudo-objects should be converted as soon as possible.
5178 case BuiltinType::PseudoObject:
5179 return true;
5180
5181 // The debugger mode could theoretically but currently does not try
5182 // to resolve unknown-typed arguments based on known parameter types.
5183 case BuiltinType::UnknownAny:
5184 return true;
5185
5186 // These are always invalid as call arguments and should be reported.
5187 case BuiltinType::BoundMember:
5188 case BuiltinType::BuiltinFn:
5189 case BuiltinType::OMPArraySection:
5190 return true;
5191
5192 }
5193 llvm_unreachable("bad builtin type kind");
5194 }
5195
5196 /// Check an argument list for placeholders that we won't try to
5197 /// handle later.
5198 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5199 // Apply this processing to all the arguments at once instead of
5200 // dying at the first failure.
5201 bool hasInvalid = false;
5202 for (size_t i = 0, e = args.size(); i != e; i++) {
5203 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5204 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5205 if (result.isInvalid()) hasInvalid = true;
5206 else args[i] = result.get();
5207 } else if (hasInvalid) {
5208 (void)S.CorrectDelayedTyposInExpr(args[i]);
5209 }
5210 }
5211 return hasInvalid;
5212 }
5213
5214 /// If a builtin function has a pointer argument with no explicit address
5215 /// space, then it should be able to accept a pointer to any address
5216 /// space as input. In order to do this, we need to replace the
5217 /// standard builtin declaration with one that uses the same address space
5218 /// as the call.
5219 ///
5220 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5221 /// it does not contain any pointer arguments without
5222 /// an address space qualifer. Otherwise the rewritten
5223 /// FunctionDecl is returned.
5224 /// TODO: Handle pointer return types.
5225 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5226 const FunctionDecl *FDecl,
5227 MultiExprArg ArgExprs) {
5228
5229 QualType DeclType = FDecl->getType();
5230 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5231
5232 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5233 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5234 return nullptr;
5235
5236 bool NeedsNewDecl = false;
5237 unsigned i = 0;
5238 SmallVector<QualType, 8> OverloadParams;
5239
5240 for (QualType ParamType : FT->param_types()) {
5241
5242 // Convert array arguments to pointer to simplify type lookup.
5243 ExprResult ArgRes =
5244 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5245 if (ArgRes.isInvalid())
5246 return nullptr;
5247 Expr *Arg = ArgRes.get();
5248 QualType ArgType = Arg->getType();
5249 if (!ParamType->isPointerType() ||
5250 ParamType.getQualifiers().hasAddressSpace() ||
5251 !ArgType->isPointerType() ||
5252 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5253 OverloadParams.push_back(ParamType);
5254 continue;
5255 }
5256
5257 QualType PointeeType = ParamType->getPointeeType();
5258 if (PointeeType.getQualifiers().hasAddressSpace())
5259 continue;
5260
5261 NeedsNewDecl = true;
5262 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5263
5264 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5265 OverloadParams.push_back(Context.getPointerType(PointeeType));
5266 }
5267
5268 if (!NeedsNewDecl)
5269 return nullptr;
5270
5271 FunctionProtoType::ExtProtoInfo EPI;
5272 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5273 OverloadParams, EPI);
5274 DeclContext *Parent = Context.getTranslationUnitDecl();
5275 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5276 FDecl->getLocation(),
5277 FDecl->getLocation(),
5278 FDecl->getIdentifier(),
5279 OverloadTy,
5280 /*TInfo=*/nullptr,
5281 SC_Extern, false,
5282 /*hasPrototype=*/true);
5283 SmallVector<ParmVarDecl*, 16> Params;
5284 FT = cast<FunctionProtoType>(OverloadTy);
5285 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5286 QualType ParamType = FT->getParamType(i);
5287 ParmVarDecl *Parm =
5288 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5289 SourceLocation(), nullptr, ParamType,
5290 /*TInfo=*/nullptr, SC_None, nullptr);
5291 Parm->setScopeInfo(0, i);
5292 Params.push_back(Parm);
5293 }
5294 OverloadDecl->setParams(Params);
5295 return OverloadDecl;
5296 }
5297
5298 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5299 FunctionDecl *Callee,
5300 MultiExprArg ArgExprs) {
5301 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5302 // similar attributes) really don't like it when functions are called with an
5303 // invalid number of args.
5304 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5305 /*PartialOverloading=*/false) &&
5306 !Callee->isVariadic())
5307 return;
5308 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5309 return;
5310
5311 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5312 S.Diag(Fn->getBeginLoc(),
5313 isa<CXXMethodDecl>(Callee)
5314 ? diag::err_ovl_no_viable_member_function_in_call
5315 : diag::err_ovl_no_viable_function_in_call)
5316 << Callee << Callee->getSourceRange();
5317 S.Diag(Callee->getLocation(),
5318 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5319 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5320 return;
5321 }
5322 }
5323
5324 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5325 const UnresolvedMemberExpr *const UME, Sema &S) {
5326
5327 const auto GetFunctionLevelDCIfCXXClass =
5328 [](Sema &S) -> const CXXRecordDecl * {
5329 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5330 if (!DC || !DC->getParent())
5331 return nullptr;
5332
5333 // If the call to some member function was made from within a member
5334 // function body 'M' return return 'M's parent.
5335 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5336 return MD->getParent()->getCanonicalDecl();
5337 // else the call was made from within a default member initializer of a
5338 // class, so return the class.
5339 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5340 return RD->getCanonicalDecl();
5341 return nullptr;
5342 };
5343 // If our DeclContext is neither a member function nor a class (in the
5344 // case of a lambda in a default member initializer), we can't have an
5345 // enclosing 'this'.
5346
5347 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5348 if (!CurParentClass)
5349 return false;
5350
5351 // The naming class for implicit member functions call is the class in which
5352 // name lookup starts.
5353 const CXXRecordDecl *const NamingClass =
5354 UME->getNamingClass()->getCanonicalDecl();
5355 assert(NamingClass && "Must have naming class even for implicit access");
5356
5357 // If the unresolved member functions were found in a 'naming class' that is
5358 // related (either the same or derived from) to the class that contains the
5359 // member function that itself contained the implicit member access.
5360
5361 return CurParentClass == NamingClass ||
5362 CurParentClass->isDerivedFrom(NamingClass);
5363 }
5364
5365 static void
5366 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5367 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5368
5369 if (!UME)
5370 return;
5371
5372 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5373 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5374 // already been captured, or if this is an implicit member function call (if
5375 // it isn't, an attempt to capture 'this' should already have been made).
5376 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5377 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5378 return;
5379
5380 // Check if the naming class in which the unresolved members were found is
5381 // related (same as or is a base of) to the enclosing class.
5382
5383 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5384 return;
5385
5386
5387 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5388 // If the enclosing function is not dependent, then this lambda is
5389 // capture ready, so if we can capture this, do so.
5390 if (!EnclosingFunctionCtx->isDependentContext()) {
5391 // If the current lambda and all enclosing lambdas can capture 'this' -
5392 // then go ahead and capture 'this' (since our unresolved overload set
5393 // contains at least one non-static member function).
5394 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5395 S.CheckCXXThisCapture(CallLoc);
5396 } else if (S.CurContext->isDependentContext()) {
5397 // ... since this is an implicit member reference, that might potentially
5398 // involve a 'this' capture, mark 'this' for potential capture in
5399 // enclosing lambdas.
5400 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5401 CurLSI->addPotentialThisCapture(CallLoc);
5402 }
5403 }
5404
5405 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5406 /// This provides the location of the left/right parens and a list of comma
5407 /// locations.
5408 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5409 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5410 Expr *ExecConfig, bool IsExecConfig) {
5411 // Since this might be a postfix expression, get rid of ParenListExprs.
5412 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5413 if (Result.isInvalid()) return ExprError();
5414 Fn = Result.get();
5415
5416 if (checkArgsForPlaceholders(*this, ArgExprs))
5417 return ExprError();
5418
5419 if (getLangOpts().CPlusPlus) {
5420 // If this is a pseudo-destructor expression, build the call immediately.
5421 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5422 if (!ArgExprs.empty()) {
5423 // Pseudo-destructor calls should not have any arguments.
5424 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5425 << FixItHint::CreateRemoval(
5426 SourceRange(ArgExprs.front()->getBeginLoc(),
5427 ArgExprs.back()->getEndLoc()));
5428 }
5429
5430 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5431 VK_RValue, RParenLoc);
5432 }
5433 if (Fn->getType() == Context.PseudoObjectTy) {
5434 ExprResult result = CheckPlaceholderExpr(Fn);
5435 if (result.isInvalid()) return ExprError();
5436 Fn = result.get();
5437 }
5438
5439 // Determine whether this is a dependent call inside a C++ template,
5440 // in which case we won't do any semantic analysis now.
5441 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5442 if (ExecConfig) {
5443 return CUDAKernelCallExpr::Create(
5444 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5445 Context.DependentTy, VK_RValue, RParenLoc);
5446 } else {
5447
5448 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5449 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5450 Fn->getBeginLoc());
5451
5452 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5453 VK_RValue, RParenLoc);
5454 }
5455 }
5456
5457 // Determine whether this is a call to an object (C++ [over.call.object]).
5458 if (Fn->getType()->isRecordType())
5459 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5460 RParenLoc);
5461
5462 if (Fn->getType() == Context.UnknownAnyTy) {
5463 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5464 if (result.isInvalid()) return ExprError();
5465 Fn = result.get();
5466 }
5467
5468 if (Fn->getType() == Context.BoundMemberTy) {
5469 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5470 RParenLoc);
5471 }
5472 }
5473
5474 // Check for overloaded calls. This can happen even in C due to extensions.
5475 if (Fn->getType() == Context.OverloadTy) {
5476 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5477
5478 // We aren't supposed to apply this logic if there's an '&' involved.
5479 if (!find.HasFormOfMemberPointer) {
5480 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5481 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5482 VK_RValue, RParenLoc);
5483 OverloadExpr *ovl = find.Expression;
5484 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5485 return BuildOverloadedCallExpr(
5486 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5487 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5488 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5489 RParenLoc);
5490 }
5491 }
5492
5493 // If we're directly calling a function, get the appropriate declaration.
5494 if (Fn->getType() == Context.UnknownAnyTy) {
5495 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5496 if (result.isInvalid()) return ExprError();
5497 Fn = result.get();
5498 }
5499
5500 Expr *NakedFn = Fn->IgnoreParens();
5501
5502 bool CallingNDeclIndirectly = false;
5503 NamedDecl *NDecl = nullptr;
5504 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5505 if (UnOp->getOpcode() == UO_AddrOf) {
5506 CallingNDeclIndirectly = true;
5507 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5508 }
5509 }
5510
5511 if (isa<DeclRefExpr>(NakedFn)) {
5512 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5513
5514 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5515 if (FDecl && FDecl->getBuiltinID()) {
5516 // Rewrite the function decl for this builtin by replacing parameters
5517 // with no explicit address space with the address space of the arguments
5518 // in ArgExprs.
5519 if ((FDecl =
5520 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5521 NDecl = FDecl;
5522 Fn = DeclRefExpr::Create(
5523 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5524 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5525 }
5526 }
5527 } else if (isa<MemberExpr>(NakedFn))
5528 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5529
5530 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5531 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5532 FD, /*Complain=*/true, Fn->getBeginLoc()))
5533 return ExprError();
5534
5535 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5536 return ExprError();
5537
5538 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5539 }
5540
5541 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5542 ExecConfig, IsExecConfig);
5543 }
5544
5545 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5546 ///
5547 /// __builtin_astype( value, dst type )
5548 ///
5549 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5550 SourceLocation BuiltinLoc,
5551 SourceLocation RParenLoc) {
5552 ExprValueKind VK = VK_RValue;
5553 ExprObjectKind OK = OK_Ordinary;
5554 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5555 QualType SrcTy = E->getType();
5556 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5557 return ExprError(Diag(BuiltinLoc,
5558 diag::err_invalid_astype_of_different_size)
5559 << DstTy
5560 << SrcTy
5561 << E->getSourceRange());
5562 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5563 }
5564
5565 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5566 /// provided arguments.
5567 ///
5568 /// __builtin_convertvector( value, dst type )
5569 ///
5570 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5571 SourceLocation BuiltinLoc,
5572 SourceLocation RParenLoc) {
5573 TypeSourceInfo *TInfo;
5574 GetTypeFromParser(ParsedDestTy, &TInfo);
5575 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5576 }
5577
5578 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5579 /// i.e. an expression not of \p OverloadTy. The expression should
5580 /// unary-convert to an expression of function-pointer or
5581 /// block-pointer type.
5582 ///
5583 /// \param NDecl the declaration being called, if available
5584 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5585 SourceLocation LParenLoc,
5586 ArrayRef<Expr *> Args,
5587 SourceLocation RParenLoc, Expr *Config,
5588 bool IsExecConfig, ADLCallKind UsesADL) {
5589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5590 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5591
5592 // Functions with 'interrupt' attribute cannot be called directly.
5593 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5594 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5595 return ExprError();
5596 }
5597
5598 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5599 // so there's some risk when calling out to non-interrupt handler functions
5600 // that the callee might not preserve them. This is easy to diagnose here,
5601 // but can be very challenging to debug.
5602 if (auto *Caller = getCurFunctionDecl())
5603 if (Caller->hasAttr<ARMInterruptAttr>()) {
5604 bool VFP = Context.getTargetInfo().hasFeature("vfp");
5605 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5606 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5607 }
5608
5609 // Promote the function operand.
5610 // We special-case function promotion here because we only allow promoting
5611 // builtin functions to function pointers in the callee of a call.
5612 ExprResult Result;
5613 QualType ResultTy;
5614 if (BuiltinID &&
5615 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5616 // Extract the return type from the (builtin) function pointer type.
5617 // FIXME Several builtins still have setType in
5618 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5619 // Builtins.def to ensure they are correct before removing setType calls.
5620 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5621 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5622 ResultTy = FDecl->getCallResultType();
5623 } else {
5624 Result = CallExprUnaryConversions(Fn);
5625 ResultTy = Context.BoolTy;
5626 }
5627 if (Result.isInvalid())
5628 return ExprError();
5629 Fn = Result.get();
5630
5631 // Check for a valid function type, but only if it is not a builtin which
5632 // requires custom type checking. These will be handled by
5633 // CheckBuiltinFunctionCall below just after creation of the call expression.
5634 const FunctionType *FuncT = nullptr;
5635 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5636 retry:
5637 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5638 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5639 // have type pointer to function".
5640 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5641 if (!FuncT)
5642 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5643 << Fn->getType() << Fn->getSourceRange());
5644 } else if (const BlockPointerType *BPT =
5645 Fn->getType()->getAs<BlockPointerType>()) {
5646 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5647 } else {
5648 // Handle calls to expressions of unknown-any type.
5649 if (Fn->getType() == Context.UnknownAnyTy) {
5650 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5651 if (rewrite.isInvalid()) return ExprError();
5652 Fn = rewrite.get();
5653 goto retry;
5654 }
5655
5656 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5657 << Fn->getType() << Fn->getSourceRange());
5658 }
5659 }
5660
5661 // Get the number of parameters in the function prototype, if any.
5662 // We will allocate space for max(Args.size(), NumParams) arguments
5663 // in the call expression.
5664 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5665 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5666
5667 CallExpr *TheCall;
5668 if (Config) {
5669 assert(UsesADL == ADLCallKind::NotADL &&
5670 "CUDAKernelCallExpr should not use ADL");
5671 TheCall =
5672 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5673 ResultTy, VK_RValue, RParenLoc, NumParams);
5674 } else {
5675 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5676 RParenLoc, NumParams, UsesADL);
5677 }
5678
5679 if (!getLangOpts().CPlusPlus) {
5680 // C cannot always handle TypoExpr nodes in builtin calls and direct
5681 // function calls as their argument checking don't necessarily handle
5682 // dependent types properly, so make sure any TypoExprs have been
5683 // dealt with.
5684 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5685 if (!Result.isUsable()) return ExprError();
5686 TheCall = dyn_cast<CallExpr>(Result.get());
5687 if (!TheCall) return Result;
5688 // TheCall at this point has max(Args.size(), NumParams) arguments,
5689 // with extra arguments nulled. We don't want to introduce nulled
5690 // arguments in Args and so we only take the first Args.size() arguments.
5691 Args = llvm::makeArrayRef(TheCall->getArgs(), Args.size());
5692 }
5693
5694 // Bail out early if calling a builtin with custom type checking.
5695 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5696 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5697
5698 if (getLangOpts().CUDA) {
5699 if (Config) {
5700 // CUDA: Kernel calls must be to global functions
5701 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5702 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5703 << FDecl << Fn->getSourceRange());
5704
5705 // CUDA: Kernel function must have 'void' return type
5706 if (!FuncT->getReturnType()->isVoidType())
5707 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5708 << Fn->getType() << Fn->getSourceRange());
5709 } else {
5710 // CUDA: Calls to global functions must be configured
5711 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5712 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5713 << FDecl << Fn->getSourceRange());
5714 }
5715 }
5716
5717 // Check for a valid return type
5718 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5719 FDecl))
5720 return ExprError();
5721
5722 // We know the result type of the call, set it.
5723 TheCall->setType(FuncT->getCallResultType(Context));
5724 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5725
5726 if (Proto) {
5727 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5728 IsExecConfig))
5729 return ExprError();
5730 } else {
5731 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5732
5733 if (FDecl) {
5734 // Check if we have too few/too many template arguments, based
5735 // on our knowledge of the function definition.
5736 const FunctionDecl *Def = nullptr;
5737 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5738 Proto = Def->getType()->getAs<FunctionProtoType>();
5739 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5740 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5741 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5742 }
5743
5744 // If the function we're calling isn't a function prototype, but we have
5745 // a function prototype from a prior declaratiom, use that prototype.
5746 if (!FDecl->hasPrototype())
5747 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5748 }
5749
5750 // Promote the arguments (C99 6.5.2.2p6).
5751 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5752 Expr *Arg = Args[i];
5753
5754 if (Proto && i < Proto->getNumParams()) {
5755 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5756 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5757 ExprResult ArgE =
5758 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5759 if (ArgE.isInvalid())
5760 return true;
5761
5762 Arg = ArgE.getAs<Expr>();
5763
5764 } else {
5765 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5766
5767 if (ArgE.isInvalid())
5768 return true;
5769
5770 Arg = ArgE.getAs<Expr>();
5771 }
5772
5773 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5774 diag::err_call_incomplete_argument, Arg))
5775 return ExprError();
5776
5777 TheCall->setArg(i, Arg);
5778 }
5779 }
5780
5781 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5782 if (!Method->isStatic())
5783 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5784 << Fn->getSourceRange());
5785
5786 // Check for sentinels
5787 if (NDecl)
5788 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5789
5790 // Do special checking on direct calls to functions.
5791 if (FDecl) {
5792 if (CheckFunctionCall(FDecl, TheCall, Proto))
5793 return ExprError();
5794
5795 if (BuiltinID)
5796 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5797 } else if (NDecl) {
5798 if (CheckPointerCall(NDecl, TheCall, Proto))
5799 return ExprError();
5800 } else {
5801 if (CheckOtherCall(TheCall, Proto))
5802 return ExprError();
5803 }
5804
5805 return MaybeBindToTemporary(TheCall);
5806 }
5807
5808 ExprResult
5809 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5810 SourceLocation RParenLoc, Expr *InitExpr) {
5811 assert(Ty && "ActOnCompoundLiteral(): missing type");
5812 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5813
5814 TypeSourceInfo *TInfo;
5815 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5816 if (!TInfo)
5817 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5818
5819 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5820 }
5821
5822 ExprResult
5823 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5824 SourceLocation RParenLoc, Expr *LiteralExpr) {
5825 QualType literalType = TInfo->getType();
5826
5827 if (literalType->isArrayType()) {
5828 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5829 diag::err_illegal_decl_array_incomplete_type,
5830 SourceRange(LParenLoc,
5831 LiteralExpr->getSourceRange().getEnd())))
5832 return ExprError();
5833 if (literalType->isVariableArrayType())
5834 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5835 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5836 } else if (!literalType->isDependentType() &&
5837 RequireCompleteType(LParenLoc, literalType,
5838 diag::err_typecheck_decl_incomplete_type,
5839 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5840 return ExprError();
5841
5842 InitializedEntity Entity
5843 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5844 InitializationKind Kind
5845 = InitializationKind::CreateCStyleCast(LParenLoc,
5846 SourceRange(LParenLoc, RParenLoc),
5847 /*InitList=*/true);
5848 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5849 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5850 &literalType);
5851 if (Result.isInvalid())
5852 return ExprError();
5853 LiteralExpr = Result.get();
5854
5855 bool isFileScope = !CurContext->isFunctionOrMethod();
5856
5857 // In C, compound literals are l-values for some reason.
5858 // For GCC compatibility, in C++, file-scope array compound literals with
5859 // constant initializers are also l-values, and compound literals are
5860 // otherwise prvalues.
5861 //
5862 // (GCC also treats C++ list-initialized file-scope array prvalues with
5863 // constant initializers as l-values, but that's non-conforming, so we don't
5864 // follow it there.)
5865 //
5866 // FIXME: It would be better to handle the lvalue cases as materializing and
5867 // lifetime-extending a temporary object, but our materialized temporaries
5868 // representation only supports lifetime extension from a variable, not "out
5869 // of thin air".
5870 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5871 // is bound to the result of applying array-to-pointer decay to the compound
5872 // literal.
5873 // FIXME: GCC supports compound literals of reference type, which should
5874 // obviously have a value kind derived from the kind of reference involved.
5875 ExprValueKind VK =
5876 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5877 ? VK_RValue
5878 : VK_LValue;
5879
5880 if (isFileScope)
5881 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
5882 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
5883 Expr *Init = ILE->getInit(i);
5884 ILE->setInit(i, ConstantExpr::Create(Context, Init));
5885 }
5886
5887 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5888 VK, LiteralExpr, isFileScope);
5889 if (isFileScope) {
5890 if (!LiteralExpr->isTypeDependent() &&
5891 !LiteralExpr->isValueDependent() &&
5892 !literalType->isDependentType()) // C99 6.5.2.5p3
5893 if (CheckForConstantInitializer(LiteralExpr, literalType))
5894 return ExprError();
5895 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
5896 literalType.getAddressSpace() != LangAS::Default) {
5897 // Embedded-C extensions to C99 6.5.2.5:
5898 // "If the compound literal occurs inside the body of a function, the
5899 // type name shall not be qualified by an address-space qualifier."
5900 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
5901 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
5902 return ExprError();
5903 }
5904
5905 return MaybeBindToTemporary(E);
5906 }
5907
5908 ExprResult
5909 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5910 SourceLocation RBraceLoc) {
5911 // Immediately handle non-overload placeholders. Overloads can be
5912 // resolved contextually, but everything else here can't.
5913 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5914 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5915 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5916
5917 // Ignore failures; dropping the entire initializer list because
5918 // of one failure would be terrible for indexing/etc.
5919 if (result.isInvalid()) continue;
5920
5921 InitArgList[I] = result.get();
5922 }
5923 }
5924
5925 // Semantic analysis for initializers is done by ActOnDeclarator() and
5926 // CheckInitializer() - it requires knowledge of the object being initialized.
5927
5928 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5929 RBraceLoc);
5930 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5931 return E;
5932 }
5933
5934 /// Do an explicit extend of the given block pointer if we're in ARC.
5935 void Sema::maybeExtendBlockObject(ExprResult &E) {
5936 assert(E.get()->getType()->isBlockPointerType());
5937 assert(E.get()->isRValue());
5938
5939 // Only do this in an r-value context.
5940 if (!getLangOpts().ObjCAutoRefCount) return;
5941
5942 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5943 CK_ARCExtendBlockObject, E.get(),
5944 /*base path*/ nullptr, VK_RValue);
5945 Cleanup.setExprNeedsCleanups(true);
5946 }
5947
5948 /// Prepare a conversion of the given expression to an ObjC object
5949 /// pointer type.
5950 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5951 QualType type = E.get()->getType();
5952 if (type->isObjCObjectPointerType()) {
5953 return CK_BitCast;
5954 } else if (type->isBlockPointerType()) {
5955 maybeExtendBlockObject(E);
5956 return CK_BlockPointerToObjCPointerCast;
5957 } else {
5958 assert(type->isPointerType());
5959 return CK_CPointerToObjCPointerCast;
5960 }
5961 }
5962
5963 /// Prepares for a scalar cast, performing all the necessary stages
5964 /// except the final cast and returning the kind required.
5965 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5966 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5967 // Also, callers should have filtered out the invalid cases with
5968 // pointers. Everything else should be possible.
5969
5970 QualType SrcTy = Src.get()->getType();
5971 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5972 return CK_NoOp;
5973
5974 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5975 case Type::STK_MemberPointer:
5976 llvm_unreachable("member pointer type in C");
5977
5978 case Type::STK_CPointer:
5979 case Type::STK_BlockPointer:
5980 case Type::STK_ObjCObjectPointer:
5981 switch (DestTy->getScalarTypeKind()) {
5982 case Type::STK_CPointer: {
5983 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5984 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5985 if (SrcAS != DestAS)
5986 return CK_AddressSpaceConversion;
5987 if (Context.hasCvrSimilarType(SrcTy, DestTy))
5988 return CK_NoOp;
5989 return CK_BitCast;
5990 }
5991 case Type::STK_BlockPointer:
5992 return (SrcKind == Type::STK_BlockPointer
5993 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5994 case Type::STK_ObjCObjectPointer:
5995 if (SrcKind == Type::STK_ObjCObjectPointer)
5996 return CK_BitCast;
5997 if (SrcKind == Type::STK_CPointer)
5998 return CK_CPointerToObjCPointerCast;
5999 maybeExtendBlockObject(Src);
6000 return CK_BlockPointerToObjCPointerCast;
6001 case Type::STK_Bool:
6002 return CK_PointerToBoolean;
6003 case Type::STK_Integral:
6004 return CK_PointerToIntegral;
6005 case Type::STK_Floating:
6006 case Type::STK_FloatingComplex:
6007 case Type::STK_IntegralComplex:
6008 case Type::STK_MemberPointer:
6009 case Type::STK_FixedPoint:
6010 llvm_unreachable("illegal cast from pointer");
6011 }
6012 llvm_unreachable("Should have returned before this");
6013
6014 case Type::STK_FixedPoint:
6015 switch (DestTy->getScalarTypeKind()) {
6016 case Type::STK_FixedPoint:
6017 return CK_FixedPointCast;
6018 case Type::STK_Bool:
6019 return CK_FixedPointToBoolean;
6020 case Type::STK_Integral:
6021 case Type::STK_Floating:
6022 case Type::STK_IntegralComplex:
6023 case Type::STK_FloatingComplex:
6024 Diag(Src.get()->getExprLoc(),
6025 diag::err_unimplemented_conversion_with_fixed_point_type)
6026 << DestTy;
6027 return CK_IntegralCast;
6028 case Type::STK_CPointer:
6029 case Type::STK_ObjCObjectPointer:
6030 case Type::STK_BlockPointer:
6031 case Type::STK_MemberPointer:
6032 llvm_unreachable("illegal cast to pointer type");
6033 }
6034 llvm_unreachable("Should have returned before this");
6035
6036 case Type::STK_Bool: // casting from bool is like casting from an integer
6037 case Type::STK_Integral:
6038 switch (DestTy->getScalarTypeKind()) {
6039 case Type::STK_CPointer:
6040 case Type::STK_ObjCObjectPointer:
6041 case Type::STK_BlockPointer:
6042 if (Src.get()->isNullPointerConstant(Context,
6043 Expr::NPC_ValueDependentIsNull))
6044 return CK_NullToPointer;
6045 return CK_IntegralToPointer;
6046 case Type::STK_Bool:
6047 return CK_IntegralToBoolean;
6048 case Type::STK_Integral:
6049 return CK_IntegralCast;
6050 case Type::STK_Floating:
6051 return CK_IntegralToFloating;
6052 case Type::STK_IntegralComplex:
6053 Src = ImpCastExprToType(Src.get(),
6054 DestTy->castAs<ComplexType>()->getElementType(),
6055 CK_IntegralCast);
6056 return CK_IntegralRealToComplex;
6057 case Type::STK_FloatingComplex:
6058 Src = ImpCastExprToType(Src.get(),
6059 DestTy->castAs<ComplexType>()->getElementType(),
6060 CK_IntegralToFloating);
6061 return CK_FloatingRealToComplex;
6062 case Type::STK_MemberPointer:
6063 llvm_unreachable("member pointer type in C");
6064 case Type::STK_FixedPoint:
6065 Diag(Src.get()->getExprLoc(),
6066 diag::err_unimplemented_conversion_with_fixed_point_type)
6067 << SrcTy;
6068 return CK_IntegralCast;
6069 }
6070 llvm_unreachable("Should have returned before this");
6071
6072 case Type::STK_Floating:
6073 switch (DestTy->getScalarTypeKind()) {
6074 case Type::STK_Floating:
6075 return CK_FloatingCast;
6076 case Type::STK_Bool:
6077 return CK_FloatingToBoolean;
6078 case Type::STK_Integral:
6079 return CK_FloatingToIntegral;
6080 case Type::STK_FloatingComplex:
6081 Src = ImpCastExprToType(Src.get(),
6082 DestTy->castAs<ComplexType>()->getElementType(),
6083 CK_FloatingCast);
6084 return CK_FloatingRealToComplex;
6085 case Type::STK_IntegralComplex:
6086 Src = ImpCastExprToType(Src.get(),
6087 DestTy->castAs<ComplexType>()->getElementType(),
6088 CK_FloatingToIntegral);
6089 return CK_IntegralRealToComplex;
6090 case Type::STK_CPointer:
6091 case Type::STK_ObjCObjectPointer:
6092 case Type::STK_BlockPointer:
6093 llvm_unreachable("valid float->pointer cast?");
6094 case Type::STK_MemberPointer:
6095 llvm_unreachable("member pointer type in C");
6096 case Type::STK_FixedPoint:
6097 Diag(Src.get()->getExprLoc(),
6098 diag::err_unimplemented_conversion_with_fixed_point_type)
6099 << SrcTy;
6100 return CK_IntegralCast;
6101 }
6102 llvm_unreachable("Should have returned before this");
6103
6104 case Type::STK_FloatingComplex:
6105 switch (DestTy->getScalarTypeKind()) {
6106 case Type::STK_FloatingComplex:
6107 return CK_FloatingComplexCast;
6108 case Type::STK_IntegralComplex:
6109 return CK_FloatingComplexToIntegralComplex;
6110 case Type::STK_Floating: {
6111 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6112 if (Context.hasSameType(ET, DestTy))
6113 return CK_FloatingComplexToReal;
6114 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6115 return CK_FloatingCast;
6116 }
6117 case Type::STK_Bool:
6118 return CK_FloatingComplexToBoolean;
6119 case Type::STK_Integral:
6120 Src = ImpCastExprToType(Src.get(),
6121 SrcTy->castAs<ComplexType>()->getElementType(),
6122 CK_FloatingComplexToReal);
6123 return CK_FloatingToIntegral;
6124 case Type::STK_CPointer:
6125 case Type::STK_ObjCObjectPointer:
6126 case Type::STK_BlockPointer:
6127 llvm_unreachable("valid complex float->pointer cast?");
6128 case Type::STK_MemberPointer:
6129 llvm_unreachable("member pointer type in C");
6130 case Type::STK_FixedPoint:
6131 Diag(Src.get()->getExprLoc(),
6132 diag::err_unimplemented_conversion_with_fixed_point_type)
6133 << SrcTy;
6134 return CK_IntegralCast;
6135 }
6136 llvm_unreachable("Should have returned before this");
6137
6138 case Type::STK_IntegralComplex:
6139 switch (DestTy->getScalarTypeKind()) {
6140 case Type::STK_FloatingComplex:
6141 return CK_IntegralComplexToFloatingComplex;
6142 case Type::STK_IntegralComplex:
6143 return CK_IntegralComplexCast;
6144 case Type::STK_Integral: {
6145 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6146 if (Context.hasSameType(ET, DestTy))
6147 return CK_IntegralComplexToReal;
6148 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6149 return CK_IntegralCast;
6150 }
6151 case Type::STK_Bool:
6152 return CK_IntegralComplexToBoolean;
6153 case Type::STK_Floating:
6154 Src = ImpCastExprToType(Src.get(),
6155 SrcTy->castAs<ComplexType>()->getElementType(),
6156 CK_IntegralComplexToReal);
6157 return CK_IntegralToFloating;
6158 case Type::STK_CPointer:
6159 case Type::STK_ObjCObjectPointer:
6160 case Type::STK_BlockPointer:
6161 llvm_unreachable("valid complex int->pointer cast?");
6162 case Type::STK_MemberPointer:
6163 llvm_unreachable("member pointer type in C");
6164 case Type::STK_FixedPoint:
6165 Diag(Src.get()->getExprLoc(),
6166 diag::err_unimplemented_conversion_with_fixed_point_type)
6167 << SrcTy;
6168 return CK_IntegralCast;
6169 }
6170 llvm_unreachable("Should have returned before this");
6171 }
6172
6173 llvm_unreachable("Unhandled scalar cast");
6174 }
6175
6176 static bool breakDownVectorType(QualType type, uint64_t &len,
6177 QualType &eltType) {
6178 // Vectors are simple.
6179 if (const VectorType *vecType = type->getAs<VectorType>()) {
6180 len = vecType->getNumElements();
6181 eltType = vecType->getElementType();
6182 assert(eltType->isScalarType());
6183 return true;
6184 }
6185
6186 // We allow lax conversion to and from non-vector types, but only if
6187 // they're real types (i.e. non-complex, non-pointer scalar types).
6188 if (!type->isRealType()) return false;
6189
6190 len = 1;
6191 eltType = type;
6192 return true;
6193 }
6194
6195 /// Are the two types lax-compatible vector types? That is, given
6196 /// that one of them is a vector, do they have equal storage sizes,
6197 /// where the storage size is the number of elements times the element
6198 /// size?
6199 ///
6200 /// This will also return false if either of the types is neither a
6201 /// vector nor a real type.
6202 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6203 assert(destTy->isVectorType() || srcTy->isVectorType());
6204
6205 // Disallow lax conversions between scalars and ExtVectors (these
6206 // conversions are allowed for other vector types because common headers
6207 // depend on them). Most scalar OP ExtVector cases are handled by the
6208 // splat path anyway, which does what we want (convert, not bitcast).
6209 // What this rules out for ExtVectors is crazy things like char4*float.
6210 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6211 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6212
6213 uint64_t srcLen, destLen;
6214 QualType srcEltTy, destEltTy;
6215 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6216 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6217
6218 // ASTContext::getTypeSize will return the size rounded up to a
6219 // power of 2, so instead of using that, we need to use the raw
6220 // element size multiplied by the element count.
6221 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6222 uint64_t destEltSize = Context.getTypeSize(destEltTy);
6223
6224 return (srcLen * srcEltSize == destLen * destEltSize);
6225 }
6226
6227 /// Is this a legal conversion between two types, one of which is
6228 /// known to be a vector type?
6229 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6230 assert(destTy->isVectorType() || srcTy->isVectorType());
6231
6232 if (!Context.getLangOpts().LaxVectorConversions)
6233 return false;
6234 return areLaxCompatibleVectorTypes(srcTy, destTy);
6235 }
6236
6237 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6238 CastKind &Kind) {
6239 assert(VectorTy->isVectorType() && "Not a vector type!");
6240
6241 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6242 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6243 return Diag(R.getBegin(),
6244 Ty->isVectorType() ?
6245 diag::err_invalid_conversion_between_vectors :
6246 diag::err_invalid_conversion_between_vector_and_integer)
6247 << VectorTy << Ty << R;
6248 } else
6249 return Diag(R.getBegin(),
6250 diag::err_invalid_conversion_between_vector_and_scalar)
6251 << VectorTy << Ty << R;
6252
6253 Kind = CK_BitCast;
6254 return false;
6255 }
6256
6257 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6258 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6259
6260 if (DestElemTy == SplattedExpr->getType())
6261 return SplattedExpr;
6262
6263 assert(DestElemTy->isFloatingType() ||
6264 DestElemTy->isIntegralOrEnumerationType());
6265
6266 CastKind CK;
6267 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6268 // OpenCL requires that we convert `true` boolean expressions to -1, but
6269 // only when splatting vectors.
6270 if (DestElemTy->isFloatingType()) {
6271 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6272 // in two steps: boolean to signed integral, then to floating.
6273 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6274 CK_BooleanToSignedIntegral);
6275 SplattedExpr = CastExprRes.get();
6276 CK = CK_IntegralToFloating;
6277 } else {
6278 CK = CK_BooleanToSignedIntegral;
6279 }
6280 } else {
6281 ExprResult CastExprRes = SplattedExpr;
6282 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6283 if (CastExprRes.isInvalid())
6284 return ExprError();
6285 SplattedExpr = CastExprRes.get();
6286 }
6287 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6288 }
6289
6290 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6291 Expr *CastExpr, CastKind &Kind) {
6292 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6293
6294 QualType SrcTy = CastExpr->getType();
6295
6296 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6297 // an ExtVectorType.
6298 // In OpenCL, casts between vectors of different types are not allowed.
6299 // (See OpenCL 6.2).
6300 if (SrcTy->isVectorType()) {
6301 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6302 (getLangOpts().OpenCL &&
6303 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6304 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6305 << DestTy << SrcTy << R;
6306 return ExprError();
6307 }
6308 Kind = CK_BitCast;
6309 return CastExpr;
6310 }
6311
6312 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6313 // conversion will take place first from scalar to elt type, and then
6314 // splat from elt type to vector.
6315 if (SrcTy->isPointerType())
6316 return Diag(R.getBegin(),
6317 diag::err_invalid_conversion_between_vector_and_scalar)
6318 << DestTy << SrcTy << R;
6319
6320 Kind = CK_VectorSplat;
6321 return prepareVectorSplat(DestTy, CastExpr);
6322 }
6323
6324 ExprResult
6325 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6326 Declarator &D, ParsedType &Ty,
6327 SourceLocation RParenLoc, Expr *CastExpr) {
6328 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6329 "ActOnCastExpr(): missing type or expr");
6330
6331 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6332 if (D.isInvalidType())
6333 return ExprError();
6334
6335 if (getLangOpts().CPlusPlus) {
6336 // Check that there are no default arguments (C++ only).
6337 CheckExtraCXXDefaultArguments(D);
6338 } else {
6339 // Make sure any TypoExprs have been dealt with.
6340 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6341 if (!Res.isUsable())
6342 return ExprError();
6343 CastExpr = Res.get();
6344 }
6345
6346 checkUnusedDeclAttributes(D);
6347
6348 QualType castType = castTInfo->getType();
6349 Ty = CreateParsedType(castType, castTInfo);
6350
6351 bool isVectorLiteral = false;
6352
6353 // Check for an altivec or OpenCL literal,
6354 // i.e. all the elements are integer constants.
6355 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6356 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6357 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6358 && castType->isVectorType() && (PE || PLE)) {
6359 if (PLE && PLE->getNumExprs() == 0) {
6360 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6361 return ExprError();
6362 }
6363 if (PE || PLE->getNumExprs() == 1) {
6364 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6365 if (!E->getType()->isVectorType())
6366 isVectorLiteral = true;
6367 }
6368 else
6369 isVectorLiteral = true;
6370 }
6371
6372 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6373 // then handle it as such.
6374 if (isVectorLiteral)
6375 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6376
6377 // If the Expr being casted is a ParenListExpr, handle it specially.
6378 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6379 // sequence of BinOp comma operators.
6380 if (isa<ParenListExpr>(CastExpr)) {
6381 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6382 if (Result.isInvalid()) return ExprError();
6383 CastExpr = Result.get();
6384 }
6385
6386 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6387 !getSourceManager().isInSystemMacro(LParenLoc))
6388 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6389
6390 CheckTollFreeBridgeCast(castType, CastExpr);
6391
6392 CheckObjCBridgeRelatedCast(castType, CastExpr);
6393
6394 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6395
6396 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6397 }
6398
6399 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6400 SourceLocation RParenLoc, Expr *E,
6401 TypeSourceInfo *TInfo) {
6402 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6403 "Expected paren or paren list expression");
6404
6405 Expr **exprs;
6406 unsigned numExprs;
6407 Expr *subExpr;
6408 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6409 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6410 LiteralLParenLoc = PE->getLParenLoc();
6411 LiteralRParenLoc = PE->getRParenLoc();
6412 exprs = PE->getExprs();
6413 numExprs = PE->getNumExprs();
6414 } else { // isa<ParenExpr> by assertion at function entrance
6415 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6416 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6417 subExpr = cast<ParenExpr>(E)->getSubExpr();
6418 exprs = &subExpr;
6419 numExprs = 1;
6420 }
6421
6422 QualType Ty = TInfo->getType();
6423 assert(Ty->isVectorType() && "Expected vector type");
6424
6425 SmallVector<Expr *, 8> initExprs;
6426 const VectorType *VTy = Ty->getAs<VectorType>();
6427 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6428
6429 // '(...)' form of vector initialization in AltiVec: the number of
6430 // initializers must be one or must match the size of the vector.
6431 // If a single value is specified in the initializer then it will be
6432 // replicated to all the components of the vector
6433 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6434 // The number of initializers must be one or must match the size of the
6435 // vector. If a single value is specified in the initializer then it will
6436 // be replicated to all the components of the vector
6437 if (numExprs == 1) {
6438 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6439 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6440 if (Literal.isInvalid())
6441 return ExprError();
6442 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6443 PrepareScalarCast(Literal, ElemTy));
6444 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6445 }
6446 else if (numExprs < numElems) {
6447 Diag(E->getExprLoc(),
6448 diag::err_incorrect_number_of_vector_initializers);
6449 return ExprError();
6450 }
6451 else
6452 initExprs.append(exprs, exprs + numExprs);
6453 }
6454 else {
6455 // For OpenCL, when the number of initializers is a single value,
6456 // it will be replicated to all components of the vector.
6457 if (getLangOpts().OpenCL &&
6458 VTy->getVectorKind() == VectorType::GenericVector &&
6459 numExprs == 1) {
6460 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6461 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6462 if (Literal.isInvalid())
6463 return ExprError();
6464 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6465 PrepareScalarCast(Literal, ElemTy));
6466 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6467 }
6468
6469 initExprs.append(exprs, exprs + numExprs);
6470 }
6471 // FIXME: This means that pretty-printing the final AST will produce curly
6472 // braces instead of the original commas.
6473 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6474 initExprs, LiteralRParenLoc);
6475 initE->setType(Ty);
6476 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6477 }
6478
6479 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6480 /// the ParenListExpr into a sequence of comma binary operators.
6481 ExprResult
6482 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6483 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6484 if (!E)
6485 return OrigExpr;
6486
6487 ExprResult Result(E->getExpr(0));
6488
6489 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6490 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6491 E->getExpr(i));
6492
6493 if (Result.isInvalid()) return ExprError();
6494
6495 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6496 }
6497
6498 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6499 SourceLocation R,
6500 MultiExprArg Val) {
6501 return ParenListExpr::Create(Context, L, Val, R);
6502 }
6503
6504 /// Emit a specialized diagnostic when one expression is a null pointer
6505 /// constant and the other is not a pointer. Returns true if a diagnostic is
6506 /// emitted.
6507 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6508 SourceLocation QuestionLoc) {
6509 Expr *NullExpr = LHSExpr;
6510 Expr *NonPointerExpr = RHSExpr;
6511 Expr::NullPointerConstantKind NullKind =
6512 NullExpr->isNullPointerConstant(Context,
6513 Expr::NPC_ValueDependentIsNotNull);
6514
6515 if (NullKind == Expr::NPCK_NotNull) {
6516 NullExpr = RHSExpr;
6517 NonPointerExpr = LHSExpr;
6518 NullKind =
6519 NullExpr->isNullPointerConstant(Context,
6520 Expr::NPC_ValueDependentIsNotNull);
6521 }
6522
6523 if (NullKind == Expr::NPCK_NotNull)
6524 return false;
6525
6526 if (NullKind == Expr::NPCK_ZeroExpression)
6527 return false;
6528
6529 if (NullKind == Expr::NPCK_ZeroLiteral) {
6530 // In this case, check to make sure that we got here from a "NULL"
6531 // string in the source code.
6532 NullExpr = NullExpr->IgnoreParenImpCasts();
6533 SourceLocation loc = NullExpr->getExprLoc();
6534 if (!findMacroSpelling(loc, "NULL"))
6535 return false;
6536 }
6537
6538 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6539 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6540 << NonPointerExpr->getType() << DiagType
6541 << NonPointerExpr->getSourceRange();
6542 return true;
6543 }
6544
6545 /// Return false if the condition expression is valid, true otherwise.
6546 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6547 QualType CondTy = Cond->getType();
6548
6549 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6550 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6551 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6552 << CondTy << Cond->getSourceRange();
6553 return true;
6554 }
6555
6556 // C99 6.5.15p2
6557 if (CondTy->isScalarType()) return false;
6558
6559 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6560 << CondTy << Cond->getSourceRange();
6561 return true;
6562 }
6563
6564 /// Handle when one or both operands are void type.
6565 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6566 ExprResult &RHS) {
6567 Expr *LHSExpr = LHS.get();
6568 Expr *RHSExpr = RHS.get();
6569
6570 if (!LHSExpr->getType()->isVoidType())
6571 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6572 << RHSExpr->getSourceRange();
6573 if (!RHSExpr->getType()->isVoidType())
6574 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6575 << LHSExpr->getSourceRange();
6576 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6577 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6578 return S.Context.VoidTy;
6579 }
6580
6581 /// Return false if the NullExpr can be promoted to PointerTy,
6582 /// true otherwise.
6583 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6584 QualType PointerTy) {
6585 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6586 !NullExpr.get()->isNullPointerConstant(S.Context,
6587 Expr::NPC_ValueDependentIsNull))
6588 return true;
6589
6590 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6591 return false;
6592 }
6593
6594 /// Checks compatibility between two pointers and return the resulting
6595 /// type.
6596 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6597 ExprResult &RHS,
6598 SourceLocation Loc) {
6599 QualType LHSTy = LHS.get()->getType();
6600 QualType RHSTy = RHS.get()->getType();
6601
6602 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6603 // Two identical pointers types are always compatible.
6604 return LHSTy;
6605 }
6606
6607 QualType lhptee, rhptee;
6608
6609 // Get the pointee types.
6610 bool IsBlockPointer = false;
6611 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6612 lhptee = LHSBTy->getPointeeType();
6613 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6614 IsBlockPointer = true;
6615 } else {
6616 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6617 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6618 }
6619
6620 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6621 // differently qualified versions of compatible types, the result type is
6622 // a pointer to an appropriately qualified version of the composite
6623 // type.
6624
6625 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6626 // clause doesn't make sense for our extensions. E.g. address space 2 should
6627 // be incompatible with address space 3: they may live on different devices or
6628 // anything.
6629 Qualifiers lhQual = lhptee.getQualifiers();
6630 Qualifiers rhQual = rhptee.getQualifiers();
6631
6632 LangAS ResultAddrSpace = LangAS::Default;
6633 LangAS LAddrSpace = lhQual.getAddressSpace();
6634 LangAS RAddrSpace = rhQual.getAddressSpace();
6635
6636 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6637 // spaces is disallowed.
6638 if (lhQual.isAddressSpaceSupersetOf(rhQual))
6639 ResultAddrSpace = LAddrSpace;
6640 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6641 ResultAddrSpace = RAddrSpace;
6642 else {
6643 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6644 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6645 << RHS.get()->getSourceRange();
6646 return QualType();
6647 }
6648
6649 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6650 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6651 lhQual.removeCVRQualifiers();
6652 rhQual.removeCVRQualifiers();
6653
6654 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6655 // (C99 6.7.3) for address spaces. We assume that the check should behave in
6656 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6657 // qual types are compatible iff
6658 // * corresponded types are compatible
6659 // * CVR qualifiers are equal
6660 // * address spaces are equal
6661 // Thus for conditional operator we merge CVR and address space unqualified
6662 // pointees and if there is a composite type we return a pointer to it with
6663 // merged qualifiers.
6664 LHSCastKind =
6665 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6666 RHSCastKind =
6667 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6668 lhQual.removeAddressSpace();
6669 rhQual.removeAddressSpace();
6670
6671 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6672 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6673
6674 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6675
6676 if (CompositeTy.isNull()) {
6677 // In this situation, we assume void* type. No especially good
6678 // reason, but this is what gcc does, and we do have to pick
6679 // to get a consistent AST.
6680 QualType incompatTy;
6681 incompatTy = S.Context.getPointerType(
6682 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6683 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6684 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6685
6686 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6687 // for casts between types with incompatible address space qualifiers.
6688 // For the following code the compiler produces casts between global and
6689 // local address spaces of the corresponded innermost pointees:
6690 // local int *global *a;
6691 // global int *global *b;
6692 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6693 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6694 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6695 << RHS.get()->getSourceRange();
6696
6697 return incompatTy;
6698 }
6699
6700 // The pointer types are compatible.
6701 // In case of OpenCL ResultTy should have the address space qualifier
6702 // which is a superset of address spaces of both the 2nd and the 3rd
6703 // operands of the conditional operator.
6704 QualType ResultTy = [&, ResultAddrSpace]() {
6705 if (S.getLangOpts().OpenCL) {
6706 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6707 CompositeQuals.setAddressSpace(ResultAddrSpace);
6708 return S.Context
6709 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6710 .withCVRQualifiers(MergedCVRQual);
6711 }
6712 return CompositeTy.withCVRQualifiers(MergedCVRQual);
6713 }();
6714 if (IsBlockPointer)
6715 ResultTy = S.Context.getBlockPointerType(ResultTy);
6716 else
6717 ResultTy = S.Context.getPointerType(ResultTy);
6718
6719 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6720 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6721 return ResultTy;
6722 }
6723
6724 /// Return the resulting type when the operands are both block pointers.
6725 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6726 ExprResult &LHS,
6727 ExprResult &RHS,
6728 SourceLocation Loc) {
6729 QualType LHSTy = LHS.get()->getType();
6730 QualType RHSTy = RHS.get()->getType();
6731
6732 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6733 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6734 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6735 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6736 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6737 return destType;
6738 }
6739 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6740 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6741 << RHS.get()->getSourceRange();
6742 return QualType();
6743 }
6744
6745 // We have 2 block pointer types.
6746 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6747 }
6748
6749 /// Return the resulting type when the operands are both pointers.
6750 static QualType
6751 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6752 ExprResult &RHS,
6753 SourceLocation Loc) {
6754 // get the pointer types
6755 QualType LHSTy = LHS.get()->getType();
6756 QualType RHSTy = RHS.get()->getType();
6757
6758 // get the "pointed to" types
6759 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6760 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6761
6762 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6763 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6764 // Figure out necessary qualifiers (C99 6.5.15p6)
6765 QualType destPointee
6766 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6767 QualType destType = S.Context.getPointerType(destPointee);
6768 // Add qualifiers if necessary.
6769 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6770 // Promote to void*.
6771 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6772 return destType;
6773 }
6774 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6775 QualType destPointee
6776 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6777 QualType destType = S.Context.getPointerType(destPointee);
6778 // Add qualifiers if necessary.
6779 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6780 // Promote to void*.
6781 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6782 return destType;
6783 }
6784
6785 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6786 }
6787
6788 /// Return false if the first expression is not an integer and the second
6789 /// expression is not a pointer, true otherwise.
6790 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6791 Expr* PointerExpr, SourceLocation Loc,
6792 bool IsIntFirstExpr) {
6793 if (!PointerExpr->getType()->isPointerType() ||
6794 !Int.get()->getType()->isIntegerType())
6795 return false;
6796
6797 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6798 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6799
6800 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6801 << Expr1->getType() << Expr2->getType()
6802 << Expr1->getSourceRange() << Expr2->getSourceRange();
6803 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6804 CK_IntegralToPointer);
6805 return true;
6806 }
6807
6808 /// Simple conversion between integer and floating point types.
6809 ///
6810 /// Used when handling the OpenCL conditional operator where the
6811 /// condition is a vector while the other operands are scalar.
6812 ///
6813 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6814 /// types are either integer or floating type. Between the two
6815 /// operands, the type with the higher rank is defined as the "result
6816 /// type". The other operand needs to be promoted to the same type. No
6817 /// other type promotion is allowed. We cannot use
6818 /// UsualArithmeticConversions() for this purpose, since it always
6819 /// promotes promotable types.
6820 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6821 ExprResult &RHS,
6822 SourceLocation QuestionLoc) {
6823 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6824 if (LHS.isInvalid())
6825 return QualType();
6826 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6827 if (RHS.isInvalid())
6828 return QualType();
6829
6830 // For conversion purposes, we ignore any qualifiers.
6831 // For example, "const float" and "float" are equivalent.
6832 QualType LHSType =
6833 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6834 QualType RHSType =
6835 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6836
6837 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6838 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6839 << LHSType << LHS.get()->getSourceRange();
6840 return QualType();
6841 }
6842
6843 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6844 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6845 << RHSType << RHS.get()->getSourceRange();
6846 return QualType();
6847 }
6848
6849 // If both types are identical, no conversion is needed.
6850 if (LHSType == RHSType)
6851 return LHSType;
6852
6853 // Now handle "real" floating types (i.e. float, double, long double).
6854 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6855 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6856 /*IsCompAssign = */ false);
6857
6858 // Finally, we have two differing integer types.
6859 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6860 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6861 }
6862
6863 /// Convert scalar operands to a vector that matches the
6864 /// condition in length.
6865 ///
6866 /// Used when handling the OpenCL conditional operator where the
6867 /// condition is a vector while the other operands are scalar.
6868 ///
6869 /// We first compute the "result type" for the scalar operands
6870 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6871 /// into a vector of that type where the length matches the condition
6872 /// vector type. s6.11.6 requires that the element types of the result
6873 /// and the condition must have the same number of bits.
6874 static QualType
6875 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6876 QualType CondTy, SourceLocation QuestionLoc) {
6877 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6878 if (ResTy.isNull()) return QualType();
6879
6880 const VectorType *CV = CondTy->getAs<VectorType>();
6881 assert(CV);
6882
6883 // Determine the vector result type
6884 unsigned NumElements = CV->getNumElements();
6885 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6886
6887 // Ensure that all types have the same number of bits
6888 if (S.Context.getTypeSize(CV->getElementType())
6889 != S.Context.getTypeSize(ResTy)) {
6890 // Since VectorTy is created internally, it does not pretty print
6891 // with an OpenCL name. Instead, we just print a description.
6892 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6893 SmallString<64> Str;
6894 llvm::raw_svector_ostream OS(Str);
6895 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6896 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6897 << CondTy << OS.str();
6898 return QualType();
6899 }
6900
6901 // Convert operands to the vector result type
6902 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6903 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6904
6905 return VectorTy;
6906 }
6907
6908 /// Return false if this is a valid OpenCL condition vector
6909 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6910 SourceLocation QuestionLoc) {
6911 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6912 // integral type.
6913 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6914 assert(CondTy);
6915 QualType EleTy = CondTy->getElementType();
6916 if (EleTy->isIntegerType()) return false;
6917
6918 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6919 << Cond->getType() << Cond->getSourceRange();
6920 return true;
6921 }
6922
6923 /// Return false if the vector condition type and the vector
6924 /// result type are compatible.
6925 ///
6926 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6927 /// number of elements, and their element types have the same number
6928 /// of bits.
6929 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6930 SourceLocation QuestionLoc) {
6931 const VectorType *CV = CondTy->getAs<VectorType>();
6932 const VectorType *RV = VecResTy->getAs<VectorType>();
6933 assert(CV && RV);
6934
6935 if (CV->getNumElements() != RV->getNumElements()) {
6936 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6937 << CondTy << VecResTy;
6938 return true;
6939 }
6940
6941 QualType CVE = CV->getElementType();
6942 QualType RVE = RV->getElementType();
6943
6944 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6945 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6946 << CondTy << VecResTy;
6947 return true;
6948 }
6949
6950 return false;
6951 }
6952
6953 /// Return the resulting type for the conditional operator in
6954 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6955 /// s6.3.i) when the condition is a vector type.
6956 static QualType
6957 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6958 ExprResult &LHS, ExprResult &RHS,
6959 SourceLocation QuestionLoc) {
6960 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6961 if (Cond.isInvalid())
6962 return QualType();
6963 QualType CondTy = Cond.get()->getType();
6964
6965 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6966 return QualType();
6967
6968 // If either operand is a vector then find the vector type of the
6969 // result as specified in OpenCL v1.1 s6.3.i.
6970 if (LHS.get()->getType()->isVectorType() ||
6971 RHS.get()->getType()->isVectorType()) {
6972 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6973 /*isCompAssign*/false,
6974 /*AllowBothBool*/true,
6975 /*AllowBoolConversions*/false);
6976 if (VecResTy.isNull()) return QualType();
6977 // The result type must match the condition type as specified in
6978 // OpenCL v1.1 s6.11.6.
6979 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6980 return QualType();
6981 return VecResTy;
6982 }
6983
6984 // Both operands are scalar.
6985 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6986 }
6987
6988 /// Return true if the Expr is block type
6989 static bool checkBlockType(Sema &S, const Expr *E) {
6990 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6991 QualType Ty = CE->getCallee()->getType();
6992 if (Ty->isBlockPointerType()) {
6993 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6994 return true;
6995 }
6996 }
6997 return false;
6998 }
6999
7000 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7001 /// In that case, LHS = cond.
7002 /// C99 6.5.15
7003 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7004 ExprResult &RHS, ExprValueKind &VK,
7005 ExprObjectKind &OK,
7006 SourceLocation QuestionLoc) {
7007
7008 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7009 if (!LHSResult.isUsable()) return QualType();
7010 LHS = LHSResult;
7011
7012 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7013 if (!RHSResult.isUsable()) return QualType();
7014 RHS = RHSResult;
7015
7016 // C++ is sufficiently different to merit its own checker.
7017 if (getLangOpts().CPlusPlus)
7018 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7019
7020 VK = VK_RValue;
7021 OK = OK_Ordinary;
7022
7023 // The OpenCL operator with a vector condition is sufficiently
7024 // different to merit its own checker.
7025 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7026 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7027
7028 // First, check the condition.
7029 Cond = UsualUnaryConversions(Cond.get());
7030 if (Cond.isInvalid())
7031 return QualType();
7032 if (checkCondition(*this, Cond.get(), QuestionLoc))
7033 return QualType();
7034
7035 // Now check the two expressions.
7036 if (LHS.get()->getType()->isVectorType() ||
7037 RHS.get()->getType()->isVectorType())
7038 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7039 /*AllowBothBool*/true,
7040 /*AllowBoolConversions*/false);
7041
7042 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7043 if (LHS.isInvalid() || RHS.isInvalid())
7044 return QualType();
7045
7046 QualType LHSTy = LHS.get()->getType();
7047 QualType RHSTy = RHS.get()->getType();
7048
7049 // Diagnose attempts to convert between __float128 and long double where
7050 // such conversions currently can't be handled.
7051 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7052 Diag(QuestionLoc,
7053 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7054 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7055 return QualType();
7056 }
7057
7058 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7059 // selection operator (?:).
7060 if (getLangOpts().OpenCL &&
7061 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7062 return QualType();
7063 }
7064
7065 // If both operands have arithmetic type, do the usual arithmetic conversions
7066 // to find a common type: C99 6.5.15p3,5.
7067 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7068 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7069 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7070
7071 return ResTy;
7072 }
7073
7074 // If both operands are the same structure or union type, the result is that
7075 // type.
7076 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7077 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7078 if (LHSRT->getDecl() == RHSRT->getDecl())
7079 // "If both the operands have structure or union type, the result has
7080 // that type." This implies that CV qualifiers are dropped.
7081 return LHSTy.getUnqualifiedType();
7082 // FIXME: Type of conditional expression must be complete in C mode.
7083 }
7084
7085 // C99 6.5.15p5: "If both operands have void type, the result has void type."
7086 // The following || allows only one side to be void (a GCC-ism).
7087 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7088 return checkConditionalVoidType(*this, LHS, RHS);
7089 }
7090
7091 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7092 // the type of the other operand."
7093 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7094 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7095
7096 // All objective-c pointer type analysis is done here.
7097 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7098 QuestionLoc);
7099 if (LHS.isInvalid() || RHS.isInvalid())
7100 return QualType();
7101 if (!compositeType.isNull())
7102 return compositeType;
7103
7104
7105 // Handle block pointer types.
7106 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7107 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7108 QuestionLoc);
7109
7110 // Check constraints for C object pointers types (C99 6.5.15p3,6).
7111 if (LHSTy->isPointerType() && RHSTy->isPointerType())
7112 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7113 QuestionLoc);
7114
7115 // GCC compatibility: soften pointer/integer mismatch. Note that
7116 // null pointers have been filtered out by this point.
7117 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7118 /*isIntFirstExpr=*/true))
7119 return RHSTy;
7120 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7121 /*isIntFirstExpr=*/false))
7122 return LHSTy;
7123
7124 // Emit a better diagnostic if one of the expressions is a null pointer
7125 // constant and the other is not a pointer type. In this case, the user most
7126 // likely forgot to take the address of the other expression.
7127 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7128 return QualType();
7129
7130 // Otherwise, the operands are not compatible.
7131 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7132 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7133 << RHS.get()->getSourceRange();
7134 return QualType();
7135 }
7136
7137 /// FindCompositeObjCPointerType - Helper method to find composite type of
7138 /// two objective-c pointer types of the two input expressions.
7139 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7140 SourceLocation QuestionLoc) {
7141 QualType LHSTy = LHS.get()->getType();
7142 QualType RHSTy = RHS.get()->getType();
7143
7144 // Handle things like Class and struct objc_class*. Here we case the result
7145 // to the pseudo-builtin, because that will be implicitly cast back to the
7146 // redefinition type if an attempt is made to access its fields.
7147 if (LHSTy->isObjCClassType() &&
7148 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7149 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7150 return LHSTy;
7151 }
7152 if (RHSTy->isObjCClassType() &&
7153 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7154 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7155 return RHSTy;
7156 }
7157 // And the same for struct objc_object* / id
7158 if (LHSTy->isObjCIdType() &&
7159 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7160 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7161 return LHSTy;
7162 }
7163 if (RHSTy->isObjCIdType() &&
7164 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7165 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7166 return RHSTy;
7167 }
7168 // And the same for struct objc_selector* / SEL
7169 if (Context.isObjCSelType(LHSTy) &&
7170 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7171 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7172 return LHSTy;
7173 }
7174 if (Context.isObjCSelType(RHSTy) &&
7175 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7176 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7177 return RHSTy;
7178 }
7179 // Check constraints for Objective-C object pointers types.
7180 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7181
7182 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7183 // Two identical object pointer types are always compatible.
7184 return LHSTy;
7185 }
7186 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7187 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7188 QualType compositeType = LHSTy;
7189
7190 // If both operands are interfaces and either operand can be
7191 // assigned to the other, use that type as the composite
7192 // type. This allows
7193 // xxx ? (A*) a : (B*) b
7194 // where B is a subclass of A.
7195 //
7196 // Additionally, as for assignment, if either type is 'id'
7197 // allow silent coercion. Finally, if the types are
7198 // incompatible then make sure to use 'id' as the composite
7199 // type so the result is acceptable for sending messages to.
7200
7201 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7202 // It could return the composite type.
7203 if (!(compositeType =
7204 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7205 // Nothing more to do.
7206 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7207 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7208 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7209 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7210 } else if ((LHSTy->isObjCQualifiedIdType() ||
7211 RHSTy->isObjCQualifiedIdType()) &&
7212 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7213 // Need to handle "id<xx>" explicitly.
7214 // GCC allows qualified id and any Objective-C type to devolve to
7215 // id. Currently localizing to here until clear this should be
7216 // part of ObjCQualifiedIdTypesAreCompatible.
7217 compositeType = Context.getObjCIdType();
7218 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7219 compositeType = Context.getObjCIdType();
7220 } else {
7221 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7222 << LHSTy << RHSTy
7223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7224 QualType incompatTy = Context.getObjCIdType();
7225 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7226 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7227 return incompatTy;
7228 }
7229 // The object pointer types are compatible.
7230 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7231 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7232 return compositeType;
7233 }
7234 // Check Objective-C object pointer types and 'void *'
7235 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7236 if (getLangOpts().ObjCAutoRefCount) {
7237 // ARC forbids the implicit conversion of object pointers to 'void *',
7238 // so these types are not compatible.
7239 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7241 LHS = RHS = true;
7242 return QualType();
7243 }
7244 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7245 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7246 QualType destPointee
7247 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7248 QualType destType = Context.getPointerType(destPointee);
7249 // Add qualifiers if necessary.
7250 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7251 // Promote to void*.
7252 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7253 return destType;
7254 }
7255 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7256 if (getLangOpts().ObjCAutoRefCount) {
7257 // ARC forbids the implicit conversion of object pointers to 'void *',
7258 // so these types are not compatible.
7259 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7261 LHS = RHS = true;
7262 return QualType();
7263 }
7264 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7265 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7266 QualType destPointee
7267 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7268 QualType destType = Context.getPointerType(destPointee);
7269 // Add qualifiers if necessary.
7270 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7271 // Promote to void*.
7272 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7273 return destType;
7274 }
7275 return QualType();
7276 }
7277
7278 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7279 /// ParenRange in parentheses.
7280 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7281 const PartialDiagnostic &Note,
7282 SourceRange ParenRange) {
7283 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7284 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7285 EndLoc.isValid()) {
7286 Self.Diag(Loc, Note)
7287 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7288 << FixItHint::CreateInsertion(EndLoc, ")");
7289 } else {
7290 // We can't display the parentheses, so just show the bare note.
7291 Self.Diag(Loc, Note) << ParenRange;
7292 }
7293 }
7294
7295 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7296 return BinaryOperator::isAdditiveOp(Opc) ||
7297 BinaryOperator::isMultiplicativeOp(Opc) ||
7298 BinaryOperator::isShiftOp(Opc);
7299 }
7300
7301 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7302 /// expression, either using a built-in or overloaded operator,
7303 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7304 /// expression.
7305 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7306 Expr **RHSExprs) {
7307 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7308 E = E->IgnoreImpCasts();
7309 E = E->IgnoreConversionOperator();
7310 E = E->IgnoreImpCasts();
7311 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7312 E = MTE->GetTemporaryExpr();
7313 E = E->IgnoreImpCasts();
7314 }
7315
7316 // Built-in binary operator.
7317 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7318 if (IsArithmeticOp(OP->getOpcode())) {
7319 *Opcode = OP->getOpcode();
7320 *RHSExprs = OP->getRHS();
7321 return true;
7322 }
7323 }
7324
7325 // Overloaded operator.
7326 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7327 if (Call->getNumArgs() != 2)
7328 return false;
7329
7330 // Make sure this is really a binary operator that is safe to pass into
7331 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7332 OverloadedOperatorKind OO = Call->getOperator();
7333 if (OO < OO_Plus || OO > OO_Arrow ||
7334 OO == OO_PlusPlus || OO == OO_MinusMinus)
7335 return false;
7336
7337 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7338 if (IsArithmeticOp(OpKind)) {
7339 *Opcode = OpKind;
7340 *RHSExprs = Call->getArg(1);
7341 return true;
7342 }
7343 }
7344
7345 return false;
7346 }
7347
7348 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7349 /// or is a logical expression such as (x==y) which has int type, but is
7350 /// commonly interpreted as boolean.
7351 static bool ExprLooksBoolean(Expr *E) {
7352 E = E->IgnoreParenImpCasts();
7353
7354 if (E->getType()->isBooleanType())
7355 return true;
7356 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7357 return OP->isComparisonOp() || OP->isLogicalOp();
7358 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7359 return OP->getOpcode() == UO_LNot;
7360 if (E->getType()->isPointerType())
7361 return true;
7362 // FIXME: What about overloaded operator calls returning "unspecified boolean
7363 // type"s (commonly pointer-to-members)?
7364
7365 return false;
7366 }
7367
7368 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7369 /// and binary operator are mixed in a way that suggests the programmer assumed
7370 /// the conditional operator has higher precedence, for example:
7371 /// "int x = a + someBinaryCondition ? 1 : 2".
7372 static void DiagnoseConditionalPrecedence(Sema &Self,
7373 SourceLocation OpLoc,
7374 Expr *Condition,
7375 Expr *LHSExpr,
7376 Expr *RHSExpr) {
7377 BinaryOperatorKind CondOpcode;
7378 Expr *CondRHS;
7379
7380 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7381 return;
7382 if (!ExprLooksBoolean(CondRHS))
7383 return;
7384
7385 // The condition is an arithmetic binary expression, with a right-
7386 // hand side that looks boolean, so warn.
7387
7388 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7389 << Condition->getSourceRange()
7390 << BinaryOperator::getOpcodeStr(CondOpcode);
7391
7392 SuggestParentheses(
7393 Self, OpLoc,
7394 Self.PDiag(diag::note_precedence_silence)
7395 << BinaryOperator::getOpcodeStr(CondOpcode),
7396 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7397
7398 SuggestParentheses(Self, OpLoc,
7399 Self.PDiag(diag::note_precedence_conditional_first),
7400 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7401 }
7402
7403 /// Compute the nullability of a conditional expression.
7404 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7405 QualType LHSTy, QualType RHSTy,
7406 ASTContext &Ctx) {
7407 if (!ResTy->isAnyPointerType())
7408 return ResTy;
7409
7410 auto GetNullability = [&Ctx](QualType Ty) {
7411 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7412 if (Kind)
7413 return *Kind;
7414 return NullabilityKind::Unspecified;
7415 };
7416
7417 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7418 NullabilityKind MergedKind;
7419
7420 // Compute nullability of a binary conditional expression.
7421 if (IsBin) {
7422 if (LHSKind == NullabilityKind::NonNull)
7423 MergedKind = NullabilityKind::NonNull;
7424 else
7425 MergedKind = RHSKind;
7426 // Compute nullability of a normal conditional expression.
7427 } else {
7428 if (LHSKind == NullabilityKind::Nullable ||
7429 RHSKind == NullabilityKind::Nullable)
7430 MergedKind = NullabilityKind::Nullable;
7431 else if (LHSKind == NullabilityKind::NonNull)
7432 MergedKind = RHSKind;
7433 else if (RHSKind == NullabilityKind::NonNull)
7434 MergedKind = LHSKind;
7435 else
7436 MergedKind = NullabilityKind::Unspecified;
7437 }
7438
7439 // Return if ResTy already has the correct nullability.
7440 if (GetNullability(ResTy) == MergedKind)
7441 return ResTy;
7442
7443 // Strip all nullability from ResTy.
7444 while (ResTy->getNullability(Ctx))
7445 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7446
7447 // Create a new AttributedType with the new nullability kind.
7448 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7449 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7450 }
7451
7452 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7453 /// in the case of a the GNU conditional expr extension.
7454 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7455 SourceLocation ColonLoc,
7456 Expr *CondExpr, Expr *LHSExpr,
7457 Expr *RHSExpr) {
7458 if (!getLangOpts().CPlusPlus) {
7459 // C cannot handle TypoExpr nodes in the condition because it
7460 // doesn't handle dependent types properly, so make sure any TypoExprs have
7461 // been dealt with before checking the operands.
7462 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7463 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7464 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7465
7466 if (!CondResult.isUsable())
7467 return ExprError();
7468
7469 if (LHSExpr) {
7470 if (!LHSResult.isUsable())
7471 return ExprError();
7472 }
7473
7474 if (!RHSResult.isUsable())
7475 return ExprError();
7476
7477 CondExpr = CondResult.get();
7478 LHSExpr = LHSResult.get();
7479 RHSExpr = RHSResult.get();
7480 }
7481
7482 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7483 // was the condition.
7484 OpaqueValueExpr *opaqueValue = nullptr;
7485 Expr *commonExpr = nullptr;
7486 if (!LHSExpr) {
7487 commonExpr = CondExpr;
7488 // Lower out placeholder types first. This is important so that we don't
7489 // try to capture a placeholder. This happens in few cases in C++; such
7490 // as Objective-C++'s dictionary subscripting syntax.
7491 if (commonExpr->hasPlaceholderType()) {
7492 ExprResult result = CheckPlaceholderExpr(commonExpr);
7493 if (!result.isUsable()) return ExprError();
7494 commonExpr = result.get();
7495 }
7496 // We usually want to apply unary conversions *before* saving, except
7497 // in the special case of a C++ l-value conditional.
7498 if (!(getLangOpts().CPlusPlus
7499 && !commonExpr->isTypeDependent()
7500 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7501 && commonExpr->isGLValue()
7502 && commonExpr->isOrdinaryOrBitFieldObject()
7503 && RHSExpr->isOrdinaryOrBitFieldObject()
7504 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7505 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7506 if (commonRes.isInvalid())
7507 return ExprError();
7508 commonExpr = commonRes.get();
7509 }
7510
7511 // If the common expression is a class or array prvalue, materialize it
7512 // so that we can safely refer to it multiple times.
7513 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7514 commonExpr->getType()->isArrayType())) {
7515 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7516 if (MatExpr.isInvalid())
7517 return ExprError();
7518 commonExpr = MatExpr.get();
7519 }
7520
7521 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7522 commonExpr->getType(),
7523 commonExpr->getValueKind(),
7524 commonExpr->getObjectKind(),
7525 commonExpr);
7526 LHSExpr = CondExpr = opaqueValue;
7527 }
7528
7529 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7530 ExprValueKind VK = VK_RValue;
7531 ExprObjectKind OK = OK_Ordinary;
7532 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7533 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7534 VK, OK, QuestionLoc);
7535 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7536 RHS.isInvalid())
7537 return ExprError();
7538
7539 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7540 RHS.get());
7541
7542 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7543
7544 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7545 Context);
7546
7547 if (!commonExpr)
7548 return new (Context)
7549 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7550 RHS.get(), result, VK, OK);
7551
7552 return new (Context) BinaryConditionalOperator(
7553 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7554 ColonLoc, result, VK, OK);
7555 }
7556
7557 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7558 // being closely modeled after the C99 spec:-). The odd characteristic of this
7559 // routine is it effectively iqnores the qualifiers on the top level pointee.
7560 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7561 // FIXME: add a couple examples in this comment.
7562 static Sema::AssignConvertType
7563 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7564 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7565 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7566
7567 // get the "pointed to" type (ignoring qualifiers at the top level)
7568 const Type *lhptee, *rhptee;
7569 Qualifiers lhq, rhq;
7570 std::tie(lhptee, lhq) =
7571 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7572 std::tie(rhptee, rhq) =
7573 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7574
7575 Sema::AssignConvertType ConvTy = Sema::Compatible;
7576
7577 // C99 6.5.16.1p1: This following citation is common to constraints
7578 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7579 // qualifiers of the type *pointed to* by the right;
7580
7581 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7582 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7583 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7584 // Ignore lifetime for further calculation.
7585 lhq.removeObjCLifetime();
7586 rhq.removeObjCLifetime();
7587 }
7588
7589 if (!lhq.compatiblyIncludes(rhq)) {
7590 // Treat address-space mismatches as fatal. TODO: address subspaces
7591 if (!lhq.isAddressSpaceSupersetOf(rhq))
7592 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7593
7594 // It's okay to add or remove GC or lifetime qualifiers when converting to
7595 // and from void*.
7596 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7597 .compatiblyIncludes(
7598 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7599 && (lhptee->isVoidType() || rhptee->isVoidType()))
7600 ; // keep old
7601
7602 // Treat lifetime mismatches as fatal.
7603 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7604 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7605
7606 // For GCC/MS compatibility, other qualifier mismatches are treated
7607 // as still compatible in C.
7608 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7609 }
7610
7611 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7612 // incomplete type and the other is a pointer to a qualified or unqualified
7613 // version of void...
7614 if (lhptee->isVoidType()) {
7615 if (rhptee->isIncompleteOrObjectType())
7616 return ConvTy;
7617
7618 // As an extension, we allow cast to/from void* to function pointer.
7619 assert(rhptee->isFunctionType());
7620 return Sema::FunctionVoidPointer;
7621 }
7622
7623 if (rhptee->isVoidType()) {
7624 if (lhptee->isIncompleteOrObjectType())
7625 return ConvTy;
7626
7627 // As an extension, we allow cast to/from void* to function pointer.
7628 assert(lhptee->isFunctionType());
7629 return Sema::FunctionVoidPointer;
7630 }
7631
7632 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7633 // unqualified versions of compatible types, ...
7634 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7635 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7636 // Check if the pointee types are compatible ignoring the sign.
7637 // We explicitly check for char so that we catch "char" vs
7638 // "unsigned char" on systems where "char" is unsigned.
7639 if (lhptee->isCharType())
7640 ltrans = S.Context.UnsignedCharTy;
7641 else if (lhptee->hasSignedIntegerRepresentation())
7642 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7643
7644 if (rhptee->isCharType())
7645 rtrans = S.Context.UnsignedCharTy;
7646 else if (rhptee->hasSignedIntegerRepresentation())
7647 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7648
7649 if (ltrans == rtrans) {
7650 // Types are compatible ignoring the sign. Qualifier incompatibility
7651 // takes priority over sign incompatibility because the sign
7652 // warning can be disabled.
7653 if (ConvTy != Sema::Compatible)
7654 return ConvTy;
7655
7656 return Sema::IncompatiblePointerSign;
7657 }
7658
7659 // If we are a multi-level pointer, it's possible that our issue is simply
7660 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7661 // the eventual target type is the same and the pointers have the same
7662 // level of indirection, this must be the issue.
7663 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7664 do {
7665 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7666 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7667 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7668
7669 if (lhptee == rhptee)
7670 return Sema::IncompatibleNestedPointerQualifiers;
7671 }
7672
7673 // General pointer incompatibility takes priority over qualifiers.
7674 return Sema::IncompatiblePointer;
7675 }
7676 if (!S.getLangOpts().CPlusPlus &&
7677 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7678 return Sema::IncompatiblePointer;
7679 return ConvTy;
7680 }
7681
7682 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7683 /// block pointer types are compatible or whether a block and normal pointer
7684 /// are compatible. It is more restrict than comparing two function pointer
7685 // types.
7686 static Sema::AssignConvertType
7687 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7688 QualType RHSType) {
7689 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7690 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7691
7692 QualType lhptee, rhptee;
7693
7694 // get the "pointed to" type (ignoring qualifiers at the top level)
7695 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7696 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7697
7698 // In C++, the types have to match exactly.
7699 if (S.getLangOpts().CPlusPlus)
7700 return Sema::IncompatibleBlockPointer;
7701
7702 Sema::AssignConvertType ConvTy = Sema::Compatible;
7703
7704 // For blocks we enforce that qualifiers are identical.
7705 Qualifiers LQuals = lhptee.getLocalQualifiers();
7706 Qualifiers RQuals = rhptee.getLocalQualifiers();
7707 if (S.getLangOpts().OpenCL) {
7708 LQuals.removeAddressSpace();
7709 RQuals.removeAddressSpace();
7710 }
7711 if (LQuals != RQuals)
7712 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7713
7714 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7715 // assignment.
7716 // The current behavior is similar to C++ lambdas. A block might be
7717 // assigned to a variable iff its return type and parameters are compatible
7718 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7719 // an assignment. Presumably it should behave in way that a function pointer
7720 // assignment does in C, so for each parameter and return type:
7721 // * CVR and address space of LHS should be a superset of CVR and address
7722 // space of RHS.
7723 // * unqualified types should be compatible.
7724 if (S.getLangOpts().OpenCL) {
7725 if (!S.Context.typesAreBlockPointerCompatible(
7726 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7727 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7728 return Sema::IncompatibleBlockPointer;
7729 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7730 return Sema::IncompatibleBlockPointer;
7731
7732 return ConvTy;
7733 }
7734
7735 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7736 /// for assignment compatibility.
7737 static Sema::AssignConvertType
7738 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7739 QualType RHSType) {
7740 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7741 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7742
7743 if (LHSType->isObjCBuiltinType()) {
7744 // Class is not compatible with ObjC object pointers.
7745 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7746 !RHSType->isObjCQualifiedClassType())
7747 return Sema::IncompatiblePointer;
7748 return Sema::Compatible;
7749 }
7750 if (RHSType->isObjCBuiltinType()) {
7751 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7752 !LHSType->isObjCQualifiedClassType())
7753 return Sema::IncompatiblePointer;
7754 return Sema::Compatible;
7755 }
7756 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7757 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7758
7759 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7760 // make an exception for id<P>
7761 !LHSType->isObjCQualifiedIdType())
7762 return Sema::CompatiblePointerDiscardsQualifiers;
7763
7764 if (S.Context.typesAreCompatible(LHSType, RHSType))
7765 return Sema::Compatible;
7766 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7767 return Sema::IncompatibleObjCQualifiedId;
7768 return Sema::IncompatiblePointer;
7769 }
7770
7771 Sema::AssignConvertType
7772 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7773 QualType LHSType, QualType RHSType) {
7774 // Fake up an opaque expression. We don't actually care about what
7775 // cast operations are required, so if CheckAssignmentConstraints
7776 // adds casts to this they'll be wasted, but fortunately that doesn't
7777 // usually happen on valid code.
7778 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7779 ExprResult RHSPtr = &RHSExpr;
7780 CastKind K;
7781
7782 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7783 }
7784
7785 /// This helper function returns true if QT is a vector type that has element
7786 /// type ElementType.
7787 static bool isVector(QualType QT, QualType ElementType) {
7788 if (const VectorType *VT = QT->getAs<VectorType>())
7789 return VT->getElementType() == ElementType;
7790 return false;
7791 }
7792
7793 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7794 /// has code to accommodate several GCC extensions when type checking
7795 /// pointers. Here are some objectionable examples that GCC considers warnings:
7796 ///
7797 /// int a, *pint;
7798 /// short *pshort;
7799 /// struct foo *pfoo;
7800 ///
7801 /// pint = pshort; // warning: assignment from incompatible pointer type
7802 /// a = pint; // warning: assignment makes integer from pointer without a cast
7803 /// pint = a; // warning: assignment makes pointer from integer without a cast
7804 /// pint = pfoo; // warning: assignment from incompatible pointer type
7805 ///
7806 /// As a result, the code for dealing with pointers is more complex than the
7807 /// C99 spec dictates.
7808 ///
7809 /// Sets 'Kind' for any result kind except Incompatible.
7810 Sema::AssignConvertType
7811 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7812 CastKind &Kind, bool ConvertRHS) {
7813 QualType RHSType = RHS.get()->getType();
7814 QualType OrigLHSType = LHSType;
7815
7816 // Get canonical types. We're not formatting these types, just comparing
7817 // them.
7818 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7819 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7820
7821 // Common case: no conversion required.
7822 if (LHSType == RHSType) {
7823 Kind = CK_NoOp;
7824 return Compatible;
7825 }
7826
7827 // If we have an atomic type, try a non-atomic assignment, then just add an
7828 // atomic qualification step.
7829 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7830 Sema::AssignConvertType result =
7831 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7832 if (result != Compatible)
7833 return result;
7834 if (Kind != CK_NoOp && ConvertRHS)
7835 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7836 Kind = CK_NonAtomicToAtomic;
7837 return Compatible;
7838 }
7839
7840 // If the left-hand side is a reference type, then we are in a
7841 // (rare!) case where we've allowed the use of references in C,
7842 // e.g., as a parameter type in a built-in function. In this case,
7843 // just make sure that the type referenced is compatible with the
7844 // right-hand side type. The caller is responsible for adjusting
7845 // LHSType so that the resulting expression does not have reference
7846 // type.
7847 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7848 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7849 Kind = CK_LValueBitCast;
7850 return Compatible;
7851 }
7852 return Incompatible;
7853 }
7854
7855 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7856 // to the same ExtVector type.
7857 if (LHSType->isExtVectorType()) {
7858 if (RHSType->isExtVectorType())
7859 return Incompatible;
7860 if (RHSType->isArithmeticType()) {
7861 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7862 if (ConvertRHS)
7863 RHS = prepareVectorSplat(LHSType, RHS.get());
7864 Kind = CK_VectorSplat;
7865 return Compatible;
7866 }
7867 }
7868
7869 // Conversions to or from vector type.
7870 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7871 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7872 // Allow assignments of an AltiVec vector type to an equivalent GCC
7873 // vector type and vice versa
7874 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7875 Kind = CK_BitCast;
7876 return Compatible;
7877 }
7878
7879 // If we are allowing lax vector conversions, and LHS and RHS are both
7880 // vectors, the total size only needs to be the same. This is a bitcast;
7881 // no bits are changed but the result type is different.
7882 if (isLaxVectorConversion(RHSType, LHSType)) {
7883 Kind = CK_BitCast;
7884 return IncompatibleVectors;
7885 }
7886 }
7887
7888 // When the RHS comes from another lax conversion (e.g. binops between
7889 // scalars and vectors) the result is canonicalized as a vector. When the
7890 // LHS is also a vector, the lax is allowed by the condition above. Handle
7891 // the case where LHS is a scalar.
7892 if (LHSType->isScalarType()) {
7893 const VectorType *VecType = RHSType->getAs<VectorType>();
7894 if (VecType && VecType->getNumElements() == 1 &&
7895 isLaxVectorConversion(RHSType, LHSType)) {
7896 ExprResult *VecExpr = &RHS;
7897 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7898 Kind = CK_BitCast;
7899 return Compatible;
7900 }
7901 }
7902
7903 return Incompatible;
7904 }
7905
7906 // Diagnose attempts to convert between __float128 and long double where
7907 // such conversions currently can't be handled.
7908 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7909 return Incompatible;
7910
7911 // Disallow assigning a _Complex to a real type in C++ mode since it simply
7912 // discards the imaginary part.
7913 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7914 !LHSType->getAs<ComplexType>())
7915 return Incompatible;
7916
7917 // Arithmetic conversions.
7918 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7919 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7920 if (ConvertRHS)
7921 Kind = PrepareScalarCast(RHS, LHSType);
7922 return Compatible;
7923 }
7924
7925 // Conversions to normal pointers.
7926 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7927 // U* -> T*
7928 if (isa<PointerType>(RHSType)) {
7929 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7930 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7931 if (AddrSpaceL != AddrSpaceR)
7932 Kind = CK_AddressSpaceConversion;
7933 else if (Context.hasCvrSimilarType(RHSType, LHSType))
7934 Kind = CK_NoOp;
7935 else
7936 Kind = CK_BitCast;
7937 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7938 }
7939
7940 // int -> T*
7941 if (RHSType->isIntegerType()) {
7942 Kind = CK_IntegralToPointer; // FIXME: null?
7943 return IntToPointer;
7944 }
7945
7946 // C pointers are not compatible with ObjC object pointers,
7947 // with two exceptions:
7948 if (isa<ObjCObjectPointerType>(RHSType)) {
7949 // - conversions to void*
7950 if (LHSPointer->getPointeeType()->isVoidType()) {
7951 Kind = CK_BitCast;
7952 return Compatible;
7953 }
7954
7955 // - conversions from 'Class' to the redefinition type
7956 if (RHSType->isObjCClassType() &&
7957 Context.hasSameType(LHSType,
7958 Context.getObjCClassRedefinitionType())) {
7959 Kind = CK_BitCast;
7960 return Compatible;
7961 }
7962
7963 Kind = CK_BitCast;
7964 return IncompatiblePointer;
7965 }
7966
7967 // U^ -> void*
7968 if (RHSType->getAs<BlockPointerType>()) {
7969 if (LHSPointer->getPointeeType()->isVoidType()) {
7970 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7971 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7972 ->getPointeeType()
7973 .getAddressSpace();
7974 Kind =
7975 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7976 return Compatible;
7977 }
7978 }
7979
7980 return Incompatible;
7981 }
7982
7983 // Conversions to block pointers.
7984 if (isa<BlockPointerType>(LHSType)) {
7985 // U^ -> T^
7986 if (RHSType->isBlockPointerType()) {
7987 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7988 ->getPointeeType()
7989 .getAddressSpace();
7990 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7991 ->getPointeeType()
7992 .getAddressSpace();
7993 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7994 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7995 }
7996
7997 // int or null -> T^
7998 if (RHSType->isIntegerType()) {
7999 Kind = CK_IntegralToPointer; // FIXME: null
8000 return IntToBlockPointer;
8001 }
8002
8003 // id -> T^
8004 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8005 Kind = CK_AnyPointerToBlockPointerCast;
8006 return Compatible;
8007 }
8008
8009 // void* -> T^
8010 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8011 if (RHSPT->getPointeeType()->isVoidType()) {
8012 Kind = CK_AnyPointerToBlockPointerCast;
8013 return Compatible;
8014 }
8015
8016 return Incompatible;
8017 }
8018
8019 // Conversions to Objective-C pointers.
8020 if (isa<ObjCObjectPointerType>(LHSType)) {
8021 // A* -> B*
8022 if (RHSType->isObjCObjectPointerType()) {
8023 Kind = CK_BitCast;
8024 Sema::AssignConvertType result =
8025 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8026 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8027 result == Compatible &&
8028 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8029 result = IncompatibleObjCWeakRef;
8030 return result;
8031 }
8032
8033 // int or null -> A*
8034 if (RHSType->isIntegerType()) {
8035 Kind = CK_IntegralToPointer; // FIXME: null
8036 return IntToPointer;
8037 }
8038
8039 // In general, C pointers are not compatible with ObjC object pointers,
8040 // with two exceptions:
8041 if (isa<PointerType>(RHSType)) {
8042 Kind = CK_CPointerToObjCPointerCast;
8043
8044 // - conversions from 'void*'
8045 if (RHSType->isVoidPointerType()) {
8046 return Compatible;
8047 }
8048
8049 // - conversions to 'Class' from its redefinition type
8050 if (LHSType->isObjCClassType() &&
8051 Context.hasSameType(RHSType,
8052 Context.getObjCClassRedefinitionType())) {
8053 return Compatible;
8054 }
8055
8056 return IncompatiblePointer;
8057 }
8058
8059 // Only under strict condition T^ is compatible with an Objective-C pointer.
8060 if (RHSType->isBlockPointerType() &&
8061 LHSType->isBlockCompatibleObjCPointerType(Context)) {
8062 if (ConvertRHS)
8063 maybeExtendBlockObject(RHS);
8064 Kind = CK_BlockPointerToObjCPointerCast;
8065 return Compatible;
8066 }
8067
8068 return Incompatible;
8069 }
8070
8071 // Conversions from pointers that are not covered by the above.
8072 if (isa<PointerType>(RHSType)) {
8073 // T* -> _Bool
8074 if (LHSType == Context.BoolTy) {
8075 Kind = CK_PointerToBoolean;
8076 return Compatible;
8077 }
8078
8079 // T* -> int
8080 if (LHSType->isIntegerType()) {
8081 Kind = CK_PointerToIntegral;
8082 return PointerToInt;
8083 }
8084
8085 return Incompatible;
8086 }
8087
8088 // Conversions from Objective-C pointers that are not covered by the above.
8089 if (isa<ObjCObjectPointerType>(RHSType)) {
8090 // T* -> _Bool
8091 if (LHSType == Context.BoolTy) {
8092 Kind = CK_PointerToBoolean;
8093 return Compatible;
8094 }
8095
8096 // T* -> int
8097 if (LHSType->isIntegerType()) {
8098 Kind = CK_PointerToIntegral;
8099 return PointerToInt;
8100 }
8101
8102 return Incompatible;
8103 }
8104
8105 // struct A -> struct B
8106 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8107 if (Context.typesAreCompatible(LHSType, RHSType)) {
8108 Kind = CK_NoOp;
8109 return Compatible;
8110 }
8111 }
8112
8113 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8114 Kind = CK_IntToOCLSampler;
8115 return Compatible;
8116 }
8117
8118 return Incompatible;
8119 }
8120
8121 /// Constructs a transparent union from an expression that is
8122 /// used to initialize the transparent union.
8123 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8124 ExprResult &EResult, QualType UnionType,
8125 FieldDecl *Field) {
8126 // Build an initializer list that designates the appropriate member
8127 // of the transparent union.
8128 Expr *E = EResult.get();
8129 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8130 E, SourceLocation());
8131 Initializer->setType(UnionType);
8132 Initializer->setInitializedFieldInUnion(Field);
8133
8134 // Build a compound literal constructing a value of the transparent
8135 // union type from this initializer list.
8136 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8137 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8138 VK_RValue, Initializer, false);
8139 }
8140
8141 Sema::AssignConvertType
8142 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8143 ExprResult &RHS) {
8144 QualType RHSType = RHS.get()->getType();
8145
8146 // If the ArgType is a Union type, we want to handle a potential
8147 // transparent_union GCC extension.
8148 const RecordType *UT = ArgType->getAsUnionType();
8149 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8150 return Incompatible;
8151
8152 // The field to initialize within the transparent union.
8153 RecordDecl *UD = UT->getDecl();
8154 FieldDecl *InitField = nullptr;
8155 // It's compatible if the expression matches any of the fields.
8156 for (auto *it : UD->fields()) {
8157 if (it->getType()->isPointerType()) {
8158 // If the transparent union contains a pointer type, we allow:
8159 // 1) void pointer
8160 // 2) null pointer constant
8161 if (RHSType->isPointerType())
8162 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8163 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8164 InitField = it;
8165 break;
8166 }
8167
8168 if (RHS.get()->isNullPointerConstant(Context,
8169 Expr::NPC_ValueDependentIsNull)) {
8170 RHS = ImpCastExprToType(RHS.get(), it->getType(),
8171 CK_NullToPointer);
8172 InitField = it;
8173 break;
8174 }
8175 }
8176
8177 CastKind Kind;
8178 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8179 == Compatible) {
8180 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8181 InitField = it;
8182 break;
8183 }
8184 }
8185
8186 if (!InitField)
8187 return Incompatible;
8188
8189 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8190 return Compatible;
8191 }
8192
8193 Sema::AssignConvertType
8194 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8195 bool Diagnose,
8196 bool DiagnoseCFAudited,
8197 bool ConvertRHS) {
8198 // We need to be able to tell the caller whether we diagnosed a problem, if
8199 // they ask us to issue diagnostics.
8200 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8201
8202 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8203 // we can't avoid *all* modifications at the moment, so we need some somewhere
8204 // to put the updated value.
8205 ExprResult LocalRHS = CallerRHS;
8206 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8207
8208 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8209 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8210 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8211 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8212 Diag(RHS.get()->getExprLoc(),
8213 diag::warn_noderef_to_dereferenceable_pointer)
8214 << RHS.get()->getSourceRange();
8215 }
8216 }
8217 }
8218
8219 if (getLangOpts().CPlusPlus) {
8220 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8221 // C++ 5.17p3: If the left operand is not of class type, the
8222 // expression is implicitly converted (C++ 4) to the
8223 // cv-unqualified type of the left operand.
8224 QualType RHSType = RHS.get()->getType();
8225 if (Diagnose) {
8226 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8227 AA_Assigning);
8228 } else {
8229 ImplicitConversionSequence ICS =
8230 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8231 /*SuppressUserConversions=*/false,
8232 /*AllowExplicit=*/false,
8233 /*InOverloadResolution=*/false,
8234 /*CStyle=*/false,
8235 /*AllowObjCWritebackConversion=*/false);
8236 if (ICS.isFailure())
8237 return Incompatible;
8238 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8239 ICS, AA_Assigning);
8240 }
8241 if (RHS.isInvalid())
8242 return Incompatible;
8243 Sema::AssignConvertType result = Compatible;
8244 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8245 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8246 result = IncompatibleObjCWeakRef;
8247 return result;
8248 }
8249
8250 // FIXME: Currently, we fall through and treat C++ classes like C
8251 // structures.
8252 // FIXME: We also fall through for atomics; not sure what should
8253 // happen there, though.
8254 } else if (RHS.get()->getType() == Context.OverloadTy) {
8255 // As a set of extensions to C, we support overloading on functions. These
8256 // functions need to be resolved here.
8257 DeclAccessPair DAP;
8258 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8259 RHS.get(), LHSType, /*Complain=*/false, DAP))
8260 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8261 else
8262 return Incompatible;
8263 }
8264
8265 // C99 6.5.16.1p1: the left operand is a pointer and the right is
8266 // a null pointer constant.
8267 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8268 LHSType->isBlockPointerType()) &&
8269 RHS.get()->isNullPointerConstant(Context,
8270 Expr::NPC_ValueDependentIsNull)) {
8271 if (Diagnose || ConvertRHS) {
8272 CastKind Kind;
8273 CXXCastPath Path;
8274 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8275 /*IgnoreBaseAccess=*/false, Diagnose);
8276 if (ConvertRHS)
8277 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8278 }
8279 return Compatible;
8280 }
8281
8282 // OpenCL queue_t type assignment.
8283 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8284 Context, Expr::NPC_ValueDependentIsNull)) {
8285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8286 return Compatible;
8287 }
8288
8289 // This check seems unnatural, however it is necessary to ensure the proper
8290 // conversion of functions/arrays. If the conversion were done for all
8291 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8292 // expressions that suppress this implicit conversion (&, sizeof).
8293 //
8294 // Suppress this for references: C++ 8.5.3p5.
8295 if (!LHSType->isReferenceType()) {
8296 // FIXME: We potentially allocate here even if ConvertRHS is false.
8297 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8298 if (RHS.isInvalid())
8299 return Incompatible;
8300 }
8301 CastKind Kind;
8302 Sema::AssignConvertType result =
8303 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8304
8305 // C99 6.5.16.1p2: The value of the right operand is converted to the
8306 // type of the assignment expression.
8307 // CheckAssignmentConstraints allows the left-hand side to be a reference,
8308 // so that we can use references in built-in functions even in C.
8309 // The getNonReferenceType() call makes sure that the resulting expression
8310 // does not have reference type.
8311 if (result != Incompatible && RHS.get()->getType() != LHSType) {
8312 QualType Ty = LHSType.getNonLValueExprType(Context);
8313 Expr *E = RHS.get();
8314
8315 // Check for various Objective-C errors. If we are not reporting
8316 // diagnostics and just checking for errors, e.g., during overload
8317 // resolution, return Incompatible to indicate the failure.
8318 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8319 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8320 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8321 if (!Diagnose)
8322 return Incompatible;
8323 }
8324 if (getLangOpts().ObjC &&
8325 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8326 E->getType(), E, Diagnose) ||
8327 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8328 if (!Diagnose)
8329 return Incompatible;
8330 // Replace the expression with a corrected version and continue so we
8331 // can find further errors.
8332 RHS = E;
8333 return Compatible;
8334 }
8335
8336 if (ConvertRHS)
8337 RHS = ImpCastExprToType(E, Ty, Kind);
8338 }
8339
8340 return result;
8341 }
8342
8343 namespace {
8344 /// The original operand to an operator, prior to the application of the usual
8345 /// arithmetic conversions and converting the arguments of a builtin operator
8346 /// candidate.
8347 struct OriginalOperand {
8348 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8349 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8350 Op = MTE->GetTemporaryExpr();
8351 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8352 Op = BTE->getSubExpr();
8353 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8354 Orig = ICE->getSubExprAsWritten();
8355 Conversion = ICE->getConversionFunction();
8356 }
8357 }
8358
8359 QualType getType() const { return Orig->getType(); }
8360
8361 Expr *Orig;
8362 NamedDecl *Conversion;
8363 };
8364 }
8365
8366 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8367 ExprResult &RHS) {
8368 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8369
8370 Diag(Loc, diag::err_typecheck_invalid_operands)
8371 << OrigLHS.getType() << OrigRHS.getType()
8372 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8373
8374 // If a user-defined conversion was applied to either of the operands prior
8375 // to applying the built-in operator rules, tell the user about it.
8376 if (OrigLHS.Conversion) {
8377 Diag(OrigLHS.Conversion->getLocation(),
8378 diag::note_typecheck_invalid_operands_converted)
8379 << 0 << LHS.get()->getType();
8380 }
8381 if (OrigRHS.Conversion) {
8382 Diag(OrigRHS.Conversion->getLocation(),
8383 diag::note_typecheck_invalid_operands_converted)
8384 << 1 << RHS.get()->getType();
8385 }
8386
8387 return QualType();
8388 }
8389
8390 // Diagnose cases where a scalar was implicitly converted to a vector and
8391 // diagnose the underlying types. Otherwise, diagnose the error
8392 // as invalid vector logical operands for non-C++ cases.
8393 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8394 ExprResult &RHS) {
8395 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8396 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8397
8398 bool LHSNatVec = LHSType->isVectorType();
8399 bool RHSNatVec = RHSType->isVectorType();
8400
8401 if (!(LHSNatVec && RHSNatVec)) {
8402 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8403 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8404 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8405 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8406 << Vector->getSourceRange();
8407 return QualType();
8408 }
8409
8410 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8411 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8412 << RHS.get()->getSourceRange();
8413
8414 return QualType();
8415 }
8416
8417 /// Try to convert a value of non-vector type to a vector type by converting
8418 /// the type to the element type of the vector and then performing a splat.
8419 /// If the language is OpenCL, we only use conversions that promote scalar
8420 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8421 /// for float->int.
8422 ///
8423 /// OpenCL V2.0 6.2.6.p2:
8424 /// An error shall occur if any scalar operand type has greater rank
8425 /// than the type of the vector element.
8426 ///
8427 /// \param scalar - if non-null, actually perform the conversions
8428 /// \return true if the operation fails (but without diagnosing the failure)
8429 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8430 QualType scalarTy,
8431 QualType vectorEltTy,
8432 QualType vectorTy,
8433 unsigned &DiagID) {
8434 // The conversion to apply to the scalar before splatting it,
8435 // if necessary.
8436 CastKind scalarCast = CK_NoOp;
8437
8438 if (vectorEltTy->isIntegralType(S.Context)) {
8439 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8440 (scalarTy->isIntegerType() &&
8441 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8442 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8443 return true;
8444 }
8445 if (!scalarTy->isIntegralType(S.Context))
8446 return true;
8447 scalarCast = CK_IntegralCast;
8448 } else if (vectorEltTy->isRealFloatingType()) {
8449 if (scalarTy->isRealFloatingType()) {
8450 if (S.getLangOpts().OpenCL &&
8451 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8452 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8453 return true;
8454 }
8455 scalarCast = CK_FloatingCast;
8456 }
8457 else if (scalarTy->isIntegralType(S.Context))
8458 scalarCast = CK_IntegralToFloating;
8459 else
8460 return true;
8461 } else {
8462 return true;
8463 }
8464
8465 // Adjust scalar if desired.
8466 if (scalar) {
8467 if (scalarCast != CK_NoOp)
8468 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8469 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8470 }
8471 return false;
8472 }
8473
8474 /// Convert vector E to a vector with the same number of elements but different
8475 /// element type.
8476 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8477 const auto *VecTy = E->getType()->getAs<VectorType>();
8478 assert(VecTy && "Expression E must be a vector");
8479 QualType NewVecTy = S.Context.getVectorType(ElementType,
8480 VecTy->getNumElements(),
8481 VecTy->getVectorKind());
8482
8483 // Look through the implicit cast. Return the subexpression if its type is
8484 // NewVecTy.
8485 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8486 if (ICE->getSubExpr()->getType() == NewVecTy)
8487 return ICE->getSubExpr();
8488
8489 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8490 return S.ImpCastExprToType(E, NewVecTy, Cast);
8491 }
8492
8493 /// Test if a (constant) integer Int can be casted to another integer type
8494 /// IntTy without losing precision.
8495 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8496 QualType OtherIntTy) {
8497 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8498
8499 // Reject cases where the value of the Int is unknown as that would
8500 // possibly cause truncation, but accept cases where the scalar can be
8501 // demoted without loss of precision.
8502 Expr::EvalResult EVResult;
8503 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8504 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8505 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8506 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8507
8508 if (CstInt) {
8509 // If the scalar is constant and is of a higher order and has more active
8510 // bits that the vector element type, reject it.
8511 llvm::APSInt Result = EVResult.Val.getInt();
8512 unsigned NumBits = IntSigned
8513 ? (Result.isNegative() ? Result.getMinSignedBits()
8514 : Result.getActiveBits())
8515 : Result.getActiveBits();
8516 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8517 return true;
8518
8519 // If the signedness of the scalar type and the vector element type
8520 // differs and the number of bits is greater than that of the vector
8521 // element reject it.
8522 return (IntSigned != OtherIntSigned &&
8523 NumBits > S.Context.getIntWidth(OtherIntTy));
8524 }
8525
8526 // Reject cases where the value of the scalar is not constant and it's
8527 // order is greater than that of the vector element type.
8528 return (Order < 0);
8529 }
8530
8531 /// Test if a (constant) integer Int can be casted to floating point type
8532 /// FloatTy without losing precision.
8533 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8534 QualType FloatTy) {
8535 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8536
8537 // Determine if the integer constant can be expressed as a floating point
8538 // number of the appropriate type.
8539 Expr::EvalResult EVResult;
8540 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8541
8542 uint64_t Bits = 0;
8543 if (CstInt) {
8544 // Reject constants that would be truncated if they were converted to
8545 // the floating point type. Test by simple to/from conversion.
8546 // FIXME: Ideally the conversion to an APFloat and from an APFloat
8547 // could be avoided if there was a convertFromAPInt method
8548 // which could signal back if implicit truncation occurred.
8549 llvm::APSInt Result = EVResult.Val.getInt();
8550 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8551 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8552 llvm::APFloat::rmTowardZero);
8553 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8554 !IntTy->hasSignedIntegerRepresentation());
8555 bool Ignored = false;
8556 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8557 &Ignored);
8558 if (Result != ConvertBack)
8559 return true;
8560 } else {
8561 // Reject types that cannot be fully encoded into the mantissa of
8562 // the float.
8563 Bits = S.Context.getTypeSize(IntTy);
8564 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8565 S.Context.getFloatTypeSemantics(FloatTy));
8566 if (Bits > FloatPrec)
8567 return true;
8568 }
8569
8570 return false;
8571 }
8572
8573 /// Attempt to convert and splat Scalar into a vector whose types matches
8574 /// Vector following GCC conversion rules. The rule is that implicit
8575 /// conversion can occur when Scalar can be casted to match Vector's element
8576 /// type without causing truncation of Scalar.
8577 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8578 ExprResult *Vector) {
8579 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8580 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8581 const VectorType *VT = VectorTy->getAs<VectorType>();
8582
8583 assert(!isa<ExtVectorType>(VT) &&
8584 "ExtVectorTypes should not be handled here!");
8585
8586 QualType VectorEltTy = VT->getElementType();
8587
8588 // Reject cases where the vector element type or the scalar element type are
8589 // not integral or floating point types.
8590 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8591 return true;
8592
8593 // The conversion to apply to the scalar before splatting it,
8594 // if necessary.
8595 CastKind ScalarCast = CK_NoOp;
8596
8597 // Accept cases where the vector elements are integers and the scalar is
8598 // an integer.
8599 // FIXME: Notionally if the scalar was a floating point value with a precise
8600 // integral representation, we could cast it to an appropriate integer
8601 // type and then perform the rest of the checks here. GCC will perform
8602 // this conversion in some cases as determined by the input language.
8603 // We should accept it on a language independent basis.
8604 if (VectorEltTy->isIntegralType(S.Context) &&
8605 ScalarTy->isIntegralType(S.Context) &&
8606 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8607
8608 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8609 return true;
8610
8611 ScalarCast = CK_IntegralCast;
8612 } else if (VectorEltTy->isRealFloatingType()) {
8613 if (ScalarTy->isRealFloatingType()) {
8614
8615 // Reject cases where the scalar type is not a constant and has a higher
8616 // Order than the vector element type.
8617 llvm::APFloat Result(0.0);
8618 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8619 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8620 if (!CstScalar && Order < 0)
8621 return true;
8622
8623 // If the scalar cannot be safely casted to the vector element type,
8624 // reject it.
8625 if (CstScalar) {
8626 bool Truncated = false;
8627 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8628 llvm::APFloat::rmNearestTiesToEven, &Truncated);
8629 if (Truncated)
8630 return true;
8631 }
8632
8633 ScalarCast = CK_FloatingCast;
8634 } else if (ScalarTy->isIntegralType(S.Context)) {
8635 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8636 return true;
8637
8638 ScalarCast = CK_IntegralToFloating;
8639 } else
8640 return true;
8641 }
8642
8643 // Adjust scalar if desired.
8644 if (Scalar) {
8645 if (ScalarCast != CK_NoOp)
8646 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8647 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8648 }
8649 return false;
8650 }
8651
8652 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8653 SourceLocation Loc, bool IsCompAssign,
8654 bool AllowBothBool,
8655 bool AllowBoolConversions) {
8656 if (!IsCompAssign) {
8657 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8658 if (LHS.isInvalid())
8659 return QualType();
8660 }
8661 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8662 if (RHS.isInvalid())
8663 return QualType();
8664
8665 // For conversion purposes, we ignore any qualifiers.
8666 // For example, "const float" and "float" are equivalent.
8667 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8668 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8669
8670 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8671 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8672 assert(LHSVecType || RHSVecType);
8673
8674 // AltiVec-style "vector bool op vector bool" combinations are allowed
8675 // for some operators but not others.
8676 if (!AllowBothBool &&
8677 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8678 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8679 return InvalidOperands(Loc, LHS, RHS);
8680
8681 // If the vector types are identical, return.
8682 if (Context.hasSameType(LHSType, RHSType))
8683 return LHSType;
8684
8685 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8686 if (LHSVecType && RHSVecType &&
8687 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8688 if (isa<ExtVectorType>(LHSVecType)) {
8689 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8690 return LHSType;
8691 }
8692
8693 if (!IsCompAssign)
8694 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8695 return RHSType;
8696 }
8697
8698 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8699 // can be mixed, with the result being the non-bool type. The non-bool
8700 // operand must have integer element type.
8701 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8702 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8703 (Context.getTypeSize(LHSVecType->getElementType()) ==
8704 Context.getTypeSize(RHSVecType->getElementType()))) {
8705 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8706 LHSVecType->getElementType()->isIntegerType() &&
8707 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8708 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8709 return LHSType;
8710 }
8711 if (!IsCompAssign &&
8712 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8713 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8714 RHSVecType->getElementType()->isIntegerType()) {
8715 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8716 return RHSType;
8717 }
8718 }
8719
8720 // If there's a vector type and a scalar, try to convert the scalar to
8721 // the vector element type and splat.
8722 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8723 if (!RHSVecType) {
8724 if (isa<ExtVectorType>(LHSVecType)) {
8725 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8726 LHSVecType->getElementType(), LHSType,
8727 DiagID))
8728 return LHSType;
8729 } else {
8730 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8731 return LHSType;
8732 }
8733 }
8734 if (!LHSVecType) {
8735 if (isa<ExtVectorType>(RHSVecType)) {
8736 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8737 LHSType, RHSVecType->getElementType(),
8738 RHSType, DiagID))
8739 return RHSType;
8740 } else {
8741 if (LHS.get()->getValueKind() == VK_LValue ||
8742 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8743 return RHSType;
8744 }
8745 }
8746
8747 // FIXME: The code below also handles conversion between vectors and
8748 // non-scalars, we should break this down into fine grained specific checks
8749 // and emit proper diagnostics.
8750 QualType VecType = LHSVecType ? LHSType : RHSType;
8751 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8752 QualType OtherType = LHSVecType ? RHSType : LHSType;
8753 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8754 if (isLaxVectorConversion(OtherType, VecType)) {
8755 // If we're allowing lax vector conversions, only the total (data) size
8756 // needs to be the same. For non compound assignment, if one of the types is
8757 // scalar, the result is always the vector type.
8758 if (!IsCompAssign) {
8759 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8760 return VecType;
8761 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8762 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8763 // type. Note that this is already done by non-compound assignments in
8764 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8765 // <1 x T> -> T. The result is also a vector type.
8766 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8767 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8768 ExprResult *RHSExpr = &RHS;
8769 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8770 return VecType;
8771 }
8772 }
8773
8774 // Okay, the expression is invalid.
8775
8776 // If there's a non-vector, non-real operand, diagnose that.
8777 if ((!RHSVecType && !RHSType->isRealType()) ||
8778 (!LHSVecType && !LHSType->isRealType())) {
8779 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8780 << LHSType << RHSType
8781 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8782 return QualType();
8783 }
8784
8785 // OpenCL V1.1 6.2.6.p1:
8786 // If the operands are of more than one vector type, then an error shall
8787 // occur. Implicit conversions between vector types are not permitted, per
8788 // section 6.2.1.
8789 if (getLangOpts().OpenCL &&
8790 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8791 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8792 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8793 << RHSType;
8794 return QualType();
8795 }
8796
8797
8798 // If there is a vector type that is not a ExtVector and a scalar, we reach
8799 // this point if scalar could not be converted to the vector's element type
8800 // without truncation.
8801 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8802 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8803 QualType Scalar = LHSVecType ? RHSType : LHSType;
8804 QualType Vector = LHSVecType ? LHSType : RHSType;
8805 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8806 Diag(Loc,
8807 diag::err_typecheck_vector_not_convertable_implict_truncation)
8808 << ScalarOrVector << Scalar << Vector;
8809
8810 return QualType();
8811 }
8812
8813 // Otherwise, use the generic diagnostic.
8814 Diag(Loc, DiagID)
8815 << LHSType << RHSType
8816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8817 return QualType();
8818 }
8819
8820 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8821 // expression. These are mainly cases where the null pointer is used as an
8822 // integer instead of a pointer.
8823 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8824 SourceLocation Loc, bool IsCompare) {
8825 // The canonical way to check for a GNU null is with isNullPointerConstant,
8826 // but we use a bit of a hack here for speed; this is a relatively
8827 // hot path, and isNullPointerConstant is slow.
8828 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8829 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8830
8831 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8832
8833 // Avoid analyzing cases where the result will either be invalid (and
8834 // diagnosed as such) or entirely valid and not something to warn about.
8835 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8836 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8837 return;
8838
8839 // Comparison operations would not make sense with a null pointer no matter
8840 // what the other expression is.
8841 if (!IsCompare) {
8842 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8843 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8844 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8845 return;
8846 }
8847
8848 // The rest of the operations only make sense with a null pointer
8849 // if the other expression is a pointer.
8850 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8851 NonNullType->canDecayToPointerType())
8852 return;
8853
8854 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8855 << LHSNull /* LHS is NULL */ << NonNullType
8856 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8857 }
8858
8859 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8860 SourceLocation Loc) {
8861 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8862 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8863 if (!LUE || !RUE)
8864 return;
8865 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8866 RUE->getKind() != UETT_SizeOf)
8867 return;
8868
8869 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8870 QualType RHSTy;
8871
8872 if (RUE->isArgumentType())
8873 RHSTy = RUE->getArgumentType();
8874 else
8875 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
8876
8877 if (!LHSTy->isPointerType() || RHSTy->isPointerType())
8878 return;
8879 if (LHSTy->getPointeeType() != RHSTy)
8880 return;
8881
8882 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
8883 }
8884
8885 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8886 ExprResult &RHS,
8887 SourceLocation Loc, bool IsDiv) {
8888 // Check for division/remainder by zero.
8889 Expr::EvalResult RHSValue;
8890 if (!RHS.get()->isValueDependent() &&
8891 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
8892 RHSValue.Val.getInt() == 0)
8893 S.DiagRuntimeBehavior(Loc, RHS.get(),
8894 S.PDiag(diag::warn_remainder_division_by_zero)
8895 << IsDiv << RHS.get()->getSourceRange());
8896 }
8897
8898 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8899 SourceLocation Loc,
8900 bool IsCompAssign, bool IsDiv) {
8901 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8902
8903 if (LHS.get()->getType()->isVectorType() ||
8904 RHS.get()->getType()->isVectorType())
8905 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8906 /*AllowBothBool*/getLangOpts().AltiVec,
8907 /*AllowBoolConversions*/false);
8908
8909 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8910 if (LHS.isInvalid() || RHS.isInvalid())
8911 return QualType();
8912
8913
8914 if (compType.isNull() || !compType->isArithmeticType())
8915 return InvalidOperands(Loc, LHS, RHS);
8916 if (IsDiv) {
8917 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8918 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
8919 }
8920 return compType;
8921 }
8922
8923 QualType Sema::CheckRemainderOperands(
8924 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8925 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8926
8927 if (LHS.get()->getType()->isVectorType() ||
8928 RHS.get()->getType()->isVectorType()) {
8929 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8930 RHS.get()->getType()->hasIntegerRepresentation())
8931 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8932 /*AllowBothBool*/getLangOpts().AltiVec,
8933 /*AllowBoolConversions*/false);
8934 return InvalidOperands(Loc, LHS, RHS);
8935 }
8936
8937 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8938 if (LHS.isInvalid() || RHS.isInvalid())
8939 return QualType();
8940
8941 if (compType.isNull() || !compType->isIntegerType())
8942 return InvalidOperands(Loc, LHS, RHS);
8943 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8944 return compType;
8945 }
8946
8947 /// Diagnose invalid arithmetic on two void pointers.
8948 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8949 Expr *LHSExpr, Expr *RHSExpr) {
8950 S.Diag(Loc, S.getLangOpts().CPlusPlus
8951 ? diag::err_typecheck_pointer_arith_void_type
8952 : diag::ext_gnu_void_ptr)
8953 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8954 << RHSExpr->getSourceRange();
8955 }
8956
8957 /// Diagnose invalid arithmetic on a void pointer.
8958 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8959 Expr *Pointer) {
8960 S.Diag(Loc, S.getLangOpts().CPlusPlus
8961 ? diag::err_typecheck_pointer_arith_void_type
8962 : diag::ext_gnu_void_ptr)
8963 << 0 /* one pointer */ << Pointer->getSourceRange();
8964 }
8965
8966 /// Diagnose invalid arithmetic on a null pointer.
8967 ///
8968 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8969 /// idiom, which we recognize as a GNU extension.
8970 ///
8971 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8972 Expr *Pointer, bool IsGNUIdiom) {
8973 if (IsGNUIdiom)
8974 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8975 << Pointer->getSourceRange();
8976 else
8977 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8978 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8979 }
8980
8981 /// Diagnose invalid arithmetic on two function pointers.
8982 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8983 Expr *LHS, Expr *RHS) {
8984 assert(LHS->getType()->isAnyPointerType());
8985 assert(RHS->getType()->isAnyPointerType());
8986 S.Diag(Loc, S.getLangOpts().CPlusPlus
8987 ? diag::err_typecheck_pointer_arith_function_type
8988 : diag::ext_gnu_ptr_func_arith)
8989 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8990 // We only show the second type if it differs from the first.
8991 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8992 RHS->getType())
8993 << RHS->getType()->getPointeeType()
8994 << LHS->getSourceRange() << RHS->getSourceRange();
8995 }
8996
8997 /// Diagnose invalid arithmetic on a function pointer.
8998 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8999 Expr *Pointer) {
9000 assert(Pointer->getType()->isAnyPointerType());
9001 S.Diag(Loc, S.getLangOpts().CPlusPlus
9002 ? diag::err_typecheck_pointer_arith_function_type
9003 : diag::ext_gnu_ptr_func_arith)
9004 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9005 << 0 /* one pointer, so only one type */
9006 << Pointer->getSourceRange();
9007 }
9008
9009 /// Emit error if Operand is incomplete pointer type
9010 ///
9011 /// \returns True if pointer has incomplete type
9012 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9013 Expr *Operand) {
9014 QualType ResType = Operand->getType();
9015 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9016 ResType = ResAtomicType->getValueType();
9017
9018 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9019 QualType PointeeTy = ResType->getPointeeType();
9020 return S.RequireCompleteType(Loc, PointeeTy,
9021 diag::err_typecheck_arithmetic_incomplete_type,
9022 PointeeTy, Operand->getSourceRange());
9023 }
9024
9025 /// Check the validity of an arithmetic pointer operand.
9026 ///
9027 /// If the operand has pointer type, this code will check for pointer types
9028 /// which are invalid in arithmetic operations. These will be diagnosed
9029 /// appropriately, including whether or not the use is supported as an
9030 /// extension.
9031 ///
9032 /// \returns True when the operand is valid to use (even if as an extension).
9033 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9034 Expr *Operand) {
9035 QualType ResType = Operand->getType();
9036 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9037 ResType = ResAtomicType->getValueType();
9038
9039 if (!ResType->isAnyPointerType()) return true;
9040
9041 QualType PointeeTy = ResType->getPointeeType();
9042 if (PointeeTy->isVoidType()) {
9043 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9044 return !S.getLangOpts().CPlusPlus;
9045 }
9046 if (PointeeTy->isFunctionType()) {
9047 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9048 return !S.getLangOpts().CPlusPlus;
9049 }
9050
9051 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9052
9053 return true;
9054 }
9055
9056 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9057 /// operands.
9058 ///
9059 /// This routine will diagnose any invalid arithmetic on pointer operands much
9060 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9061 /// for emitting a single diagnostic even for operations where both LHS and RHS
9062 /// are (potentially problematic) pointers.
9063 ///
9064 /// \returns True when the operand is valid to use (even if as an extension).
9065 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9066 Expr *LHSExpr, Expr *RHSExpr) {
9067 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9068 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9069 if (!isLHSPointer && !isRHSPointer) return true;
9070
9071 QualType LHSPointeeTy, RHSPointeeTy;
9072 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9073 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9074
9075 // if both are pointers check if operation is valid wrt address spaces
9076 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9077 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9078 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9079 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9080 S.Diag(Loc,
9081 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9082 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9083 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9084 return false;
9085 }
9086 }
9087
9088 // Check for arithmetic on pointers to incomplete types.
9089 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9090 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9091 if (isLHSVoidPtr || isRHSVoidPtr) {
9092 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9093 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9094 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9095
9096 return !S.getLangOpts().CPlusPlus;
9097 }
9098
9099 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9100 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9101 if (isLHSFuncPtr || isRHSFuncPtr) {
9102 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9103 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9104 RHSExpr);
9105 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9106
9107 return !S.getLangOpts().CPlusPlus;
9108 }
9109
9110 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9111 return false;
9112 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9113 return false;
9114
9115 return true;
9116 }
9117
9118 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9119 /// literal.
9120 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9121 Expr *LHSExpr, Expr *RHSExpr) {
9122 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9123 Expr* IndexExpr = RHSExpr;
9124 if (!StrExpr) {
9125 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9126 IndexExpr = LHSExpr;
9127 }
9128
9129 bool IsStringPlusInt = StrExpr &&
9130 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9131 if (!IsStringPlusInt || IndexExpr->isValueDependent())
9132 return;
9133
9134 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9135 Self.Diag(OpLoc, diag::warn_string_plus_int)
9136 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9137
9138 // Only print a fixit for "str" + int, not for int + "str".
9139 if (IndexExpr == RHSExpr) {
9140 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9141 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9142 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9143 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9144 << FixItHint::CreateInsertion(EndLoc, "]");
9145 } else
9146 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9147 }
9148
9149 /// Emit a warning when adding a char literal to a string.
9150 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9151 Expr *LHSExpr, Expr *RHSExpr) {
9152 const Expr *StringRefExpr = LHSExpr;
9153 const CharacterLiteral *CharExpr =
9154 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9155
9156 if (!CharExpr) {
9157 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9158 StringRefExpr = RHSExpr;
9159 }
9160
9161 if (!CharExpr || !StringRefExpr)
9162 return;
9163
9164 const QualType StringType = StringRefExpr->getType();
9165
9166 // Return if not a PointerType.
9167 if (!StringType->isAnyPointerType())
9168 return;
9169
9170 // Return if not a CharacterType.
9171 if (!StringType->getPointeeType()->isAnyCharacterType())
9172 return;
9173
9174 ASTContext &Ctx = Self.getASTContext();
9175 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9176
9177 const QualType CharType = CharExpr->getType();
9178 if (!CharType->isAnyCharacterType() &&
9179 CharType->isIntegerType() &&
9180 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9181 Self.Diag(OpLoc, diag::warn_string_plus_char)
9182 << DiagRange << Ctx.CharTy;
9183 } else {
9184 Self.Diag(OpLoc, diag::warn_string_plus_char)
9185 << DiagRange << CharExpr->getType();
9186 }
9187
9188 // Only print a fixit for str + char, not for char + str.
9189 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9190 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9191 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9192 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9193 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9194 << FixItHint::CreateInsertion(EndLoc, "]");
9195 } else {
9196 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9197 }
9198 }
9199
9200 /// Emit error when two pointers are incompatible.
9201 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9202 Expr *LHSExpr, Expr *RHSExpr) {
9203 assert(LHSExpr->getType()->isAnyPointerType());
9204 assert(RHSExpr->getType()->isAnyPointerType());
9205 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9206 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9207 << RHSExpr->getSourceRange();
9208 }
9209
9210 // C99 6.5.6
9211 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9212 SourceLocation Loc, BinaryOperatorKind Opc,
9213 QualType* CompLHSTy) {
9214 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9215
9216 if (LHS.get()->getType()->isVectorType() ||
9217 RHS.get()->getType()->isVectorType()) {
9218 QualType compType = CheckVectorOperands(
9219 LHS, RHS, Loc, CompLHSTy,
9220 /*AllowBothBool*/getLangOpts().AltiVec,
9221 /*AllowBoolConversions*/getLangOpts().ZVector);
9222 if (CompLHSTy) *CompLHSTy = compType;
9223 return compType;
9224 }
9225
9226 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9227 if (LHS.isInvalid() || RHS.isInvalid())
9228 return QualType();
9229
9230 // Diagnose "string literal" '+' int and string '+' "char literal".
9231 if (Opc == BO_Add) {
9232 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9233 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9234 }
9235
9236 // handle the common case first (both operands are arithmetic).
9237 if (!compType.isNull() && compType->isArithmeticType()) {
9238 if (CompLHSTy) *CompLHSTy = compType;
9239 return compType;
9240 }
9241
9242 // Type-checking. Ultimately the pointer's going to be in PExp;
9243 // note that we bias towards the LHS being the pointer.
9244 Expr *PExp = LHS.get(), *IExp = RHS.get();
9245
9246 bool isObjCPointer;
9247 if (PExp->getType()->isPointerType()) {
9248 isObjCPointer = false;
9249 } else if (PExp->getType()->isObjCObjectPointerType()) {
9250 isObjCPointer = true;
9251 } else {
9252 std::swap(PExp, IExp);
9253 if (PExp->getType()->isPointerType()) {
9254 isObjCPointer = false;
9255 } else if (PExp->getType()->isObjCObjectPointerType()) {
9256 isObjCPointer = true;
9257 } else {
9258 return InvalidOperands(Loc, LHS, RHS);
9259 }
9260 }
9261 assert(PExp->getType()->isAnyPointerType());
9262
9263 if (!IExp->getType()->isIntegerType())
9264 return InvalidOperands(Loc, LHS, RHS);
9265
9266 // Adding to a null pointer results in undefined behavior.
9267 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9268 Context, Expr::NPC_ValueDependentIsNotNull)) {
9269 // In C++ adding zero to a null pointer is defined.
9270 Expr::EvalResult KnownVal;
9271 if (!getLangOpts().CPlusPlus ||
9272 (!IExp->isValueDependent() &&
9273 (!IExp->EvaluateAsInt(KnownVal, Context) ||
9274 KnownVal.Val.getInt() != 0))) {
9275 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9276 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9277 Context, BO_Add, PExp, IExp);
9278 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9279 }
9280 }
9281
9282 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9283 return QualType();
9284
9285 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9286 return QualType();
9287
9288 // Check array bounds for pointer arithemtic
9289 CheckArrayAccess(PExp, IExp);
9290
9291 if (CompLHSTy) {
9292 QualType LHSTy = Context.isPromotableBitField(LHS.get());
9293 if (LHSTy.isNull()) {
9294 LHSTy = LHS.get()->getType();
9295 if (LHSTy->isPromotableIntegerType())
9296 LHSTy = Context.getPromotedIntegerType(LHSTy);
9297 }
9298 *CompLHSTy = LHSTy;
9299 }
9300
9301 return PExp->getType();
9302 }
9303
9304 // C99 6.5.6
9305 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9306 SourceLocation Loc,
9307 QualType* CompLHSTy) {
9308 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9309
9310 if (LHS.get()->getType()->isVectorType() ||
9311 RHS.get()->getType()->isVectorType()) {
9312 QualType compType = CheckVectorOperands(
9313 LHS, RHS, Loc, CompLHSTy,
9314 /*AllowBothBool*/getLangOpts().AltiVec,
9315 /*AllowBoolConversions*/getLangOpts().ZVector);
9316 if (CompLHSTy) *CompLHSTy = compType;
9317 return compType;
9318 }
9319
9320 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9321 if (LHS.isInvalid() || RHS.isInvalid())
9322 return QualType();
9323
9324 // Enforce type constraints: C99 6.5.6p3.
9325
9326 // Handle the common case first (both operands are arithmetic).
9327 if (!compType.isNull() && compType->isArithmeticType()) {
9328 if (CompLHSTy) *CompLHSTy = compType;
9329 return compType;
9330 }
9331
9332 // Either ptr - int or ptr - ptr.
9333 if (LHS.get()->getType()->isAnyPointerType()) {
9334 QualType lpointee = LHS.get()->getType()->getPointeeType();
9335
9336 // Diagnose bad cases where we step over interface counts.
9337 if (LHS.get()->getType()->isObjCObjectPointerType() &&
9338 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9339 return QualType();
9340
9341 // The result type of a pointer-int computation is the pointer type.
9342 if (RHS.get()->getType()->isIntegerType()) {
9343 // Subtracting from a null pointer should produce a warning.
9344 // The last argument to the diagnose call says this doesn't match the
9345 // GNU int-to-pointer idiom.
9346 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9347 Expr::NPC_ValueDependentIsNotNull)) {
9348 // In C++ adding zero to a null pointer is defined.
9349 Expr::EvalResult KnownVal;
9350 if (!getLangOpts().CPlusPlus ||
9351 (!RHS.get()->isValueDependent() &&
9352 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9353 KnownVal.Val.getInt() != 0))) {
9354 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9355 }
9356 }
9357
9358 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9359 return QualType();
9360
9361 // Check array bounds for pointer arithemtic
9362 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9363 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9364
9365 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9366 return LHS.get()->getType();
9367 }
9368
9369 // Handle pointer-pointer subtractions.
9370 if (const PointerType *RHSPTy
9371 = RHS.get()->getType()->getAs<PointerType>()) {
9372 QualType rpointee = RHSPTy->getPointeeType();
9373
9374 if (getLangOpts().CPlusPlus) {
9375 // Pointee types must be the same: C++ [expr.add]
9376 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9377 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9378 }
9379 } else {
9380 // Pointee types must be compatible C99 6.5.6p3
9381 if (!Context.typesAreCompatible(
9382 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9383 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9384 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9385 return QualType();
9386 }
9387 }
9388
9389 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9390 LHS.get(), RHS.get()))
9391 return QualType();
9392
9393 // FIXME: Add warnings for nullptr - ptr.
9394
9395 // The pointee type may have zero size. As an extension, a structure or
9396 // union may have zero size or an array may have zero length. In this
9397 // case subtraction does not make sense.
9398 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9399 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9400 if (ElementSize.isZero()) {
9401 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9402 << rpointee.getUnqualifiedType()
9403 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9404 }
9405 }
9406
9407 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9408 return Context.getPointerDiffType();
9409 }
9410 }
9411
9412 return InvalidOperands(Loc, LHS, RHS);
9413 }
9414
9415 static bool isScopedEnumerationType(QualType T) {
9416 if (const EnumType *ET = T->getAs<EnumType>())
9417 return ET->getDecl()->isScoped();
9418 return false;
9419 }
9420
9421 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9422 SourceLocation Loc, BinaryOperatorKind Opc,
9423 QualType LHSType) {
9424 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9425 // so skip remaining warnings as we don't want to modify values within Sema.
9426 if (S.getLangOpts().OpenCL)
9427 return;
9428
9429 // Check right/shifter operand
9430 Expr::EvalResult RHSResult;
9431 if (RHS.get()->isValueDependent() ||
9432 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9433 return;
9434 llvm::APSInt Right = RHSResult.Val.getInt();
9435
9436 if (Right.isNegative()) {
9437 S.DiagRuntimeBehavior(Loc, RHS.get(),
9438 S.PDiag(diag::warn_shift_negative)
9439 << RHS.get()->getSourceRange());
9440 return;
9441 }
9442 llvm::APInt LeftBits(Right.getBitWidth(),
9443 S.Context.getTypeSize(LHS.get()->getType()));
9444 if (Right.uge(LeftBits)) {
9445 S.DiagRuntimeBehavior(Loc, RHS.get(),
9446 S.PDiag(diag::warn_shift_gt_typewidth)
9447 << RHS.get()->getSourceRange());
9448 return;
9449 }
9450 if (Opc != BO_Shl)
9451 return;
9452
9453 // When left shifting an ICE which is signed, we can check for overflow which
9454 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9455 // integers have defined behavior modulo one more than the maximum value
9456 // representable in the result type, so never warn for those.
9457 Expr::EvalResult LHSResult;
9458 if (LHS.get()->isValueDependent() ||
9459 LHSType->hasUnsignedIntegerRepresentation() ||
9460 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9461 return;
9462 llvm::APSInt Left = LHSResult.Val.getInt();
9463
9464 // If LHS does not have a signed type and non-negative value
9465 // then, the behavior is undefined. Warn about it.
9466 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9467 S.DiagRuntimeBehavior(Loc, LHS.get(),
9468 S.PDiag(diag::warn_shift_lhs_negative)
9469 << LHS.get()->getSourceRange());
9470 return;
9471 }
9472
9473 llvm::APInt ResultBits =
9474 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9475 if (LeftBits.uge(ResultBits))
9476 return;
9477 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9478 Result = Result.shl(Right);
9479
9480 // Print the bit representation of the signed integer as an unsigned
9481 // hexadecimal number.
9482 SmallString<40> HexResult;
9483 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9484
9485 // If we are only missing a sign bit, this is less likely to result in actual
9486 // bugs -- if the result is cast back to an unsigned type, it will have the
9487 // expected value. Thus we place this behind a different warning that can be
9488 // turned off separately if needed.
9489 if (LeftBits == ResultBits - 1) {
9490 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9491 << HexResult << LHSType
9492 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9493 return;
9494 }
9495
9496 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9497 << HexResult.str() << Result.getMinSignedBits() << LHSType
9498 << Left.getBitWidth() << LHS.get()->getSourceRange()
9499 << RHS.get()->getSourceRange();
9500 }
9501
9502 /// Return the resulting type when a vector is shifted
9503 /// by a scalar or vector shift amount.
9504 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9505 SourceLocation Loc, bool IsCompAssign) {
9506 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9507 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9508 !LHS.get()->getType()->isVectorType()) {
9509 S.Diag(Loc, diag::err_shift_rhs_only_vector)
9510 << RHS.get()->getType() << LHS.get()->getType()
9511 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9512 return QualType();
9513 }
9514
9515 if (!IsCompAssign) {
9516 LHS = S.UsualUnaryConversions(LHS.get());
9517 if (LHS.isInvalid()) return QualType();
9518 }
9519
9520 RHS = S.UsualUnaryConversions(RHS.get());
9521 if (RHS.isInvalid()) return QualType();
9522
9523 QualType LHSType = LHS.get()->getType();
9524 // Note that LHS might be a scalar because the routine calls not only in
9525 // OpenCL case.
9526 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9527 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9528
9529 // Note that RHS might not be a vector.
9530 QualType RHSType = RHS.get()->getType();
9531 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9532 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9533
9534 // The operands need to be integers.
9535 if (!LHSEleType->isIntegerType()) {
9536 S.Diag(Loc, diag::err_typecheck_expect_int)
9537 << LHS.get()->getType() << LHS.get()->getSourceRange();
9538 return QualType();
9539 }
9540
9541 if (!RHSEleType->isIntegerType()) {
9542 S.Diag(Loc, diag::err_typecheck_expect_int)
9543 << RHS.get()->getType() << RHS.get()->getSourceRange();
9544 return QualType();
9545 }
9546
9547 if (!LHSVecTy) {
9548 assert(RHSVecTy);
9549 if (IsCompAssign)
9550 return RHSType;
9551 if (LHSEleType != RHSEleType) {
9552 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9553 LHSEleType = RHSEleType;
9554 }
9555 QualType VecTy =
9556 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9557 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9558 LHSType = VecTy;
9559 } else if (RHSVecTy) {
9560 // OpenCL v1.1 s6.3.j says that for vector types, the operators
9561 // are applied component-wise. So if RHS is a vector, then ensure
9562 // that the number of elements is the same as LHS...
9563 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9564 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9565 << LHS.get()->getType() << RHS.get()->getType()
9566 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9567 return QualType();
9568 }
9569 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9570 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9571 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9572 if (LHSBT != RHSBT &&
9573 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9574 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9575 << LHS.get()->getType() << RHS.get()->getType()
9576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9577 }
9578 }
9579 } else {
9580 // ...else expand RHS to match the number of elements in LHS.
9581 QualType VecTy =
9582 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9583 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9584 }
9585
9586 return LHSType;
9587 }
9588
9589 // C99 6.5.7
9590 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9591 SourceLocation Loc, BinaryOperatorKind Opc,
9592 bool IsCompAssign) {
9593 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9594
9595 // Vector shifts promote their scalar inputs to vector type.
9596 if (LHS.get()->getType()->isVectorType() ||
9597 RHS.get()->getType()->isVectorType()) {
9598 if (LangOpts.ZVector) {
9599 // The shift operators for the z vector extensions work basically
9600 // like general shifts, except that neither the LHS nor the RHS is
9601 // allowed to be a "vector bool".
9602 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9603 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9604 return InvalidOperands(Loc, LHS, RHS);
9605 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9606 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9607 return InvalidOperands(Loc, LHS, RHS);
9608 }
9609 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9610 }
9611
9612 // Shifts don't perform usual arithmetic conversions, they just do integer
9613 // promotions on each operand. C99 6.5.7p3
9614
9615 // For the LHS, do usual unary conversions, but then reset them away
9616 // if this is a compound assignment.
9617 ExprResult OldLHS = LHS;
9618 LHS = UsualUnaryConversions(LHS.get());
9619 if (LHS.isInvalid())
9620 return QualType();
9621 QualType LHSType = LHS.get()->getType();
9622 if (IsCompAssign) LHS = OldLHS;
9623
9624 // The RHS is simpler.
9625 RHS = UsualUnaryConversions(RHS.get());
9626 if (RHS.isInvalid())
9627 return QualType();
9628 QualType RHSType = RHS.get()->getType();
9629
9630 // C99 6.5.7p2: Each of the operands shall have integer type.
9631 if (!LHSType->hasIntegerRepresentation() ||
9632 !RHSType->hasIntegerRepresentation())
9633 return InvalidOperands(Loc, LHS, RHS);
9634
9635 // C++0x: Don't allow scoped enums. FIXME: Use something better than
9636 // hasIntegerRepresentation() above instead of this.
9637 if (isScopedEnumerationType(LHSType) ||
9638 isScopedEnumerationType(RHSType)) {
9639 return InvalidOperands(Loc, LHS, RHS);
9640 }
9641 // Sanity-check shift operands
9642 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9643
9644 // "The type of the result is that of the promoted left operand."
9645 return LHSType;
9646 }
9647
9648 /// If two different enums are compared, raise a warning.
9649 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9650 Expr *RHS) {
9651 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9652 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9653
9654 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9655 if (!LHSEnumType)
9656 return;
9657 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9658 if (!RHSEnumType)
9659 return;
9660
9661 // Ignore anonymous enums.
9662 if (!LHSEnumType->getDecl()->getIdentifier() &&
9663 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9664 return;
9665 if (!RHSEnumType->getDecl()->getIdentifier() &&
9666 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9667 return;
9668
9669 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9670 return;
9671
9672 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9673 << LHSStrippedType << RHSStrippedType
9674 << LHS->getSourceRange() << RHS->getSourceRange();
9675 }
9676
9677 /// Diagnose bad pointer comparisons.
9678 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9679 ExprResult &LHS, ExprResult &RHS,
9680 bool IsError) {
9681 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9682 : diag::ext_typecheck_comparison_of_distinct_pointers)
9683 << LHS.get()->getType() << RHS.get()->getType()
9684 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9685 }
9686
9687 /// Returns false if the pointers are converted to a composite type,
9688 /// true otherwise.
9689 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9690 ExprResult &LHS, ExprResult &RHS) {
9691 // C++ [expr.rel]p2:
9692 // [...] Pointer conversions (4.10) and qualification
9693 // conversions (4.4) are performed on pointer operands (or on
9694 // a pointer operand and a null pointer constant) to bring
9695 // them to their composite pointer type. [...]
9696 //
9697 // C++ [expr.eq]p1 uses the same notion for (in)equality
9698 // comparisons of pointers.
9699
9700 QualType LHSType = LHS.get()->getType();
9701 QualType RHSType = RHS.get()->getType();
9702 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9703 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9704
9705 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9706 if (T.isNull()) {
9707 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9708 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9709 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9710 else
9711 S.InvalidOperands(Loc, LHS, RHS);
9712 return true;
9713 }
9714
9715 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9716 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9717 return false;
9718 }
9719
9720 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9721 ExprResult &LHS,
9722 ExprResult &RHS,
9723 bool IsError) {
9724 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9725 : diag::ext_typecheck_comparison_of_fptr_to_void)
9726 << LHS.get()->getType() << RHS.get()->getType()
9727 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9728 }
9729
9730 static bool isObjCObjectLiteral(ExprResult &E) {
9731 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9732 case Stmt::ObjCArrayLiteralClass:
9733 case Stmt::ObjCDictionaryLiteralClass:
9734 case Stmt::ObjCStringLiteralClass:
9735 case Stmt::ObjCBoxedExprClass:
9736 return true;
9737 default:
9738 // Note that ObjCBoolLiteral is NOT an object literal!
9739 return false;
9740 }
9741 }
9742
9743 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9744 const ObjCObjectPointerType *Type =
9745 LHS->getType()->getAs<ObjCObjectPointerType>();
9746
9747 // If this is not actually an Objective-C object, bail out.
9748 if (!Type)
9749 return false;
9750
9751 // Get the LHS object's interface type.
9752 QualType InterfaceType = Type->getPointeeType();
9753
9754 // If the RHS isn't an Objective-C object, bail out.
9755 if (!RHS->getType()->isObjCObjectPointerType())
9756 return false;
9757
9758 // Try to find the -isEqual: method.
9759 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9760 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9761 InterfaceType,
9762 /*instance=*/true);
9763 if (!Method) {
9764 if (Type->isObjCIdType()) {
9765 // For 'id', just check the global pool.
9766 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9767 /*receiverId=*/true);
9768 } else {
9769 // Check protocols.
9770 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9771 /*instance=*/true);
9772 }
9773 }
9774
9775 if (!Method)
9776 return false;
9777
9778 QualType T = Method->parameters()[0]->getType();
9779 if (!T->isObjCObjectPointerType())
9780 return false;
9781
9782 QualType R = Method->getReturnType();
9783 if (!R->isScalarType())
9784 return false;
9785
9786 return true;
9787 }
9788
9789 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9790 FromE = FromE->IgnoreParenImpCasts();
9791 switch (FromE->getStmtClass()) {
9792 default:
9793 break;
9794 case Stmt::ObjCStringLiteralClass:
9795 // "string literal"
9796 return LK_String;
9797 case Stmt::ObjCArrayLiteralClass:
9798 // "array literal"
9799 return LK_Array;
9800 case Stmt::ObjCDictionaryLiteralClass:
9801 // "dictionary literal"
9802 return LK_Dictionary;
9803 case Stmt::BlockExprClass:
9804 return LK_Block;
9805 case Stmt::ObjCBoxedExprClass: {
9806 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9807 switch (Inner->getStmtClass()) {
9808 case Stmt::IntegerLiteralClass:
9809 case Stmt::FloatingLiteralClass:
9810 case Stmt::CharacterLiteralClass:
9811 case Stmt::ObjCBoolLiteralExprClass:
9812 case Stmt::CXXBoolLiteralExprClass:
9813 // "numeric literal"
9814 return LK_Numeric;
9815 case Stmt::ImplicitCastExprClass: {
9816 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9817 // Boolean literals can be represented by implicit casts.
9818 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9819 return LK_Numeric;
9820 break;
9821 }
9822 default:
9823 break;
9824 }
9825 return LK_Boxed;
9826 }
9827 }
9828 return LK_None;
9829 }
9830
9831 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9832 ExprResult &LHS, ExprResult &RHS,
9833 BinaryOperator::Opcode Opc){
9834 Expr *Literal;
9835 Expr *Other;
9836 if (isObjCObjectLiteral(LHS)) {
9837 Literal = LHS.get();
9838 Other = RHS.get();
9839 } else {
9840 Literal = RHS.get();
9841 Other = LHS.get();
9842 }
9843
9844 // Don't warn on comparisons against nil.
9845 Other = Other->IgnoreParenCasts();
9846 if (Other->isNullPointerConstant(S.getASTContext(),
9847 Expr::NPC_ValueDependentIsNotNull))
9848 return;
9849
9850 // This should be kept in sync with warn_objc_literal_comparison.
9851 // LK_String should always be after the other literals, since it has its own
9852 // warning flag.
9853 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9854 assert(LiteralKind != Sema::LK_Block);
9855 if (LiteralKind == Sema::LK_None) {
9856 llvm_unreachable("Unknown Objective-C object literal kind");
9857 }
9858
9859 if (LiteralKind == Sema::LK_String)
9860 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9861 << Literal->getSourceRange();
9862 else
9863 S.Diag(Loc, diag::warn_objc_literal_comparison)
9864 << LiteralKind << Literal->getSourceRange();
9865
9866 if (BinaryOperator::isEqualityOp(Opc) &&
9867 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9868 SourceLocation Start = LHS.get()->getBeginLoc();
9869 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9870 CharSourceRange OpRange =
9871 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9872
9873 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9874 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9875 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9876 << FixItHint::CreateInsertion(End, "]");
9877 }
9878 }
9879
9880 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9881 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9882 ExprResult &RHS, SourceLocation Loc,
9883 BinaryOperatorKind Opc) {
9884 // Check that left hand side is !something.
9885 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9886 if (!UO || UO->getOpcode() != UO_LNot) return;
9887
9888 // Only check if the right hand side is non-bool arithmetic type.
9889 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9890
9891 // Make sure that the something in !something is not bool.
9892 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9893 if (SubExpr->isKnownToHaveBooleanValue()) return;
9894
9895 // Emit warning.
9896 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9897 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9898 << Loc << IsBitwiseOp;
9899
9900 // First note suggest !(x < y)
9901 SourceLocation FirstOpen = SubExpr->getBeginLoc();
9902 SourceLocation FirstClose = RHS.get()->getEndLoc();
9903 FirstClose = S.getLocForEndOfToken(FirstClose);
9904 if (FirstClose.isInvalid())
9905 FirstOpen = SourceLocation();
9906 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9907 << IsBitwiseOp
9908 << FixItHint::CreateInsertion(FirstOpen, "(")
9909 << FixItHint::CreateInsertion(FirstClose, ")");
9910
9911 // Second note suggests (!x) < y
9912 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9913 SourceLocation SecondClose = LHS.get()->getEndLoc();
9914 SecondClose = S.getLocForEndOfToken(SecondClose);
9915 if (SecondClose.isInvalid())
9916 SecondOpen = SourceLocation();
9917 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9918 << FixItHint::CreateInsertion(SecondOpen, "(")
9919 << FixItHint::CreateInsertion(SecondClose, ")");
9920 }
9921
9922 // Get the decl for a simple expression: a reference to a variable,
9923 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9924 static ValueDecl *getCompareDecl(Expr *E) {
9925 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9926 return DR->getDecl();
9927 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9928 if (Ivar->isFreeIvar())
9929 return Ivar->getDecl();
9930 }
9931 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9932 if (Mem->isImplicitAccess())
9933 return Mem->getMemberDecl();
9934 }
9935 return nullptr;
9936 }
9937
9938 /// Diagnose some forms of syntactically-obvious tautological comparison.
9939 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9940 Expr *LHS, Expr *RHS,
9941 BinaryOperatorKind Opc) {
9942 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9943 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9944
9945 QualType LHSType = LHS->getType();
9946 QualType RHSType = RHS->getType();
9947 if (LHSType->hasFloatingRepresentation() ||
9948 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9949 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9950 S.inTemplateInstantiation())
9951 return;
9952
9953 // Comparisons between two array types are ill-formed for operator<=>, so
9954 // we shouldn't emit any additional warnings about it.
9955 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9956 return;
9957
9958 // For non-floating point types, check for self-comparisons of the form
9959 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9960 // often indicate logic errors in the program.
9961 //
9962 // NOTE: Don't warn about comparison expressions resulting from macro
9963 // expansion. Also don't warn about comparisons which are only self
9964 // comparisons within a template instantiation. The warnings should catch
9965 // obvious cases in the definition of the template anyways. The idea is to
9966 // warn when the typed comparison operator will always evaluate to the same
9967 // result.
9968 ValueDecl *DL = getCompareDecl(LHSStripped);
9969 ValueDecl *DR = getCompareDecl(RHSStripped);
9970 if (DL && DR && declaresSameEntity(DL, DR)) {
9971 StringRef Result;
9972 switch (Opc) {
9973 case BO_EQ: case BO_LE: case BO_GE:
9974 Result = "true";
9975 break;
9976 case BO_NE: case BO_LT: case BO_GT:
9977 Result = "false";
9978 break;
9979 case BO_Cmp:
9980 Result = "'std::strong_ordering::equal'";
9981 break;
9982 default:
9983 break;
9984 }
9985 S.DiagRuntimeBehavior(Loc, nullptr,
9986 S.PDiag(diag::warn_comparison_always)
9987 << 0 /*self-comparison*/ << !Result.empty()
9988 << Result);
9989 } else if (DL && DR &&
9990 DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9991 !DL->isWeak() && !DR->isWeak()) {
9992 // What is it always going to evaluate to?
9993 StringRef Result;
9994 switch(Opc) {
9995 case BO_EQ: // e.g. array1 == array2
9996 Result = "false";
9997 break;
9998 case BO_NE: // e.g. array1 != array2
9999 Result = "true";
10000 break;
10001 default: // e.g. array1 <= array2
10002 // The best we can say is 'a constant'
10003 break;
10004 }
10005 S.DiagRuntimeBehavior(Loc, nullptr,
10006 S.PDiag(diag::warn_comparison_always)
10007 << 1 /*array comparison*/
10008 << !Result.empty() << Result);
10009 }
10010
10011 if (isa<CastExpr>(LHSStripped))
10012 LHSStripped = LHSStripped->IgnoreParenCasts();
10013 if (isa<CastExpr>(RHSStripped))
10014 RHSStripped = RHSStripped->IgnoreParenCasts();
10015
10016 // Warn about comparisons against a string constant (unless the other
10017 // operand is null); the user probably wants strcmp.
10018 Expr *LiteralString = nullptr;
10019 Expr *LiteralStringStripped = nullptr;
10020 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10021 !RHSStripped->isNullPointerConstant(S.Context,
10022 Expr::NPC_ValueDependentIsNull)) {
10023 LiteralString = LHS;
10024 LiteralStringStripped = LHSStripped;
10025 } else if ((isa<StringLiteral>(RHSStripped) ||
10026 isa<ObjCEncodeExpr>(RHSStripped)) &&
10027 !LHSStripped->isNullPointerConstant(S.Context,
10028 Expr::NPC_ValueDependentIsNull)) {
10029 LiteralString = RHS;
10030 LiteralStringStripped = RHSStripped;
10031 }
10032
10033 if (LiteralString) {
10034 S.DiagRuntimeBehavior(Loc, nullptr,
10035 S.PDiag(diag::warn_stringcompare)
10036 << isa<ObjCEncodeExpr>(LiteralStringStripped)
10037 << LiteralString->getSourceRange());
10038 }
10039 }
10040
10041 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10042 switch (CK) {
10043 default: {
10044 #ifndef NDEBUG
10045 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10046 << "\n";
10047 #endif
10048 llvm_unreachable("unhandled cast kind");
10049 }
10050 case CK_UserDefinedConversion:
10051 return ICK_Identity;
10052 case CK_LValueToRValue:
10053 return ICK_Lvalue_To_Rvalue;
10054 case CK_ArrayToPointerDecay:
10055 return ICK_Array_To_Pointer;
10056 case CK_FunctionToPointerDecay:
10057 return ICK_Function_To_Pointer;
10058 case CK_IntegralCast:
10059 return ICK_Integral_Conversion;
10060 case CK_FloatingCast:
10061 return ICK_Floating_Conversion;
10062 case CK_IntegralToFloating:
10063 case CK_FloatingToIntegral:
10064 return ICK_Floating_Integral;
10065 case CK_IntegralComplexCast:
10066 case CK_FloatingComplexCast:
10067 case CK_FloatingComplexToIntegralComplex:
10068 case CK_IntegralComplexToFloatingComplex:
10069 return ICK_Complex_Conversion;
10070 case CK_FloatingComplexToReal:
10071 case CK_FloatingRealToComplex:
10072 case CK_IntegralComplexToReal:
10073 case CK_IntegralRealToComplex:
10074 return ICK_Complex_Real;
10075 }
10076 }
10077
10078 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10079 QualType FromType,
10080 SourceLocation Loc) {
10081 // Check for a narrowing implicit conversion.
10082 StandardConversionSequence SCS;
10083 SCS.setAsIdentityConversion();
10084 SCS.setToType(0, FromType);
10085 SCS.setToType(1, ToType);
10086 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10087 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10088
10089 APValue PreNarrowingValue;
10090 QualType PreNarrowingType;
10091 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10092 PreNarrowingType,
10093 /*IgnoreFloatToIntegralConversion*/ true)) {
10094 case NK_Dependent_Narrowing:
10095 // Implicit conversion to a narrower type, but the expression is
10096 // value-dependent so we can't tell whether it's actually narrowing.
10097 case NK_Not_Narrowing:
10098 return false;
10099
10100 case NK_Constant_Narrowing:
10101 // Implicit conversion to a narrower type, and the value is not a constant
10102 // expression.
10103 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10104 << /*Constant*/ 1
10105 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10106 return true;
10107
10108 case NK_Variable_Narrowing:
10109 // Implicit conversion to a narrower type, and the value is not a constant
10110 // expression.
10111 case NK_Type_Narrowing:
10112 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10113 << /*Constant*/ 0 << FromType << ToType;
10114 // TODO: It's not a constant expression, but what if the user intended it
10115 // to be? Can we produce notes to help them figure out why it isn't?
10116 return true;
10117 }
10118 llvm_unreachable("unhandled case in switch");
10119 }
10120
10121 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10122 ExprResult &LHS,
10123 ExprResult &RHS,
10124 SourceLocation Loc) {
10125 using CCT = ComparisonCategoryType;
10126
10127 QualType LHSType = LHS.get()->getType();
10128 QualType RHSType = RHS.get()->getType();
10129 // Dig out the original argument type and expression before implicit casts
10130 // were applied. These are the types/expressions we need to check the
10131 // [expr.spaceship] requirements against.
10132 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10133 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10134 QualType LHSStrippedType = LHSStripped.get()->getType();
10135 QualType RHSStrippedType = RHSStripped.get()->getType();
10136
10137 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10138 // other is not, the program is ill-formed.
10139 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10140 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10141 return QualType();
10142 }
10143
10144 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10145 RHSStrippedType->isEnumeralType();
10146 if (NumEnumArgs == 1) {
10147 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10148 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10149 if (OtherTy->hasFloatingRepresentation()) {
10150 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10151 return QualType();
10152 }
10153 }
10154 if (NumEnumArgs == 2) {
10155 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10156 // type E, the operator yields the result of converting the operands
10157 // to the underlying type of E and applying <=> to the converted operands.
10158 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10159 S.InvalidOperands(Loc, LHS, RHS);
10160 return QualType();
10161 }
10162 QualType IntType =
10163 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10164 assert(IntType->isArithmeticType());
10165
10166 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10167 // promote the boolean type, and all other promotable integer types, to
10168 // avoid this.
10169 if (IntType->isPromotableIntegerType())
10170 IntType = S.Context.getPromotedIntegerType(IntType);
10171
10172 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10173 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10174 LHSType = RHSType = IntType;
10175 }
10176
10177 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10178 // usual arithmetic conversions are applied to the operands.
10179 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10180 if (LHS.isInvalid() || RHS.isInvalid())
10181 return QualType();
10182 if (Type.isNull())
10183 return S.InvalidOperands(Loc, LHS, RHS);
10184 assert(Type->isArithmeticType() || Type->isEnumeralType());
10185
10186 bool HasNarrowing = checkThreeWayNarrowingConversion(
10187 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10188 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10189 RHS.get()->getBeginLoc());
10190 if (HasNarrowing)
10191 return QualType();
10192
10193 assert(!Type.isNull() && "composite type for <=> has not been set");
10194
10195 auto TypeKind = [&]() {
10196 if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10197 if (CT->getElementType()->hasFloatingRepresentation())
10198 return CCT::WeakEquality;
10199 return CCT::StrongEquality;
10200 }
10201 if (Type->isIntegralOrEnumerationType())
10202 return CCT::StrongOrdering;
10203 if (Type->hasFloatingRepresentation())
10204 return CCT::PartialOrdering;
10205 llvm_unreachable("other types are unimplemented");
10206 }();
10207
10208 return S.CheckComparisonCategoryType(TypeKind, Loc);
10209 }
10210
10211 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10212 ExprResult &RHS,
10213 SourceLocation Loc,
10214 BinaryOperatorKind Opc) {
10215 if (Opc == BO_Cmp)
10216 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10217
10218 // C99 6.5.8p3 / C99 6.5.9p4
10219 QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10220 if (LHS.isInvalid() || RHS.isInvalid())
10221 return QualType();
10222 if (Type.isNull())
10223 return S.InvalidOperands(Loc, LHS, RHS);
10224 assert(Type->isArithmeticType() || Type->isEnumeralType());
10225
10226 checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10227
10228 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10229 return S.InvalidOperands(Loc, LHS, RHS);
10230
10231 // Check for comparisons of floating point operands using != and ==.
10232 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10233 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10234
10235 // The result of comparisons is 'bool' in C++, 'int' in C.
10236 return S.Context.getLogicalOperationType();
10237 }
10238
10239 // C99 6.5.8, C++ [expr.rel]
10240 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10241 SourceLocation Loc,
10242 BinaryOperatorKind Opc) {
10243 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10244 bool IsThreeWay = Opc == BO_Cmp;
10245 auto IsAnyPointerType = [](ExprResult E) {
10246 QualType Ty = E.get()->getType();
10247 return Ty->isPointerType() || Ty->isMemberPointerType();
10248 };
10249
10250 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10251 // type, array-to-pointer, ..., conversions are performed on both operands to
10252 // bring them to their composite type.
10253 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10254 // any type-related checks.
10255 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10256 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10257 if (LHS.isInvalid())
10258 return QualType();
10259 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10260 if (RHS.isInvalid())
10261 return QualType();
10262 } else {
10263 LHS = DefaultLvalueConversion(LHS.get());
10264 if (LHS.isInvalid())
10265 return QualType();
10266 RHS = DefaultLvalueConversion(RHS.get());
10267 if (RHS.isInvalid())
10268 return QualType();
10269 }
10270
10271 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10272
10273 // Handle vector comparisons separately.
10274 if (LHS.get()->getType()->isVectorType() ||
10275 RHS.get()->getType()->isVectorType())
10276 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10277
10278 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10279 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10280
10281 QualType LHSType = LHS.get()->getType();
10282 QualType RHSType = RHS.get()->getType();
10283 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10284 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10285 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10286
10287 const Expr::NullPointerConstantKind LHSNullKind =
10288 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10289 const Expr::NullPointerConstantKind RHSNullKind =
10290 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10291 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10292 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10293
10294 auto computeResultTy = [&]() {
10295 if (Opc != BO_Cmp)
10296 return Context.getLogicalOperationType();
10297 assert(getLangOpts().CPlusPlus);
10298 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10299
10300 QualType CompositeTy = LHS.get()->getType();
10301 assert(!CompositeTy->isReferenceType());
10302
10303 auto buildResultTy = [&](ComparisonCategoryType Kind) {
10304 return CheckComparisonCategoryType(Kind, Loc);
10305 };
10306
10307 // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10308 // pointer type, a pointer-to-member type, or std::nullptr_t, the
10309 // result is of type std::strong_equality
10310 if (CompositeTy->isFunctionPointerType() ||
10311 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10312 // FIXME: consider making the function pointer case produce
10313 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10314 // and direction polls
10315 return buildResultTy(ComparisonCategoryType::StrongEquality);
10316
10317 // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10318 // pointer type, p <=> q is of type std::strong_ordering.
10319 if (CompositeTy->isPointerType()) {
10320 // P0946R0: Comparisons between a null pointer constant and an object
10321 // pointer result in std::strong_equality
10322 if (LHSIsNull != RHSIsNull)
10323 return buildResultTy(ComparisonCategoryType::StrongEquality);
10324 return buildResultTy(ComparisonCategoryType::StrongOrdering);
10325 }
10326 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10327 // TODO: Extend support for operator<=> to ObjC types.
10328 return InvalidOperands(Loc, LHS, RHS);
10329 };
10330
10331
10332 if (!IsRelational && LHSIsNull != RHSIsNull) {
10333 bool IsEquality = Opc == BO_EQ;
10334 if (RHSIsNull)
10335 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10336 RHS.get()->getSourceRange());
10337 else
10338 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10339 LHS.get()->getSourceRange());
10340 }
10341
10342 if ((LHSType->isIntegerType() && !LHSIsNull) ||
10343 (RHSType->isIntegerType() && !RHSIsNull)) {
10344 // Skip normal pointer conversion checks in this case; we have better
10345 // diagnostics for this below.
10346 } else if (getLangOpts().CPlusPlus) {
10347 // Equality comparison of a function pointer to a void pointer is invalid,
10348 // but we allow it as an extension.
10349 // FIXME: If we really want to allow this, should it be part of composite
10350 // pointer type computation so it works in conditionals too?
10351 if (!IsRelational &&
10352 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10353 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10354 // This is a gcc extension compatibility comparison.
10355 // In a SFINAE context, we treat this as a hard error to maintain
10356 // conformance with the C++ standard.
10357 diagnoseFunctionPointerToVoidComparison(
10358 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10359
10360 if (isSFINAEContext())
10361 return QualType();
10362
10363 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10364 return computeResultTy();
10365 }
10366
10367 // C++ [expr.eq]p2:
10368 // If at least one operand is a pointer [...] bring them to their
10369 // composite pointer type.
10370 // C++ [expr.spaceship]p6
10371 // If at least one of the operands is of pointer type, [...] bring them
10372 // to their composite pointer type.
10373 // C++ [expr.rel]p2:
10374 // If both operands are pointers, [...] bring them to their composite
10375 // pointer type.
10376 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10377 (IsRelational ? 2 : 1) &&
10378 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10379 RHSType->isObjCObjectPointerType()))) {
10380 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10381 return QualType();
10382 return computeResultTy();
10383 }
10384 } else if (LHSType->isPointerType() &&
10385 RHSType->isPointerType()) { // C99 6.5.8p2
10386 // All of the following pointer-related warnings are GCC extensions, except
10387 // when handling null pointer constants.
10388 QualType LCanPointeeTy =
10389 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10390 QualType RCanPointeeTy =
10391 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10392
10393 // C99 6.5.9p2 and C99 6.5.8p2
10394 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10395 RCanPointeeTy.getUnqualifiedType())) {
10396 // Valid unless a relational comparison of function pointers
10397 if (IsRelational && LCanPointeeTy->isFunctionType()) {
10398 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10399 << LHSType << RHSType << LHS.get()->getSourceRange()
10400 << RHS.get()->getSourceRange();
10401 }
10402 } else if (!IsRelational &&
10403 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10404 // Valid unless comparison between non-null pointer and function pointer
10405 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10406 && !LHSIsNull && !RHSIsNull)
10407 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10408 /*isError*/false);
10409 } else {
10410 // Invalid
10411 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10412 }
10413 if (LCanPointeeTy != RCanPointeeTy) {
10414 // Treat NULL constant as a special case in OpenCL.
10415 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10416 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10417 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10418 Diag(Loc,
10419 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10420 << LHSType << RHSType << 0 /* comparison */
10421 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10422 }
10423 }
10424 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10425 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10426 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10427 : CK_BitCast;
10428 if (LHSIsNull && !RHSIsNull)
10429 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10430 else
10431 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10432 }
10433 return computeResultTy();
10434 }
10435
10436 if (getLangOpts().CPlusPlus) {
10437 // C++ [expr.eq]p4:
10438 // Two operands of type std::nullptr_t or one operand of type
10439 // std::nullptr_t and the other a null pointer constant compare equal.
10440 if (!IsRelational && LHSIsNull && RHSIsNull) {
10441 if (LHSType->isNullPtrType()) {
10442 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10443 return computeResultTy();
10444 }
10445 if (RHSType->isNullPtrType()) {
10446 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10447 return computeResultTy();
10448 }
10449 }
10450
10451 // Comparison of Objective-C pointers and block pointers against nullptr_t.
10452 // These aren't covered by the composite pointer type rules.
10453 if (!IsRelational && RHSType->isNullPtrType() &&
10454 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10455 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10456 return computeResultTy();
10457 }
10458 if (!IsRelational && LHSType->isNullPtrType() &&
10459 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10460 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10461 return computeResultTy();
10462 }
10463
10464 if (IsRelational &&
10465 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10466 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10467 // HACK: Relational comparison of nullptr_t against a pointer type is
10468 // invalid per DR583, but we allow it within std::less<> and friends,
10469 // since otherwise common uses of it break.
10470 // FIXME: Consider removing this hack once LWG fixes std::less<> and
10471 // friends to have std::nullptr_t overload candidates.
10472 DeclContext *DC = CurContext;
10473 if (isa<FunctionDecl>(DC))
10474 DC = DC->getParent();
10475 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10476 if (CTSD->isInStdNamespace() &&
10477 llvm::StringSwitch<bool>(CTSD->getName())
10478 .Cases("less", "less_equal", "greater", "greater_equal", true)
10479 .Default(false)) {
10480 if (RHSType->isNullPtrType())
10481 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10482 else
10483 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10484 return computeResultTy();
10485 }
10486 }
10487 }
10488
10489 // C++ [expr.eq]p2:
10490 // If at least one operand is a pointer to member, [...] bring them to
10491 // their composite pointer type.
10492 if (!IsRelational &&
10493 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10494 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10495 return QualType();
10496 else
10497 return computeResultTy();
10498 }
10499 }
10500
10501 // Handle block pointer types.
10502 if (!IsRelational && LHSType->isBlockPointerType() &&
10503 RHSType->isBlockPointerType()) {
10504 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10505 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10506
10507 if (!LHSIsNull && !RHSIsNull &&
10508 !Context.typesAreCompatible(lpointee, rpointee)) {
10509 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10510 << LHSType << RHSType << LHS.get()->getSourceRange()
10511 << RHS.get()->getSourceRange();
10512 }
10513 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10514 return computeResultTy();
10515 }
10516
10517 // Allow block pointers to be compared with null pointer constants.
10518 if (!IsRelational
10519 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10520 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10521 if (!LHSIsNull && !RHSIsNull) {
10522 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10523 ->getPointeeType()->isVoidType())
10524 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10525 ->getPointeeType()->isVoidType())))
10526 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10527 << LHSType << RHSType << LHS.get()->getSourceRange()
10528 << RHS.get()->getSourceRange();
10529 }
10530 if (LHSIsNull && !RHSIsNull)
10531 LHS = ImpCastExprToType(LHS.get(), RHSType,
10532 RHSType->isPointerType() ? CK_BitCast
10533 : CK_AnyPointerToBlockPointerCast);
10534 else
10535 RHS = ImpCastExprToType(RHS.get(), LHSType,
10536 LHSType->isPointerType() ? CK_BitCast
10537 : CK_AnyPointerToBlockPointerCast);
10538 return computeResultTy();
10539 }
10540
10541 if (LHSType->isObjCObjectPointerType() ||
10542 RHSType->isObjCObjectPointerType()) {
10543 const PointerType *LPT = LHSType->getAs<PointerType>();
10544 const PointerType *RPT = RHSType->getAs<PointerType>();
10545 if (LPT || RPT) {
10546 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10547 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10548
10549 if (!LPtrToVoid && !RPtrToVoid &&
10550 !Context.typesAreCompatible(LHSType, RHSType)) {
10551 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10552 /*isError*/false);
10553 }
10554 if (LHSIsNull && !RHSIsNull) {
10555 Expr *E = LHS.get();
10556 if (getLangOpts().ObjCAutoRefCount)
10557 CheckObjCConversion(SourceRange(), RHSType, E,
10558 CCK_ImplicitConversion);
10559 LHS = ImpCastExprToType(E, RHSType,
10560 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10561 }
10562 else {
10563 Expr *E = RHS.get();
10564 if (getLangOpts().ObjCAutoRefCount)
10565 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10566 /*Diagnose=*/true,
10567 /*DiagnoseCFAudited=*/false, Opc);
10568 RHS = ImpCastExprToType(E, LHSType,
10569 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10570 }
10571 return computeResultTy();
10572 }
10573 if (LHSType->isObjCObjectPointerType() &&
10574 RHSType->isObjCObjectPointerType()) {
10575 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10576 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10577 /*isError*/false);
10578 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10579 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10580
10581 if (LHSIsNull && !RHSIsNull)
10582 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10583 else
10584 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10585 return computeResultTy();
10586 }
10587
10588 if (!IsRelational && LHSType->isBlockPointerType() &&
10589 RHSType->isBlockCompatibleObjCPointerType(Context)) {
10590 LHS = ImpCastExprToType(LHS.get(), RHSType,
10591 CK_BlockPointerToObjCPointerCast);
10592 return computeResultTy();
10593 } else if (!IsRelational &&
10594 LHSType->isBlockCompatibleObjCPointerType(Context) &&
10595 RHSType->isBlockPointerType()) {
10596 RHS = ImpCastExprToType(RHS.get(), LHSType,
10597 CK_BlockPointerToObjCPointerCast);
10598 return computeResultTy();
10599 }
10600 }
10601 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10602 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10603 unsigned DiagID = 0;
10604 bool isError = false;
10605 if (LangOpts.DebuggerSupport) {
10606 // Under a debugger, allow the comparison of pointers to integers,
10607 // since users tend to want to compare addresses.
10608 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10609 (RHSIsNull && RHSType->isIntegerType())) {
10610 if (IsRelational) {
10611 isError = getLangOpts().CPlusPlus;
10612 DiagID =
10613 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10614 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10615 }
10616 } else if (getLangOpts().CPlusPlus) {
10617 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10618 isError = true;
10619 } else if (IsRelational)
10620 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10621 else
10622 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10623
10624 if (DiagID) {
10625 Diag(Loc, DiagID)
10626 << LHSType << RHSType << LHS.get()->getSourceRange()
10627 << RHS.get()->getSourceRange();
10628 if (isError)
10629 return QualType();
10630 }
10631
10632 if (LHSType->isIntegerType())
10633 LHS = ImpCastExprToType(LHS.get(), RHSType,
10634 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10635 else
10636 RHS = ImpCastExprToType(RHS.get(), LHSType,
10637 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10638 return computeResultTy();
10639 }
10640
10641 // Handle block pointers.
10642 if (!IsRelational && RHSIsNull
10643 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10644 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10645 return computeResultTy();
10646 }
10647 if (!IsRelational && LHSIsNull
10648 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10649 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10650 return computeResultTy();
10651 }
10652
10653 if (getLangOpts().OpenCLVersion >= 200) {
10654 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10655 return computeResultTy();
10656 }
10657
10658 if (LHSType->isQueueT() && RHSType->isQueueT()) {
10659 return computeResultTy();
10660 }
10661
10662 if (LHSIsNull && RHSType->isQueueT()) {
10663 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10664 return computeResultTy();
10665 }
10666
10667 if (LHSType->isQueueT() && RHSIsNull) {
10668 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10669 return computeResultTy();
10670 }
10671 }
10672
10673 return InvalidOperands(Loc, LHS, RHS);
10674 }
10675
10676 // Return a signed ext_vector_type that is of identical size and number of
10677 // elements. For floating point vectors, return an integer type of identical
10678 // size and number of elements. In the non ext_vector_type case, search from
10679 // the largest type to the smallest type to avoid cases where long long == long,
10680 // where long gets picked over long long.
10681 QualType Sema::GetSignedVectorType(QualType V) {
10682 const VectorType *VTy = V->getAs<VectorType>();
10683 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10684
10685 if (isa<ExtVectorType>(VTy)) {
10686 if (TypeSize == Context.getTypeSize(Context.CharTy))
10687 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10688 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10689 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10690 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10691 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10692 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10693 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10694 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10695 "Unhandled vector element size in vector compare");
10696 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10697 }
10698
10699 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10700 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10701 VectorType::GenericVector);
10702 else if (TypeSize == Context.getTypeSize(Context.LongTy))
10703 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10704 VectorType::GenericVector);
10705 else if (TypeSize == Context.getTypeSize(Context.IntTy))
10706 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10707 VectorType::GenericVector);
10708 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10709 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10710 VectorType::GenericVector);
10711 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10712 "Unhandled vector element size in vector compare");
10713 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10714 VectorType::GenericVector);
10715 }
10716
10717 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10718 /// operates on extended vector types. Instead of producing an IntTy result,
10719 /// like a scalar comparison, a vector comparison produces a vector of integer
10720 /// types.
10721 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10722 SourceLocation Loc,
10723 BinaryOperatorKind Opc) {
10724 // Check to make sure we're operating on vectors of the same type and width,
10725 // Allowing one side to be a scalar of element type.
10726 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10727 /*AllowBothBool*/true,
10728 /*AllowBoolConversions*/getLangOpts().ZVector);
10729 if (vType.isNull())
10730 return vType;
10731
10732 QualType LHSType = LHS.get()->getType();
10733
10734 // If AltiVec, the comparison results in a numeric type, i.e.
10735 // bool for C++, int for C
10736 if (getLangOpts().AltiVec &&
10737 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10738 return Context.getLogicalOperationType();
10739
10740 // For non-floating point types, check for self-comparisons of the form
10741 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10742 // often indicate logic errors in the program.
10743 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10744
10745 // Check for comparisons of floating point operands using != and ==.
10746 if (BinaryOperator::isEqualityOp(Opc) &&
10747 LHSType->hasFloatingRepresentation()) {
10748 assert(RHS.get()->getType()->hasFloatingRepresentation());
10749 CheckFloatComparison(Loc, LHS.get(), RHS.get());
10750 }
10751
10752 // Return a signed type for the vector.
10753 return GetSignedVectorType(vType);
10754 }
10755
10756 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10757 SourceLocation Loc) {
10758 // Ensure that either both operands are of the same vector type, or
10759 // one operand is of a vector type and the other is of its element type.
10760 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10761 /*AllowBothBool*/true,
10762 /*AllowBoolConversions*/false);
10763 if (vType.isNull())
10764 return InvalidOperands(Loc, LHS, RHS);
10765 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10766 vType->hasFloatingRepresentation())
10767 return InvalidOperands(Loc, LHS, RHS);
10768 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10769 // usage of the logical operators && and || with vectors in C. This
10770 // check could be notionally dropped.
10771 if (!getLangOpts().CPlusPlus &&
10772 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10773 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10774
10775 return GetSignedVectorType(LHS.get()->getType());
10776 }
10777
10778 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10779 SourceLocation Loc,
10780 BinaryOperatorKind Opc) {
10781 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10782
10783 bool IsCompAssign =
10784 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10785
10786 if (LHS.get()->getType()->isVectorType() ||
10787 RHS.get()->getType()->isVectorType()) {
10788 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10789 RHS.get()->getType()->hasIntegerRepresentation())
10790 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10791 /*AllowBothBool*/true,
10792 /*AllowBoolConversions*/getLangOpts().ZVector);
10793 return InvalidOperands(Loc, LHS, RHS);
10794 }
10795
10796 if (Opc == BO_And)
10797 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10798
10799 ExprResult LHSResult = LHS, RHSResult = RHS;
10800 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10801 IsCompAssign);
10802 if (LHSResult.isInvalid() || RHSResult.isInvalid())
10803 return QualType();
10804 LHS = LHSResult.get();
10805 RHS = RHSResult.get();
10806
10807 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10808 return compType;
10809 return InvalidOperands(Loc, LHS, RHS);
10810 }
10811
10812 // C99 6.5.[13,14]
10813 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10814 SourceLocation Loc,
10815 BinaryOperatorKind Opc) {
10816 // Check vector operands differently.
10817 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10818 return CheckVectorLogicalOperands(LHS, RHS, Loc);
10819
10820 // Diagnose cases where the user write a logical and/or but probably meant a
10821 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
10822 // is a constant.
10823 if (LHS.get()->getType()->isIntegerType() &&
10824 !LHS.get()->getType()->isBooleanType() &&
10825 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10826 // Don't warn in macros or template instantiations.
10827 !Loc.isMacroID() && !inTemplateInstantiation()) {
10828 // If the RHS can be constant folded, and if it constant folds to something
10829 // that isn't 0 or 1 (which indicate a potential logical operation that
10830 // happened to fold to true/false) then warn.
10831 // Parens on the RHS are ignored.
10832 Expr::EvalResult EVResult;
10833 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10834 llvm::APSInt Result = EVResult.Val.getInt();
10835 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10836 !RHS.get()->getExprLoc().isMacroID()) ||
10837 (Result != 0 && Result != 1)) {
10838 Diag(Loc, diag::warn_logical_instead_of_bitwise)
10839 << RHS.get()->getSourceRange()
10840 << (Opc == BO_LAnd ? "&&" : "||");
10841 // Suggest replacing the logical operator with the bitwise version
10842 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10843 << (Opc == BO_LAnd ? "&" : "|")
10844 << FixItHint::CreateReplacement(SourceRange(
10845 Loc, getLocForEndOfToken(Loc)),
10846 Opc == BO_LAnd ? "&" : "|");
10847 if (Opc == BO_LAnd)
10848 // Suggest replacing "Foo() && kNonZero" with "Foo()"
10849 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10850 << FixItHint::CreateRemoval(
10851 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10852 RHS.get()->getEndLoc()));
10853 }
10854 }
10855 }
10856
10857 if (!Context.getLangOpts().CPlusPlus) {
10858 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10859 // not operate on the built-in scalar and vector float types.
10860 if (Context.getLangOpts().OpenCL &&
10861 Context.getLangOpts().OpenCLVersion < 120) {
10862 if (LHS.get()->getType()->isFloatingType() ||
10863 RHS.get()->getType()->isFloatingType())
10864 return InvalidOperands(Loc, LHS, RHS);
10865 }
10866
10867 LHS = UsualUnaryConversions(LHS.get());
10868 if (LHS.isInvalid())
10869 return QualType();
10870
10871 RHS = UsualUnaryConversions(RHS.get());
10872 if (RHS.isInvalid())
10873 return QualType();
10874
10875 if (!LHS.get()->getType()->isScalarType() ||
10876 !RHS.get()->getType()->isScalarType())
10877 return InvalidOperands(Loc, LHS, RHS);
10878
10879 return Context.IntTy;
10880 }
10881
10882 // The following is safe because we only use this method for
10883 // non-overloadable operands.
10884
10885 // C++ [expr.log.and]p1
10886 // C++ [expr.log.or]p1
10887 // The operands are both contextually converted to type bool.
10888 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10889 if (LHSRes.isInvalid())
10890 return InvalidOperands(Loc, LHS, RHS);
10891 LHS = LHSRes;
10892
10893 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10894 if (RHSRes.isInvalid())
10895 return InvalidOperands(Loc, LHS, RHS);
10896 RHS = RHSRes;
10897
10898 // C++ [expr.log.and]p2
10899 // C++ [expr.log.or]p2
10900 // The result is a bool.
10901 return Context.BoolTy;
10902 }
10903
10904 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10905 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10906 if (!ME) return false;
10907 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10908 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10909 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10910 if (!Base) return false;
10911 return Base->getMethodDecl() != nullptr;
10912 }
10913
10914 /// Is the given expression (which must be 'const') a reference to a
10915 /// variable which was originally non-const, but which has become
10916 /// 'const' due to being captured within a block?
10917 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10918 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10919 assert(E->isLValue() && E->getType().isConstQualified());
10920 E = E->IgnoreParens();
10921
10922 // Must be a reference to a declaration from an enclosing scope.
10923 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10924 if (!DRE) return NCCK_None;
10925 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10926
10927 // The declaration must be a variable which is not declared 'const'.
10928 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10929 if (!var) return NCCK_None;
10930 if (var->getType().isConstQualified()) return NCCK_None;
10931 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10932
10933 // Decide whether the first capture was for a block or a lambda.
10934 DeclContext *DC = S.CurContext, *Prev = nullptr;
10935 // Decide whether the first capture was for a block or a lambda.
10936 while (DC) {
10937 // For init-capture, it is possible that the variable belongs to the
10938 // template pattern of the current context.
10939 if (auto *FD = dyn_cast<FunctionDecl>(DC))
10940 if (var->isInitCapture() &&
10941 FD->getTemplateInstantiationPattern() == var->getDeclContext())
10942 break;
10943 if (DC == var->getDeclContext())
10944 break;
10945 Prev = DC;
10946 DC = DC->getParent();
10947 }
10948 // Unless we have an init-capture, we've gone one step too far.
10949 if (!var->isInitCapture())
10950 DC = Prev;
10951 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10952 }
10953
10954 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10955 Ty = Ty.getNonReferenceType();
10956 if (IsDereference && Ty->isPointerType())
10957 Ty = Ty->getPointeeType();
10958 return !Ty.isConstQualified();
10959 }
10960
10961 // Update err_typecheck_assign_const and note_typecheck_assign_const
10962 // when this enum is changed.
10963 enum {
10964 ConstFunction,
10965 ConstVariable,
10966 ConstMember,
10967 ConstMethod,
10968 NestedConstMember,
10969 ConstUnknown, // Keep as last element
10970 };
10971
10972 /// Emit the "read-only variable not assignable" error and print notes to give
10973 /// more information about why the variable is not assignable, such as pointing
10974 /// to the declaration of a const variable, showing that a method is const, or
10975 /// that the function is returning a const reference.
10976 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10977 SourceLocation Loc) {
10978 SourceRange ExprRange = E->getSourceRange();
10979
10980 // Only emit one error on the first const found. All other consts will emit
10981 // a note to the error.
10982 bool DiagnosticEmitted = false;
10983
10984 // Track if the current expression is the result of a dereference, and if the
10985 // next checked expression is the result of a dereference.
10986 bool IsDereference = false;
10987 bool NextIsDereference = false;
10988
10989 // Loop to process MemberExpr chains.
10990 while (true) {
10991 IsDereference = NextIsDereference;
10992
10993 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10994 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10995 NextIsDereference = ME->isArrow();
10996 const ValueDecl *VD = ME->getMemberDecl();
10997 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10998 // Mutable fields can be modified even if the class is const.
10999 if (Field->isMutable()) {
11000 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11001 break;
11002 }
11003
11004 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11005 if (!DiagnosticEmitted) {
11006 S.Diag(Loc, diag::err_typecheck_assign_const)
11007 << ExprRange << ConstMember << false /*static*/ << Field
11008 << Field->getType();
11009 DiagnosticEmitted = true;
11010 }
11011 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11012 << ConstMember << false /*static*/ << Field << Field->getType()
11013 << Field->getSourceRange();
11014 }
11015 E = ME->getBase();
11016 continue;
11017 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11018 if (VDecl->getType().isConstQualified()) {
11019 if (!DiagnosticEmitted) {
11020 S.Diag(Loc, diag::err_typecheck_assign_const)
11021 << ExprRange << ConstMember << true /*static*/ << VDecl
11022 << VDecl->getType();
11023 DiagnosticEmitted = true;
11024 }
11025 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11026 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11027 << VDecl->getSourceRange();
11028 }
11029 // Static fields do not inherit constness from parents.
11030 break;
11031 }
11032 break; // End MemberExpr
11033 } else if (const ArraySubscriptExpr *ASE =
11034 dyn_cast<ArraySubscriptExpr>(E)) {
11035 E = ASE->getBase()->IgnoreParenImpCasts();
11036 continue;
11037 } else if (const ExtVectorElementExpr *EVE =
11038 dyn_cast<ExtVectorElementExpr>(E)) {
11039 E = EVE->getBase()->IgnoreParenImpCasts();
11040 continue;
11041 }
11042 break;
11043 }
11044
11045 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11046 // Function calls
11047 const FunctionDecl *FD = CE->getDirectCallee();
11048 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11049 if (!DiagnosticEmitted) {
11050 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11051 << ConstFunction << FD;
11052 DiagnosticEmitted = true;
11053 }
11054 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11055 diag::note_typecheck_assign_const)
11056 << ConstFunction << FD << FD->getReturnType()
11057 << FD->getReturnTypeSourceRange();
11058 }
11059 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11060 // Point to variable declaration.
11061 if (const ValueDecl *VD = DRE->getDecl()) {
11062 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11063 if (!DiagnosticEmitted) {
11064 S.Diag(Loc, diag::err_typecheck_assign_const)
11065 << ExprRange << ConstVariable << VD << VD->getType();
11066 DiagnosticEmitted = true;
11067 }
11068 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11069 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11070 }
11071 }
11072 } else if (isa<CXXThisExpr>(E)) {
11073 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11074 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11075 if (MD->isConst()) {
11076 if (!DiagnosticEmitted) {
11077 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11078 << ConstMethod << MD;
11079 DiagnosticEmitted = true;
11080 }
11081 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11082 << ConstMethod << MD << MD->getSourceRange();
11083 }
11084 }
11085 }
11086 }
11087
11088 if (DiagnosticEmitted)
11089 return;
11090
11091 // Can't determine a more specific message, so display the generic error.
11092 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11093 }
11094
11095 enum OriginalExprKind {
11096 OEK_Variable,
11097 OEK_Member,
11098 OEK_LValue
11099 };
11100
11101 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11102 const RecordType *Ty,
11103 SourceLocation Loc, SourceRange Range,
11104 OriginalExprKind OEK,
11105 bool &DiagnosticEmitted) {
11106 std::vector<const RecordType *> RecordTypeList;
11107 RecordTypeList.push_back(Ty);
11108 unsigned NextToCheckIndex = 0;
11109 // We walk the record hierarchy breadth-first to ensure that we print
11110 // diagnostics in field nesting order.
11111 while (RecordTypeList.size() > NextToCheckIndex) {
11112 bool IsNested = NextToCheckIndex > 0;
11113 for (const FieldDecl *Field :
11114 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11115 // First, check every field for constness.
11116 QualType FieldTy = Field->getType();
11117 if (FieldTy.isConstQualified()) {
11118 if (!DiagnosticEmitted) {
11119 S.Diag(Loc, diag::err_typecheck_assign_const)
11120 << Range << NestedConstMember << OEK << VD
11121 << IsNested << Field;
11122 DiagnosticEmitted = true;
11123 }
11124 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11125 << NestedConstMember << IsNested << Field
11126 << FieldTy << Field->getSourceRange();
11127 }
11128
11129 // Then we append it to the list to check next in order.
11130 FieldTy = FieldTy.getCanonicalType();
11131 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11132 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11133 RecordTypeList.push_back(FieldRecTy);
11134 }
11135 }
11136 ++NextToCheckIndex;
11137 }
11138 }
11139
11140 /// Emit an error for the case where a record we are trying to assign to has a
11141 /// const-qualified field somewhere in its hierarchy.
11142 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11143 SourceLocation Loc) {
11144 QualType Ty = E->getType();
11145 assert(Ty->isRecordType() && "lvalue was not record?");
11146 SourceRange Range = E->getSourceRange();
11147 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11148 bool DiagEmitted = false;
11149
11150 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11151 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11152 Range, OEK_Member, DiagEmitted);
11153 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11154 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11155 Range, OEK_Variable, DiagEmitted);
11156 else
11157 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11158 Range, OEK_LValue, DiagEmitted);
11159 if (!DiagEmitted)
11160 DiagnoseConstAssignment(S, E, Loc);
11161 }
11162
11163 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11164 /// emit an error and return true. If so, return false.
11165 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11166 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11167
11168 S.CheckShadowingDeclModification(E, Loc);
11169
11170 SourceLocation OrigLoc = Loc;
11171 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11172 &Loc);
11173 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11174 IsLV = Expr::MLV_InvalidMessageExpression;
11175 if (IsLV == Expr::MLV_Valid)
11176 return false;
11177
11178 unsigned DiagID = 0;
11179 bool NeedType = false;
11180 switch (IsLV) { // C99 6.5.16p2
11181 case Expr::MLV_ConstQualified:
11182 // Use a specialized diagnostic when we're assigning to an object
11183 // from an enclosing function or block.
11184 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11185 if (NCCK == NCCK_Block)
11186 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11187 else
11188 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11189 break;
11190 }
11191
11192 // In ARC, use some specialized diagnostics for occasions where we
11193 // infer 'const'. These are always pseudo-strong variables.
11194 if (S.getLangOpts().ObjCAutoRefCount) {
11195 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11196 if (declRef && isa<VarDecl>(declRef->getDecl())) {
11197 VarDecl *var = cast<VarDecl>(declRef->getDecl());
11198
11199 // Use the normal diagnostic if it's pseudo-__strong but the
11200 // user actually wrote 'const'.
11201 if (var->isARCPseudoStrong() &&
11202 (!var->getTypeSourceInfo() ||
11203 !var->getTypeSourceInfo()->getType().isConstQualified())) {
11204 // There are three pseudo-strong cases:
11205 // - self
11206 ObjCMethodDecl *method = S.getCurMethodDecl();
11207 if (method && var == method->getSelfDecl()) {
11208 DiagID = method->isClassMethod()
11209 ? diag::err_typecheck_arc_assign_self_class_method
11210 : diag::err_typecheck_arc_assign_self;
11211
11212 // - Objective-C externally_retained attribute.
11213 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11214 isa<ParmVarDecl>(var)) {
11215 DiagID = diag::err_typecheck_arc_assign_externally_retained;
11216
11217 // - fast enumeration variables
11218 } else {
11219 DiagID = diag::err_typecheck_arr_assign_enumeration;
11220 }
11221
11222 SourceRange Assign;
11223 if (Loc != OrigLoc)
11224 Assign = SourceRange(OrigLoc, OrigLoc);
11225 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11226 // We need to preserve the AST regardless, so migration tool
11227 // can do its job.
11228 return false;
11229 }
11230 }
11231 }
11232
11233 // If none of the special cases above are triggered, then this is a
11234 // simple const assignment.
11235 if (DiagID == 0) {
11236 DiagnoseConstAssignment(S, E, Loc);
11237 return true;
11238 }
11239
11240 break;
11241 case Expr::MLV_ConstAddrSpace:
11242 DiagnoseConstAssignment(S, E, Loc);
11243 return true;
11244 case Expr::MLV_ConstQualifiedField:
11245 DiagnoseRecursiveConstFields(S, E, Loc);
11246 return true;
11247 case Expr::MLV_ArrayType:
11248 case Expr::MLV_ArrayTemporary:
11249 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11250 NeedType = true;
11251 break;
11252 case Expr::MLV_NotObjectType:
11253 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11254 NeedType = true;
11255 break;
11256 case Expr::MLV_LValueCast:
11257 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11258 break;
11259 case Expr::MLV_Valid:
11260 llvm_unreachable("did not take early return for MLV_Valid");
11261 case Expr::MLV_InvalidExpression:
11262 case Expr::MLV_MemberFunction:
11263 case Expr::MLV_ClassTemporary:
11264 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11265 break;
11266 case Expr::MLV_IncompleteType:
11267 case Expr::MLV_IncompleteVoidType:
11268 return S.RequireCompleteType(Loc, E->getType(),
11269 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11270 case Expr::MLV_DuplicateVectorComponents:
11271 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11272 break;
11273 case Expr::MLV_NoSetterProperty:
11274 llvm_unreachable("readonly properties should be processed differently");
11275 case Expr::MLV_InvalidMessageExpression:
11276 DiagID = diag::err_readonly_message_assignment;
11277 break;
11278 case Expr::MLV_SubObjCPropertySetting:
11279 DiagID = diag::err_no_subobject_property_setting;
11280 break;
11281 }
11282
11283 SourceRange Assign;
11284 if (Loc != OrigLoc)
11285 Assign = SourceRange(OrigLoc, OrigLoc);
11286 if (NeedType)
11287 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11288 else
11289 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11290 return true;
11291 }
11292
11293 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11294 SourceLocation Loc,
11295 Sema &Sema) {
11296 if (Sema.inTemplateInstantiation())
11297 return;
11298 if (Sema.isUnevaluatedContext())
11299 return;
11300 if (Loc.isInvalid() || Loc.isMacroID())
11301 return;
11302 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11303 return;
11304
11305 // C / C++ fields
11306 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11307 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11308 if (ML && MR) {
11309 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11310 return;
11311 const ValueDecl *LHSDecl =
11312 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11313 const ValueDecl *RHSDecl =
11314 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11315 if (LHSDecl != RHSDecl)
11316 return;
11317 if (LHSDecl->getType().isVolatileQualified())
11318 return;
11319 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11320 if (RefTy->getPointeeType().isVolatileQualified())
11321 return;
11322
11323 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11324 }
11325
11326 // Objective-C instance variables
11327 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11328 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11329 if (OL && OR && OL->getDecl() == OR->getDecl()) {
11330 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11331 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11332 if (RL && RR && RL->getDecl() == RR->getDecl())
11333 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11334 }
11335 }
11336
11337 // C99 6.5.16.1
11338 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11339 SourceLocation Loc,
11340 QualType CompoundType) {
11341 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11342
11343 // Verify that LHS is a modifiable lvalue, and emit error if not.
11344 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11345 return QualType();
11346
11347 QualType LHSType = LHSExpr->getType();
11348 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11349 CompoundType;
11350 // OpenCL v1.2 s6.1.1.1 p2:
11351 // The half data type can only be used to declare a pointer to a buffer that
11352 // contains half values
11353 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11354 LHSType->isHalfType()) {
11355 Diag(Loc, diag::err_opencl_half_load_store) << 1
11356 << LHSType.getUnqualifiedType();
11357 return QualType();
11358 }
11359
11360 AssignConvertType ConvTy;
11361 if (CompoundType.isNull()) {
11362 Expr *RHSCheck = RHS.get();
11363
11364 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11365
11366 QualType LHSTy(LHSType);
11367 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11368 if (RHS.isInvalid())
11369 return QualType();
11370 // Special case of NSObject attributes on c-style pointer types.
11371 if (ConvTy == IncompatiblePointer &&
11372 ((Context.isObjCNSObjectType(LHSType) &&
11373 RHSType->isObjCObjectPointerType()) ||
11374 (Context.isObjCNSObjectType(RHSType) &&
11375 LHSType->isObjCObjectPointerType())))
11376 ConvTy = Compatible;
11377
11378 if (ConvTy == Compatible &&
11379 LHSType->isObjCObjectType())
11380 Diag(Loc, diag::err_objc_object_assignment)
11381 << LHSType;
11382
11383 // If the RHS is a unary plus or minus, check to see if they = and + are
11384 // right next to each other. If so, the user may have typo'd "x =+ 4"
11385 // instead of "x += 4".
11386 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11387 RHSCheck = ICE->getSubExpr();
11388 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11389 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11390 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11391 // Only if the two operators are exactly adjacent.
11392 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11393 // And there is a space or other character before the subexpr of the
11394 // unary +/-. We don't want to warn on "x=-1".
11395 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11396 UO->getSubExpr()->getBeginLoc().isFileID()) {
11397 Diag(Loc, diag::warn_not_compound_assign)
11398 << (UO->getOpcode() == UO_Plus ? "+" : "-")
11399 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11400 }
11401 }
11402
11403 if (ConvTy == Compatible) {
11404 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11405 // Warn about retain cycles where a block captures the LHS, but
11406 // not if the LHS is a simple variable into which the block is
11407 // being stored...unless that variable can be captured by reference!
11408 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11409 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11410 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11411 checkRetainCycles(LHSExpr, RHS.get());
11412 }
11413
11414 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11415 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11416 // It is safe to assign a weak reference into a strong variable.
11417 // Although this code can still have problems:
11418 // id x = self.weakProp;
11419 // id y = self.weakProp;
11420 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11421 // paths through the function. This should be revisited if
11422 // -Wrepeated-use-of-weak is made flow-sensitive.
11423 // For ObjCWeak only, we do not warn if the assign is to a non-weak
11424 // variable, which will be valid for the current autorelease scope.
11425 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11426 RHS.get()->getBeginLoc()))
11427 getCurFunction()->markSafeWeakUse(RHS.get());
11428
11429 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11430 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11431 }
11432 }
11433 } else {
11434 // Compound assignment "x += y"
11435 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11436 }
11437
11438 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11439 RHS.get(), AA_Assigning))
11440 return QualType();
11441
11442 CheckForNullPointerDereference(*this, LHSExpr);
11443
11444 // C99 6.5.16p3: The type of an assignment expression is the type of the
11445 // left operand unless the left operand has qualified type, in which case
11446 // it is the unqualified version of the type of the left operand.
11447 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11448 // is converted to the type of the assignment expression (above).
11449 // C++ 5.17p1: the type of the assignment expression is that of its left
11450 // operand.
11451 return (getLangOpts().CPlusPlus
11452 ? LHSType : LHSType.getUnqualifiedType());
11453 }
11454
11455 // Only ignore explicit casts to void.
11456 static bool IgnoreCommaOperand(const Expr *E) {
11457 E = E->IgnoreParens();
11458
11459 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11460 if (CE->getCastKind() == CK_ToVoid) {
11461 return true;
11462 }
11463
11464 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11465 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11466 CE->getSubExpr()->getType()->isDependentType()) {
11467 return true;
11468 }
11469 }
11470
11471 return false;
11472 }
11473
11474 // Look for instances where it is likely the comma operator is confused with
11475 // another operator. There is a whitelist of acceptable expressions for the
11476 // left hand side of the comma operator, otherwise emit a warning.
11477 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11478 // No warnings in macros
11479 if (Loc.isMacroID())
11480 return;
11481
11482 // Don't warn in template instantiations.
11483 if (inTemplateInstantiation())
11484 return;
11485
11486 // Scope isn't fine-grained enough to whitelist the specific cases, so
11487 // instead, skip more than needed, then call back into here with the
11488 // CommaVisitor in SemaStmt.cpp.
11489 // The whitelisted locations are the initialization and increment portions
11490 // of a for loop. The additional checks are on the condition of
11491 // if statements, do/while loops, and for loops.
11492 // Differences in scope flags for C89 mode requires the extra logic.
11493 const unsigned ForIncrementFlags =
11494 getLangOpts().C99 || getLangOpts().CPlusPlus
11495 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11496 : Scope::ContinueScope | Scope::BreakScope;
11497 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11498 const unsigned ScopeFlags = getCurScope()->getFlags();
11499 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11500 (ScopeFlags & ForInitFlags) == ForInitFlags)
11501 return;
11502
11503 // If there are multiple comma operators used together, get the RHS of the
11504 // of the comma operator as the LHS.
11505 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11506 if (BO->getOpcode() != BO_Comma)
11507 break;
11508 LHS = BO->getRHS();
11509 }
11510
11511 // Only allow some expressions on LHS to not warn.
11512 if (IgnoreCommaOperand(LHS))
11513 return;
11514
11515 Diag(Loc, diag::warn_comma_operator);
11516 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11517 << LHS->getSourceRange()
11518 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11519 LangOpts.CPlusPlus ? "static_cast<void>("
11520 : "(void)(")
11521 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11522 ")");
11523 }
11524
11525 // C99 6.5.17
11526 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11527 SourceLocation Loc) {
11528 LHS = S.CheckPlaceholderExpr(LHS.get());
11529 RHS = S.CheckPlaceholderExpr(RHS.get());
11530 if (LHS.isInvalid() || RHS.isInvalid())
11531 return QualType();
11532
11533 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11534 // operands, but not unary promotions.
11535 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11536
11537 // So we treat the LHS as a ignored value, and in C++ we allow the
11538 // containing site to determine what should be done with the RHS.
11539 LHS = S.IgnoredValueConversions(LHS.get());
11540 if (LHS.isInvalid())
11541 return QualType();
11542
11543 S.DiagnoseUnusedExprResult(LHS.get());
11544
11545 if (!S.getLangOpts().CPlusPlus) {
11546 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11547 if (RHS.isInvalid())
11548 return QualType();
11549 if (!RHS.get()->getType()->isVoidType())
11550 S.RequireCompleteType(Loc, RHS.get()->getType(),
11551 diag::err_incomplete_type);
11552 }
11553
11554 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11555 S.DiagnoseCommaOperator(LHS.get(), Loc);
11556
11557 return RHS.get()->getType();
11558 }
11559
11560 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11561 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11562 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11563 ExprValueKind &VK,
11564 ExprObjectKind &OK,
11565 SourceLocation OpLoc,
11566 bool IsInc, bool IsPrefix) {
11567 if (Op->isTypeDependent())
11568 return S.Context.DependentTy;
11569
11570 QualType ResType = Op->getType();
11571 // Atomic types can be used for increment / decrement where the non-atomic
11572 // versions can, so ignore the _Atomic() specifier for the purpose of
11573 // checking.
11574 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11575 ResType = ResAtomicType->getValueType();
11576
11577 assert(!ResType.isNull() && "no type for increment/decrement expression");
11578
11579 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11580 // Decrement of bool is not allowed.
11581 if (!IsInc) {
11582 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11583 return QualType();
11584 }
11585 // Increment of bool sets it to true, but is deprecated.
11586 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11587 : diag::warn_increment_bool)
11588 << Op->getSourceRange();
11589 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11590 // Error on enum increments and decrements in C++ mode
11591 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11592 return QualType();
11593 } else if (ResType->isRealType()) {
11594 // OK!
11595 } else if (ResType->isPointerType()) {
11596 // C99 6.5.2.4p2, 6.5.6p2
11597 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11598 return QualType();
11599 } else if (ResType->isObjCObjectPointerType()) {
11600 // On modern runtimes, ObjC pointer arithmetic is forbidden.
11601 // Otherwise, we just need a complete type.
11602 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11603 checkArithmeticOnObjCPointer(S, OpLoc, Op))
11604 return QualType();
11605 } else if (ResType->isAnyComplexType()) {
11606 // C99 does not support ++/-- on complex types, we allow as an extension.
11607 S.Diag(OpLoc, diag::ext_integer_increment_complex)
11608 << ResType << Op->getSourceRange();
11609 } else if (ResType->isPlaceholderType()) {
11610 ExprResult PR = S.CheckPlaceholderExpr(Op);
11611 if (PR.isInvalid()) return QualType();
11612 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11613 IsInc, IsPrefix);
11614 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11615 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11616 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11617 (ResType->getAs<VectorType>()->getVectorKind() !=
11618 VectorType::AltiVecBool)) {
11619 // The z vector extensions allow ++ and -- for non-bool vectors.
11620 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11621 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11622 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11623 } else {
11624 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11625 << ResType << int(IsInc) << Op->getSourceRange();
11626 return QualType();
11627 }
11628 // At this point, we know we have a real, complex or pointer type.
11629 // Now make sure the operand is a modifiable lvalue.
11630 if (CheckForModifiableLvalue(Op, OpLoc, S))
11631 return QualType();
11632 // In C++, a prefix increment is the same type as the operand. Otherwise
11633 // (in C or with postfix), the increment is the unqualified type of the
11634 // operand.
11635 if (IsPrefix && S.getLangOpts().CPlusPlus) {
11636 VK = VK_LValue;
11637 OK = Op->getObjectKind();
11638 return ResType;
11639 } else {
11640 VK = VK_RValue;
11641 return ResType.getUnqualifiedType();
11642 }
11643 }
11644
11645
11646 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11647 /// This routine allows us to typecheck complex/recursive expressions
11648 /// where the declaration is needed for type checking. We only need to
11649 /// handle cases when the expression references a function designator
11650 /// or is an lvalue. Here are some examples:
11651 /// - &(x) => x
11652 /// - &*****f => f for f a function designator.
11653 /// - &s.xx => s
11654 /// - &s.zz[1].yy -> s, if zz is an array
11655 /// - *(x + 1) -> x, if x is an array
11656 /// - &"123"[2] -> 0
11657 /// - & __real__ x -> x
11658 static ValueDecl *getPrimaryDecl(Expr *E) {
11659 switch (E->getStmtClass()) {
11660 case Stmt::DeclRefExprClass:
11661 return cast<DeclRefExpr>(E)->getDecl();
11662 case Stmt::MemberExprClass:
11663 // If this is an arrow operator, the address is an offset from
11664 // the base's value, so the object the base refers to is
11665 // irrelevant.
11666 if (cast<MemberExpr>(E)->isArrow())
11667 return nullptr;
11668 // Otherwise, the expression refers to a part of the base
11669 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11670 case Stmt::ArraySubscriptExprClass: {
11671 // FIXME: This code shouldn't be necessary! We should catch the implicit
11672 // promotion of register arrays earlier.
11673 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11674 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11675 if (ICE->getSubExpr()->getType()->isArrayType())
11676 return getPrimaryDecl(ICE->getSubExpr());
11677 }
11678 return nullptr;
11679 }
11680 case Stmt::UnaryOperatorClass: {
11681 UnaryOperator *UO = cast<UnaryOperator>(E);
11682
11683 switch(UO->getOpcode()) {
11684 case UO_Real:
11685 case UO_Imag:
11686 case UO_Extension:
11687 return getPrimaryDecl(UO->getSubExpr());
11688 default:
11689 return nullptr;
11690 }
11691 }
11692 case Stmt::ParenExprClass:
11693 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11694 case Stmt::ImplicitCastExprClass:
11695 // If the result of an implicit cast is an l-value, we care about
11696 // the sub-expression; otherwise, the result here doesn't matter.
11697 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11698 default:
11699 return nullptr;
11700 }
11701 }
11702
11703 namespace {
11704 enum {
11705 AO_Bit_Field = 0,
11706 AO_Vector_Element = 1,
11707 AO_Property_Expansion = 2,
11708 AO_Register_Variable = 3,
11709 AO_No_Error = 4
11710 };
11711 }
11712 /// Diagnose invalid operand for address of operations.
11713 ///
11714 /// \param Type The type of operand which cannot have its address taken.
11715 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11716 Expr *E, unsigned Type) {
11717 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11718 }
11719
11720 /// CheckAddressOfOperand - The operand of & must be either a function
11721 /// designator or an lvalue designating an object. If it is an lvalue, the
11722 /// object cannot be declared with storage class register or be a bit field.
11723 /// Note: The usual conversions are *not* applied to the operand of the &
11724 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11725 /// In C++, the operand might be an overloaded function name, in which case
11726 /// we allow the '&' but retain the overloaded-function type.
11727 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11728 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11729 if (PTy->getKind() == BuiltinType::Overload) {
11730 Expr *E = OrigOp.get()->IgnoreParens();
11731 if (!isa<OverloadExpr>(E)) {
11732 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11733 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11734 << OrigOp.get()->getSourceRange();
11735 return QualType();
11736 }
11737
11738 OverloadExpr *Ovl = cast<OverloadExpr>(E);
11739 if (isa<UnresolvedMemberExpr>(Ovl))
11740 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11741 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11742 << OrigOp.get()->getSourceRange();
11743 return QualType();
11744 }
11745
11746 return Context.OverloadTy;
11747 }
11748
11749 if (PTy->getKind() == BuiltinType::UnknownAny)
11750 return Context.UnknownAnyTy;
11751
11752 if (PTy->getKind() == BuiltinType::BoundMember) {
11753 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11754 << OrigOp.get()->getSourceRange();
11755 return QualType();
11756 }
11757
11758 OrigOp = CheckPlaceholderExpr(OrigOp.get());
11759 if (OrigOp.isInvalid()) return QualType();
11760 }
11761
11762 if (OrigOp.get()->isTypeDependent())
11763 return Context.DependentTy;
11764
11765 assert(!OrigOp.get()->getType()->isPlaceholderType());
11766
11767 // Make sure to ignore parentheses in subsequent checks
11768 Expr *op = OrigOp.get()->IgnoreParens();
11769
11770 // In OpenCL captures for blocks called as lambda functions
11771 // are located in the private address space. Blocks used in
11772 // enqueue_kernel can be located in a different address space
11773 // depending on a vendor implementation. Thus preventing
11774 // taking an address of the capture to avoid invalid AS casts.
11775 if (LangOpts.OpenCL) {
11776 auto* VarRef = dyn_cast<DeclRefExpr>(op);
11777 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11778 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11779 return QualType();
11780 }
11781 }
11782
11783 if (getLangOpts().C99) {
11784 // Implement C99-only parts of addressof rules.
11785 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11786 if (uOp->getOpcode() == UO_Deref)
11787 // Per C99 6.5.3.2, the address of a deref always returns a valid result
11788 // (assuming the deref expression is valid).
11789 return uOp->getSubExpr()->getType();
11790 }
11791 // Technically, there should be a check for array subscript
11792 // expressions here, but the result of one is always an lvalue anyway.
11793 }
11794 ValueDecl *dcl = getPrimaryDecl(op);
11795
11796 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11797 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11798 op->getBeginLoc()))
11799 return QualType();
11800
11801 Expr::LValueClassification lval = op->ClassifyLValue(Context);
11802 unsigned AddressOfError = AO_No_Error;
11803
11804 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11805 bool sfinae = (bool)isSFINAEContext();
11806 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11807 : diag::ext_typecheck_addrof_temporary)
11808 << op->getType() << op->getSourceRange();
11809 if (sfinae)
11810 return QualType();
11811 // Materialize the temporary as an lvalue so that we can take its address.
11812 OrigOp = op =
11813 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11814 } else if (isa<ObjCSelectorExpr>(op)) {
11815 return Context.getPointerType(op->getType());
11816 } else if (lval == Expr::LV_MemberFunction) {
11817 // If it's an instance method, make a member pointer.
11818 // The expression must have exactly the form &A::foo.
11819
11820 // If the underlying expression isn't a decl ref, give up.
11821 if (!isa<DeclRefExpr>(op)) {
11822 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11823 << OrigOp.get()->getSourceRange();
11824 return QualType();
11825 }
11826 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11827 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11828
11829 // The id-expression was parenthesized.
11830 if (OrigOp.get() != DRE) {
11831 Diag(OpLoc, diag::err_parens_pointer_member_function)
11832 << OrigOp.get()->getSourceRange();
11833
11834 // The method was named without a qualifier.
11835 } else if (!DRE->getQualifier()) {
11836 if (MD->getParent()->getName().empty())
11837 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11838 << op->getSourceRange();
11839 else {
11840 SmallString<32> Str;
11841 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11842 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11843 << op->getSourceRange()
11844 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11845 }
11846 }
11847
11848 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11849 if (isa<CXXDestructorDecl>(MD))
11850 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11851
11852 QualType MPTy = Context.getMemberPointerType(
11853 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11854 // Under the MS ABI, lock down the inheritance model now.
11855 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11856 (void)isCompleteType(OpLoc, MPTy);
11857 return MPTy;
11858 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11859 // C99 6.5.3.2p1
11860 // The operand must be either an l-value or a function designator
11861 if (!op->getType()->isFunctionType()) {
11862 // Use a special diagnostic for loads from property references.
11863 if (isa<PseudoObjectExpr>(op)) {
11864 AddressOfError = AO_Property_Expansion;
11865 } else {
11866 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11867 << op->getType() << op->getSourceRange();
11868 return QualType();
11869 }
11870 }
11871 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11872 // The operand cannot be a bit-field
11873 AddressOfError = AO_Bit_Field;
11874 } else if (op->getObjectKind() == OK_VectorComponent) {
11875 // The operand cannot be an element of a vector
11876 AddressOfError = AO_Vector_Element;
11877 } else if (dcl) { // C99 6.5.3.2p1
11878 // We have an lvalue with a decl. Make sure the decl is not declared
11879 // with the register storage-class specifier.
11880 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11881 // in C++ it is not error to take address of a register
11882 // variable (c++03 7.1.1P3)
11883 if (vd->getStorageClass() == SC_Register &&
11884 !getLangOpts().CPlusPlus) {
11885 AddressOfError = AO_Register_Variable;
11886 }
11887 } else if (isa<MSPropertyDecl>(dcl)) {
11888 AddressOfError = AO_Property_Expansion;
11889 } else if (isa<FunctionTemplateDecl>(dcl)) {
11890 return Context.OverloadTy;
11891 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11892 // Okay: we can take the address of a field.
11893 // Could be a pointer to member, though, if there is an explicit
11894 // scope qualifier for the class.
11895 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11896 DeclContext *Ctx = dcl->getDeclContext();
11897 if (Ctx && Ctx->isRecord()) {
11898 if (dcl->getType()->isReferenceType()) {
11899 Diag(OpLoc,
11900 diag::err_cannot_form_pointer_to_member_of_reference_type)
11901 << dcl->getDeclName() << dcl->getType();
11902 return QualType();
11903 }
11904
11905 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11906 Ctx = Ctx->getParent();
11907
11908 QualType MPTy = Context.getMemberPointerType(
11909 op->getType(),
11910 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11911 // Under the MS ABI, lock down the inheritance model now.
11912 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11913 (void)isCompleteType(OpLoc, MPTy);
11914 return MPTy;
11915 }
11916 }
11917 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11918 !isa<BindingDecl>(dcl))
11919 llvm_unreachable("Unknown/unexpected decl type");
11920 }
11921
11922 if (AddressOfError != AO_No_Error) {
11923 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11924 return QualType();
11925 }
11926
11927 if (lval == Expr::LV_IncompleteVoidType) {
11928 // Taking the address of a void variable is technically illegal, but we
11929 // allow it in cases which are otherwise valid.
11930 // Example: "extern void x; void* y = &x;".
11931 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11932 }
11933
11934 // If the operand has type "type", the result has type "pointer to type".
11935 if (op->getType()->isObjCObjectType())
11936 return Context.getObjCObjectPointerType(op->getType());
11937
11938 CheckAddressOfPackedMember(op);
11939
11940 return Context.getPointerType(op->getType());
11941 }
11942
11943 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11944 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11945 if (!DRE)
11946 return;
11947 const Decl *D = DRE->getDecl();
11948 if (!D)
11949 return;
11950 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11951 if (!Param)
11952 return;
11953 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11954 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11955 return;
11956 if (FunctionScopeInfo *FD = S.getCurFunction())
11957 if (!FD->ModifiedNonNullParams.count(Param))
11958 FD->ModifiedNonNullParams.insert(Param);
11959 }
11960
11961 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11962 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11963 SourceLocation OpLoc) {
11964 if (Op->isTypeDependent())
11965 return S.Context.DependentTy;
11966
11967 ExprResult ConvResult = S.UsualUnaryConversions(Op);
11968 if (ConvResult.isInvalid())
11969 return QualType();
11970 Op = ConvResult.get();
11971 QualType OpTy = Op->getType();
11972 QualType Result;
11973
11974 if (isa<CXXReinterpretCastExpr>(Op)) {
11975 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11976 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11977 Op->getSourceRange());
11978 }
11979
11980 if (const PointerType *PT = OpTy->getAs<PointerType>())
11981 {
11982 Result = PT->getPointeeType();
11983 }
11984 else if (const ObjCObjectPointerType *OPT =
11985 OpTy->getAs<ObjCObjectPointerType>())
11986 Result = OPT->getPointeeType();
11987 else {
11988 ExprResult PR = S.CheckPlaceholderExpr(Op);
11989 if (PR.isInvalid()) return QualType();
11990 if (PR.get() != Op)
11991 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11992 }
11993
11994 if (Result.isNull()) {
11995 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11996 << OpTy << Op->getSourceRange();
11997 return QualType();
11998 }
11999
12000 // Note that per both C89 and C99, indirection is always legal, even if Result
12001 // is an incomplete type or void. It would be possible to warn about
12002 // dereferencing a void pointer, but it's completely well-defined, and such a
12003 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12004 // for pointers to 'void' but is fine for any other pointer type:
12005 //
12006 // C++ [expr.unary.op]p1:
12007 // [...] the expression to which [the unary * operator] is applied shall
12008 // be a pointer to an object type, or a pointer to a function type
12009 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12010 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12011 << OpTy << Op->getSourceRange();
12012
12013 // Dereferences are usually l-values...
12014 VK = VK_LValue;
12015
12016 // ...except that certain expressions are never l-values in C.
12017 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12018 VK = VK_RValue;
12019
12020 return Result;
12021 }
12022
12023 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12024 BinaryOperatorKind Opc;
12025 switch (Kind) {
12026 default: llvm_unreachable("Unknown binop!");
12027 case tok::periodstar: Opc = BO_PtrMemD; break;
12028 case tok::arrowstar: Opc = BO_PtrMemI; break;
12029 case tok::star: Opc = BO_Mul; break;
12030 case tok::slash: Opc = BO_Div; break;
12031 case tok::percent: Opc = BO_Rem; break;
12032 case tok::plus: Opc = BO_Add; break;
12033 case tok::minus: Opc = BO_Sub; break;
12034 case tok::lessless: Opc = BO_Shl; break;
12035 case tok::greatergreater: Opc = BO_Shr; break;
12036 case tok::lessequal: Opc = BO_LE; break;
12037 case tok::less: Opc = BO_LT; break;
12038 case tok::greaterequal: Opc = BO_GE; break;
12039 case tok::greater: Opc = BO_GT; break;
12040 case tok::exclaimequal: Opc = BO_NE; break;
12041 case tok::equalequal: Opc = BO_EQ; break;
12042 case tok::spaceship: Opc = BO_Cmp; break;
12043 case tok::amp: Opc = BO_And; break;
12044 case tok::caret: Opc = BO_Xor; break;
12045 case tok::pipe: Opc = BO_Or; break;
12046 case tok::ampamp: Opc = BO_LAnd; break;
12047 case tok::pipepipe: Opc = BO_LOr; break;
12048 case tok::equal: Opc = BO_Assign; break;
12049 case tok::starequal: Opc = BO_MulAssign; break;
12050 case tok::slashequal: Opc = BO_DivAssign; break;
12051 case tok::percentequal: Opc = BO_RemAssign; break;
12052 case tok::plusequal: Opc = BO_AddAssign; break;
12053 case tok::minusequal: Opc = BO_SubAssign; break;
12054 case tok::lesslessequal: Opc = BO_ShlAssign; break;
12055 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12056 case tok::ampequal: Opc = BO_AndAssign; break;
12057 case tok::caretequal: Opc = BO_XorAssign; break;
12058 case tok::pipeequal: Opc = BO_OrAssign; break;
12059 case tok::comma: Opc = BO_Comma; break;
12060 }
12061 return Opc;
12062 }
12063
12064 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12065 tok::TokenKind Kind) {
12066 UnaryOperatorKind Opc;
12067 switch (Kind) {
12068 default: llvm_unreachable("Unknown unary op!");
12069 case tok::plusplus: Opc = UO_PreInc; break;
12070 case tok::minusminus: Opc = UO_PreDec; break;
12071 case tok::amp: Opc = UO_AddrOf; break;
12072 case tok::star: Opc = UO_Deref; break;
12073 case tok::plus: Opc = UO_Plus; break;
12074 case tok::minus: Opc = UO_Minus; break;
12075 case tok::tilde: Opc = UO_Not; break;
12076 case tok::exclaim: Opc = UO_LNot; break;
12077 case tok::kw___real: Opc = UO_Real; break;
12078 case tok::kw___imag: Opc = UO_Imag; break;
12079 case tok::kw___extension__: Opc = UO_Extension; break;
12080 }
12081 return Opc;
12082 }
12083
12084 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12085 /// This warning suppressed in the event of macro expansions.
12086 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12087 SourceLocation OpLoc, bool IsBuiltin) {
12088 if (S.inTemplateInstantiation())
12089 return;
12090 if (S.isUnevaluatedContext())
12091 return;
12092 if (OpLoc.isInvalid() || OpLoc.isMacroID())
12093 return;
12094 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12095 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12096 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12097 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12098 if (!LHSDeclRef || !RHSDeclRef ||
12099 LHSDeclRef->getLocation().isMacroID() ||
12100 RHSDeclRef->getLocation().isMacroID())
12101 return;
12102 const ValueDecl *LHSDecl =
12103 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12104 const ValueDecl *RHSDecl =
12105 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12106 if (LHSDecl != RHSDecl)
12107 return;
12108 if (LHSDecl->getType().isVolatileQualified())
12109 return;
12110 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12111 if (RefTy->getPointeeType().isVolatileQualified())
12112 return;
12113
12114 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12115 : diag::warn_self_assignment_overloaded)
12116 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12117 << RHSExpr->getSourceRange();
12118 }
12119
12120 /// Check if a bitwise-& is performed on an Objective-C pointer. This
12121 /// is usually indicative of introspection within the Objective-C pointer.
12122 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12123 SourceLocation OpLoc) {
12124 if (!S.getLangOpts().ObjC)
12125 return;
12126
12127 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12128 const Expr *LHS = L.get();
12129 const Expr *RHS = R.get();
12130
12131 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12132 ObjCPointerExpr = LHS;
12133 OtherExpr = RHS;
12134 }
12135 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12136 ObjCPointerExpr = RHS;
12137 OtherExpr = LHS;
12138 }
12139
12140 // This warning is deliberately made very specific to reduce false
12141 // positives with logic that uses '&' for hashing. This logic mainly
12142 // looks for code trying to introspect into tagged pointers, which
12143 // code should generally never do.
12144 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12145 unsigned Diag = diag::warn_objc_pointer_masking;
12146 // Determine if we are introspecting the result of performSelectorXXX.
12147 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12148 // Special case messages to -performSelector and friends, which
12149 // can return non-pointer values boxed in a pointer value.
12150 // Some clients may wish to silence warnings in this subcase.
12151 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12152 Selector S = ME->getSelector();
12153 StringRef SelArg0 = S.getNameForSlot(0);
12154 if (SelArg0.startswith("performSelector"))
12155 Diag = diag::warn_objc_pointer_masking_performSelector;
12156 }
12157
12158 S.Diag(OpLoc, Diag)
12159 << ObjCPointerExpr->getSourceRange();
12160 }
12161 }
12162
12163 static NamedDecl *getDeclFromExpr(Expr *E) {
12164 if (!E)
12165 return nullptr;
12166 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12167 return DRE->getDecl();
12168 if (auto *ME = dyn_cast<MemberExpr>(E))
12169 return ME->getMemberDecl();
12170 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12171 return IRE->getDecl();
12172 return nullptr;
12173 }
12174
12175 // This helper function promotes a binary operator's operands (which are of a
12176 // half vector type) to a vector of floats and then truncates the result to
12177 // a vector of either half or short.
12178 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12179 BinaryOperatorKind Opc, QualType ResultTy,
12180 ExprValueKind VK, ExprObjectKind OK,
12181 bool IsCompAssign, SourceLocation OpLoc,
12182 FPOptions FPFeatures) {
12183 auto &Context = S.getASTContext();
12184 assert((isVector(ResultTy, Context.HalfTy) ||
12185 isVector(ResultTy, Context.ShortTy)) &&
12186 "Result must be a vector of half or short");
12187 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12188 isVector(RHS.get()->getType(), Context.HalfTy) &&
12189 "both operands expected to be a half vector");
12190
12191 RHS = convertVector(RHS.get(), Context.FloatTy, S);
12192 QualType BinOpResTy = RHS.get()->getType();
12193
12194 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12195 // change BinOpResTy to a vector of ints.
12196 if (isVector(ResultTy, Context.ShortTy))
12197 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12198
12199 if (IsCompAssign)
12200 return new (Context) CompoundAssignOperator(
12201 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12202 OpLoc, FPFeatures);
12203
12204 LHS = convertVector(LHS.get(), Context.FloatTy, S);
12205 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12206 VK, OK, OpLoc, FPFeatures);
12207 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12208 }
12209
12210 static std::pair<ExprResult, ExprResult>
12211 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12212 Expr *RHSExpr) {
12213 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12214 if (!S.getLangOpts().CPlusPlus) {
12215 // C cannot handle TypoExpr nodes on either side of a binop because it
12216 // doesn't handle dependent types properly, so make sure any TypoExprs have
12217 // been dealt with before checking the operands.
12218 LHS = S.CorrectDelayedTyposInExpr(LHS);
12219 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12220 if (Opc != BO_Assign)
12221 return ExprResult(E);
12222 // Avoid correcting the RHS to the same Expr as the LHS.
12223 Decl *D = getDeclFromExpr(E);
12224 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12225 });
12226 }
12227 return std::make_pair(LHS, RHS);
12228 }
12229
12230 /// Returns true if conversion between vectors of halfs and vectors of floats
12231 /// is needed.
12232 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12233 QualType SrcType) {
12234 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12235 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12236 isVector(SrcType, Ctx.HalfTy);
12237 }
12238
12239 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12240 /// operator @p Opc at location @c TokLoc. This routine only supports
12241 /// built-in operations; ActOnBinOp handles overloaded operators.
12242 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12243 BinaryOperatorKind Opc,
12244 Expr *LHSExpr, Expr *RHSExpr) {
12245 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12246 // The syntax only allows initializer lists on the RHS of assignment,
12247 // so we don't need to worry about accepting invalid code for
12248 // non-assignment operators.
12249 // C++11 5.17p9:
12250 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12251 // of x = {} is x = T().
12252 InitializationKind Kind = InitializationKind::CreateDirectList(
12253 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12254 InitializedEntity Entity =
12255 InitializedEntity::InitializeTemporary(LHSExpr->getType());
12256 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12257 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12258 if (Init.isInvalid())
12259 return Init;
12260 RHSExpr = Init.get();
12261 }
12262
12263 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12264 QualType ResultTy; // Result type of the binary operator.
12265 // The following two variables are used for compound assignment operators
12266 QualType CompLHSTy; // Type of LHS after promotions for computation
12267 QualType CompResultTy; // Type of computation result
12268 ExprValueKind VK = VK_RValue;
12269 ExprObjectKind OK = OK_Ordinary;
12270 bool ConvertHalfVec = false;
12271
12272 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12273 if (!LHS.isUsable() || !RHS.isUsable())
12274 return ExprError();
12275
12276 if (getLangOpts().OpenCL) {
12277 QualType LHSTy = LHSExpr->getType();
12278 QualType RHSTy = RHSExpr->getType();
12279 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12280 // the ATOMIC_VAR_INIT macro.
12281 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12282 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12283 if (BO_Assign == Opc)
12284 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12285 else
12286 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12287 return ExprError();
12288 }
12289
12290 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12291 // only with a builtin functions and therefore should be disallowed here.
12292 if (LHSTy->isImageType() || RHSTy->isImageType() ||
12293 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12294 LHSTy->isPipeType() || RHSTy->isPipeType() ||
12295 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12296 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12297 return ExprError();
12298 }
12299 }
12300
12301 switch (Opc) {
12302 case BO_Assign:
12303 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12304 if (getLangOpts().CPlusPlus &&
12305 LHS.get()->getObjectKind() != OK_ObjCProperty) {
12306 VK = LHS.get()->getValueKind();
12307 OK = LHS.get()->getObjectKind();
12308 }
12309 if (!ResultTy.isNull()) {
12310 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12311 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12312 }
12313 RecordModifiableNonNullParam(*this, LHS.get());
12314 break;
12315 case BO_PtrMemD:
12316 case BO_PtrMemI:
12317 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12318 Opc == BO_PtrMemI);
12319 break;
12320 case BO_Mul:
12321 case BO_Div:
12322 ConvertHalfVec = true;
12323 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12324 Opc == BO_Div);
12325 break;
12326 case BO_Rem:
12327 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12328 break;
12329 case BO_Add:
12330 ConvertHalfVec = true;
12331 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12332 break;
12333 case BO_Sub:
12334 ConvertHalfVec = true;
12335 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12336 break;
12337 case BO_Shl:
12338 case BO_Shr:
12339 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12340 break;
12341 case BO_LE:
12342 case BO_LT:
12343 case BO_GE:
12344 case BO_GT:
12345 ConvertHalfVec = true;
12346 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12347 break;
12348 case BO_EQ:
12349 case BO_NE:
12350 ConvertHalfVec = true;
12351 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12352 break;
12353 case BO_Cmp:
12354 ConvertHalfVec = true;
12355 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12356 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12357 break;
12358 case BO_And:
12359 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12360 LLVM_FALLTHROUGH;
12361 case BO_Xor:
12362 case BO_Or:
12363 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12364 break;
12365 case BO_LAnd:
12366 case BO_LOr:
12367 ConvertHalfVec = true;
12368 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12369 break;
12370 case BO_MulAssign:
12371 case BO_DivAssign:
12372 ConvertHalfVec = true;
12373 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12374 Opc == BO_DivAssign);
12375 CompLHSTy = CompResultTy;
12376 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12377 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12378 break;
12379 case BO_RemAssign:
12380 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12381 CompLHSTy = CompResultTy;
12382 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12383 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12384 break;
12385 case BO_AddAssign:
12386 ConvertHalfVec = true;
12387 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12388 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12389 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12390 break;
12391 case BO_SubAssign:
12392 ConvertHalfVec = true;
12393 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12394 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12395 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12396 break;
12397 case BO_ShlAssign:
12398 case BO_ShrAssign:
12399 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12400 CompLHSTy = CompResultTy;
12401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12402 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12403 break;
12404 case BO_AndAssign:
12405 case BO_OrAssign: // fallthrough
12406 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12407 LLVM_FALLTHROUGH;
12408 case BO_XorAssign:
12409 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12410 CompLHSTy = CompResultTy;
12411 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12412 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12413 break;
12414 case BO_Comma:
12415 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12416 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12417 VK = RHS.get()->getValueKind();
12418 OK = RHS.get()->getObjectKind();
12419 }
12420 break;
12421 }
12422 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12423 return ExprError();
12424
12425 // Some of the binary operations require promoting operands of half vector to
12426 // float vectors and truncating the result back to half vector. For now, we do
12427 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12428 // arm64).
12429 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12430 isVector(LHS.get()->getType(), Context.HalfTy) &&
12431 "both sides are half vectors or neither sides are");
12432 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12433 LHS.get()->getType());
12434
12435 // Check for array bounds violations for both sides of the BinaryOperator
12436 CheckArrayAccess(LHS.get());
12437 CheckArrayAccess(RHS.get());
12438
12439 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12440 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12441 &Context.Idents.get("object_setClass"),
12442 SourceLocation(), LookupOrdinaryName);
12443 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12444 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12445 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12446 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12447 "object_setClass(")
12448 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12449 ",")
12450 << FixItHint::CreateInsertion(RHSLocEnd, ")");
12451 }
12452 else
12453 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12454 }
12455 else if (const ObjCIvarRefExpr *OIRE =
12456 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12457 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12458
12459 // Opc is not a compound assignment if CompResultTy is null.
12460 if (CompResultTy.isNull()) {
12461 if (ConvertHalfVec)
12462 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12463 OpLoc, FPFeatures);
12464 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12465 OK, OpLoc, FPFeatures);
12466 }
12467
12468 // Handle compound assignments.
12469 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12470 OK_ObjCProperty) {
12471 VK = VK_LValue;
12472 OK = LHS.get()->getObjectKind();
12473 }
12474
12475 if (ConvertHalfVec)
12476 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12477 OpLoc, FPFeatures);
12478
12479 return new (Context) CompoundAssignOperator(
12480 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12481 OpLoc, FPFeatures);
12482 }
12483
12484 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12485 /// operators are mixed in a way that suggests that the programmer forgot that
12486 /// comparison operators have higher precedence. The most typical example of
12487 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12488 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12489 SourceLocation OpLoc, Expr *LHSExpr,
12490 Expr *RHSExpr) {
12491 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12492 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12493
12494 // Check that one of the sides is a comparison operator and the other isn't.
12495 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12496 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12497 if (isLeftComp == isRightComp)
12498 return;
12499
12500 // Bitwise operations are sometimes used as eager logical ops.
12501 // Don't diagnose this.
12502 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12503 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12504 if (isLeftBitwise || isRightBitwise)
12505 return;
12506
12507 SourceRange DiagRange = isLeftComp
12508 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12509 : SourceRange(OpLoc, RHSExpr->getEndLoc());
12510 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12511 SourceRange ParensRange =
12512 isLeftComp
12513 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12514 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12515
12516 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12517 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12518 SuggestParentheses(Self, OpLoc,
12519 Self.PDiag(diag::note_precedence_silence) << OpStr,
12520 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12521 SuggestParentheses(Self, OpLoc,
12522 Self.PDiag(diag::note_precedence_bitwise_first)
12523 << BinaryOperator::getOpcodeStr(Opc),
12524 ParensRange);
12525 }
12526
12527 /// It accepts a '&&' expr that is inside a '||' one.
12528 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12529 /// in parentheses.
12530 static void
12531 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12532 BinaryOperator *Bop) {
12533 assert(Bop->getOpcode() == BO_LAnd);
12534 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12535 << Bop->getSourceRange() << OpLoc;
12536 SuggestParentheses(Self, Bop->getOperatorLoc(),
12537 Self.PDiag(diag::note_precedence_silence)
12538 << Bop->getOpcodeStr(),
12539 Bop->getSourceRange());
12540 }
12541
12542 /// Returns true if the given expression can be evaluated as a constant
12543 /// 'true'.
12544 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12545 bool Res;
12546 return !E->isValueDependent() &&
12547 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12548 }
12549
12550 /// Returns true if the given expression can be evaluated as a constant
12551 /// 'false'.
12552 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12553 bool Res;
12554 return !E->isValueDependent() &&
12555 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12556 }
12557
12558 /// Look for '&&' in the left hand of a '||' expr.
12559 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12560 Expr *LHSExpr, Expr *RHSExpr) {
12561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12562 if (Bop->getOpcode() == BO_LAnd) {
12563 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12564 if (EvaluatesAsFalse(S, RHSExpr))
12565 return;
12566 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12567 if (!EvaluatesAsTrue(S, Bop->getLHS()))
12568 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12569 } else if (Bop->getOpcode() == BO_LOr) {
12570 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12571 // If it's "a || b && 1 || c" we didn't warn earlier for
12572 // "a || b && 1", but warn now.
12573 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12575 }
12576 }
12577 }
12578 }
12579
12580 /// Look for '&&' in the right hand of a '||' expr.
12581 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12582 Expr *LHSExpr, Expr *RHSExpr) {
12583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12584 if (Bop->getOpcode() == BO_LAnd) {
12585 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12586 if (EvaluatesAsFalse(S, LHSExpr))
12587 return;
12588 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12589 if (!EvaluatesAsTrue(S, Bop->getRHS()))
12590 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12591 }
12592 }
12593 }
12594
12595 /// Look for bitwise op in the left or right hand of a bitwise op with
12596 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12597 /// the '&' expression in parentheses.
12598 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12599 SourceLocation OpLoc, Expr *SubExpr) {
12600 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12601 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12602 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12603 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12604 << Bop->getSourceRange() << OpLoc;
12605 SuggestParentheses(S, Bop->getOperatorLoc(),
12606 S.PDiag(diag::note_precedence_silence)
12607 << Bop->getOpcodeStr(),
12608 Bop->getSourceRange());
12609 }
12610 }
12611 }
12612
12613 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12614 Expr *SubExpr, StringRef Shift) {
12615 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12616 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12617 StringRef Op = Bop->getOpcodeStr();
12618 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12619 << Bop->getSourceRange() << OpLoc << Shift << Op;
12620 SuggestParentheses(S, Bop->getOperatorLoc(),
12621 S.PDiag(diag::note_precedence_silence) << Op,
12622 Bop->getSourceRange());
12623 }
12624 }
12625 }
12626
12627 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12628 Expr *LHSExpr, Expr *RHSExpr) {
12629 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12630 if (!OCE)
12631 return;
12632
12633 FunctionDecl *FD = OCE->getDirectCallee();
12634 if (!FD || !FD->isOverloadedOperator())
12635 return;
12636
12637 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12638 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12639 return;
12640
12641 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12642 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12643 << (Kind == OO_LessLess);
12644 SuggestParentheses(S, OCE->getOperatorLoc(),
12645 S.PDiag(diag::note_precedence_silence)
12646 << (Kind == OO_LessLess ? "<<" : ">>"),
12647 OCE->getSourceRange());
12648 SuggestParentheses(
12649 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12650 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12651 }
12652
12653 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12654 /// precedence.
12655 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12656 SourceLocation OpLoc, Expr *LHSExpr,
12657 Expr *RHSExpr){
12658 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12659 if (BinaryOperator::isBitwiseOp(Opc))
12660 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12661
12662 // Diagnose "arg1 & arg2 | arg3"
12663 if ((Opc == BO_Or || Opc == BO_Xor) &&
12664 !OpLoc.isMacroID()/* Don't warn in macros. */) {
12665 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12666 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12667 }
12668
12669 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12670 // We don't warn for 'assert(a || b && "bad")' since this is safe.
12671 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12672 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12673 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12674 }
12675
12676 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12677 || Opc == BO_Shr) {
12678 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12679 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12680 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12681 }
12682
12683 // Warn on overloaded shift operators and comparisons, such as:
12684 // cout << 5 == 4;
12685 if (BinaryOperator::isComparisonOp(Opc))
12686 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12687 }
12688
12689 // Binary Operators. 'Tok' is the token for the operator.
12690 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12691 tok::TokenKind Kind,
12692 Expr *LHSExpr, Expr *RHSExpr) {
12693 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12694 assert(LHSExpr && "ActOnBinOp(): missing left expression");
12695 assert(RHSExpr && "ActOnBinOp(): missing right expression");
12696
12697 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12698 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12699
12700 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12701 }
12702
12703 /// Build an overloaded binary operator expression in the given scope.
12704 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12705 BinaryOperatorKind Opc,
12706 Expr *LHS, Expr *RHS) {
12707 switch (Opc) {
12708 case BO_Assign:
12709 case BO_DivAssign:
12710 case BO_RemAssign:
12711 case BO_SubAssign:
12712 case BO_AndAssign:
12713 case BO_OrAssign:
12714 case BO_XorAssign:
12715 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12716 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12717 break;
12718 default:
12719 break;
12720 }
12721
12722 // Find all of the overloaded operators visible from this
12723 // point. We perform both an operator-name lookup from the local
12724 // scope and an argument-dependent lookup based on the types of
12725 // the arguments.
12726 UnresolvedSet<16> Functions;
12727 OverloadedOperatorKind OverOp
12728 = BinaryOperator::getOverloadedOperator(Opc);
12729 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12730 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12731 RHS->getType(), Functions);
12732
12733 // Build the (potentially-overloaded, potentially-dependent)
12734 // binary operation.
12735 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12736 }
12737
12738 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12739 BinaryOperatorKind Opc,
12740 Expr *LHSExpr, Expr *RHSExpr) {
12741 ExprResult LHS, RHS;
12742 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12743 if (!LHS.isUsable() || !RHS.isUsable())
12744 return ExprError();
12745 LHSExpr = LHS.get();
12746 RHSExpr = RHS.get();
12747
12748 // We want to end up calling one of checkPseudoObjectAssignment
12749 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12750 // both expressions are overloadable or either is type-dependent),
12751 // or CreateBuiltinBinOp (in any other case). We also want to get
12752 // any placeholder types out of the way.
12753
12754 // Handle pseudo-objects in the LHS.
12755 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12756 // Assignments with a pseudo-object l-value need special analysis.
12757 if (pty->getKind() == BuiltinType::PseudoObject &&
12758 BinaryOperator::isAssignmentOp(Opc))
12759 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12760
12761 // Don't resolve overloads if the other type is overloadable.
12762 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12763 // We can't actually test that if we still have a placeholder,
12764 // though. Fortunately, none of the exceptions we see in that
12765 // code below are valid when the LHS is an overload set. Note
12766 // that an overload set can be dependently-typed, but it never
12767 // instantiates to having an overloadable type.
12768 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12769 if (resolvedRHS.isInvalid()) return ExprError();
12770 RHSExpr = resolvedRHS.get();
12771
12772 if (RHSExpr->isTypeDependent() ||
12773 RHSExpr->getType()->isOverloadableType())
12774 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12775 }
12776
12777 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12778 // template, diagnose the missing 'template' keyword instead of diagnosing
12779 // an invalid use of a bound member function.
12780 //
12781 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12782 // to C++1z [over.over]/1.4, but we already checked for that case above.
12783 if (Opc == BO_LT && inTemplateInstantiation() &&
12784 (pty->getKind() == BuiltinType::BoundMember ||
12785 pty->getKind() == BuiltinType::Overload)) {
12786 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12787 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12788 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12789 return isa<FunctionTemplateDecl>(ND);
12790 })) {
12791 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12792 : OE->getNameLoc(),
12793 diag::err_template_kw_missing)
12794 << OE->getName().getAsString() << "";
12795 return ExprError();
12796 }
12797 }
12798
12799 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12800 if (LHS.isInvalid()) return ExprError();
12801 LHSExpr = LHS.get();
12802 }
12803
12804 // Handle pseudo-objects in the RHS.
12805 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12806 // An overload in the RHS can potentially be resolved by the type
12807 // being assigned to.
12808 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12809 if (getLangOpts().CPlusPlus &&
12810 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12811 LHSExpr->getType()->isOverloadableType()))
12812 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12813
12814 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12815 }
12816
12817 // Don't resolve overloads if the other type is overloadable.
12818 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12819 LHSExpr->getType()->isOverloadableType())
12820 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12821
12822 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12823 if (!resolvedRHS.isUsable()) return ExprError();
12824 RHSExpr = resolvedRHS.get();
12825 }
12826
12827 if (getLangOpts().CPlusPlus) {
12828 // If either expression is type-dependent, always build an
12829 // overloaded op.
12830 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12831 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12832
12833 // Otherwise, build an overloaded op if either expression has an
12834 // overloadable type.
12835 if (LHSExpr->getType()->isOverloadableType() ||
12836 RHSExpr->getType()->isOverloadableType())
12837 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12838 }
12839
12840 // Build a built-in binary operation.
12841 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12842 }
12843
12844 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12845 if (T.isNull() || T->isDependentType())
12846 return false;
12847
12848 if (!T->isPromotableIntegerType())
12849 return true;
12850
12851 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12852 }
12853
12854 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12855 UnaryOperatorKind Opc,
12856 Expr *InputExpr) {
12857 ExprResult Input = InputExpr;
12858 ExprValueKind VK = VK_RValue;
12859 ExprObjectKind OK = OK_Ordinary;
12860 QualType resultType;
12861 bool CanOverflow = false;
12862
12863 bool ConvertHalfVec = false;
12864 if (getLangOpts().OpenCL) {
12865 QualType Ty = InputExpr->getType();
12866 // The only legal unary operation for atomics is '&'.
12867 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12868 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12869 // only with a builtin functions and therefore should be disallowed here.
12870 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12871 || Ty->isBlockPointerType())) {
12872 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12873 << InputExpr->getType()
12874 << Input.get()->getSourceRange());
12875 }
12876 }
12877 switch (Opc) {
12878 case UO_PreInc:
12879 case UO_PreDec:
12880 case UO_PostInc:
12881 case UO_PostDec:
12882 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12883 OpLoc,
12884 Opc == UO_PreInc ||
12885 Opc == UO_PostInc,
12886 Opc == UO_PreInc ||
12887 Opc == UO_PreDec);
12888 CanOverflow = isOverflowingIntegerType(Context, resultType);
12889 break;
12890 case UO_AddrOf:
12891 resultType = CheckAddressOfOperand(Input, OpLoc);
12892 CheckAddressOfNoDeref(InputExpr);
12893 RecordModifiableNonNullParam(*this, InputExpr);
12894 break;
12895 case UO_Deref: {
12896 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12897 if (Input.isInvalid()) return ExprError();
12898 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12899 break;
12900 }
12901 case UO_Plus:
12902 case UO_Minus:
12903 CanOverflow = Opc == UO_Minus &&
12904 isOverflowingIntegerType(Context, Input.get()->getType());
12905 Input = UsualUnaryConversions(Input.get());
12906 if (Input.isInvalid()) return ExprError();
12907 // Unary plus and minus require promoting an operand of half vector to a
12908 // float vector and truncating the result back to a half vector. For now, we
12909 // do this only when HalfArgsAndReturns is set (that is, when the target is
12910 // arm or arm64).
12911 ConvertHalfVec =
12912 needsConversionOfHalfVec(true, Context, Input.get()->getType());
12913
12914 // If the operand is a half vector, promote it to a float vector.
12915 if (ConvertHalfVec)
12916 Input = convertVector(Input.get(), Context.FloatTy, *this);
12917 resultType = Input.get()->getType();
12918 if (resultType->isDependentType())
12919 break;
12920 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12921 break;
12922 else if (resultType->isVectorType() &&
12923 // The z vector extensions don't allow + or - with bool vectors.
12924 (!Context.getLangOpts().ZVector ||
12925 resultType->getAs<VectorType>()->getVectorKind() !=
12926 VectorType::AltiVecBool))
12927 break;
12928 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12929 Opc == UO_Plus &&
12930 resultType->isPointerType())
12931 break;
12932
12933 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12934 << resultType << Input.get()->getSourceRange());
12935
12936 case UO_Not: // bitwise complement
12937 Input = UsualUnaryConversions(Input.get());
12938 if (Input.isInvalid())
12939 return ExprError();
12940 resultType = Input.get()->getType();
12941
12942 if (resultType->isDependentType())
12943 break;
12944 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12945 if (resultType->isComplexType() || resultType->isComplexIntegerType())
12946 // C99 does not support '~' for complex conjugation.
12947 Diag(OpLoc, diag::ext_integer_complement_complex)
12948 << resultType << Input.get()->getSourceRange();
12949 else if (resultType->hasIntegerRepresentation())
12950 break;
12951 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12952 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12953 // on vector float types.
12954 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12955 if (!T->isIntegerType())
12956 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12957 << resultType << Input.get()->getSourceRange());
12958 } else {
12959 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12960 << resultType << Input.get()->getSourceRange());
12961 }
12962 break;
12963
12964 case UO_LNot: // logical negation
12965 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12966 Input = DefaultFunctionArrayLvalueConversion(Input.get());
12967 if (Input.isInvalid()) return ExprError();
12968 resultType = Input.get()->getType();
12969
12970 // Though we still have to promote half FP to float...
12971 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12972 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12973 resultType = Context.FloatTy;
12974 }
12975
12976 if (resultType->isDependentType())
12977 break;
12978 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12979 // C99 6.5.3.3p1: ok, fallthrough;
12980 if (Context.getLangOpts().CPlusPlus) {
12981 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12982 // operand contextually converted to bool.
12983 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12984 ScalarTypeToBooleanCastKind(resultType));
12985 } else if (Context.getLangOpts().OpenCL &&
12986 Context.getLangOpts().OpenCLVersion < 120) {
12987 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12988 // operate on scalar float types.
12989 if (!resultType->isIntegerType() && !resultType->isPointerType())
12990 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12991 << resultType << Input.get()->getSourceRange());
12992 }
12993 } else if (resultType->isExtVectorType()) {
12994 if (Context.getLangOpts().OpenCL &&
12995 Context.getLangOpts().OpenCLVersion < 120) {
12996 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12997 // operate on vector float types.
12998 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12999 if (!T->isIntegerType())
13000 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13001 << resultType << Input.get()->getSourceRange());
13002 }
13003 // Vector logical not returns the signed variant of the operand type.
13004 resultType = GetSignedVectorType(resultType);
13005 break;
13006 } else {
13007 // FIXME: GCC's vector extension permits the usage of '!' with a vector
13008 // type in C++. We should allow that here too.
13009 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13010 << resultType << Input.get()->getSourceRange());
13011 }
13012
13013 // LNot always has type int. C99 6.5.3.3p5.
13014 // In C++, it's bool. C++ 5.3.1p8
13015 resultType = Context.getLogicalOperationType();
13016 break;
13017 case UO_Real:
13018 case UO_Imag:
13019 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13020 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13021 // complex l-values to ordinary l-values and all other values to r-values.
13022 if (Input.isInvalid()) return ExprError();
13023 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13024 if (Input.get()->getValueKind() != VK_RValue &&
13025 Input.get()->getObjectKind() == OK_Ordinary)
13026 VK = Input.get()->getValueKind();
13027 } else if (!getLangOpts().CPlusPlus) {
13028 // In C, a volatile scalar is read by __imag. In C++, it is not.
13029 Input = DefaultLvalueConversion(Input.get());
13030 }
13031 break;
13032 case UO_Extension:
13033 resultType = Input.get()->getType();
13034 VK = Input.get()->getValueKind();
13035 OK = Input.get()->getObjectKind();
13036 break;
13037 case UO_Coawait:
13038 // It's unnecessary to represent the pass-through operator co_await in the
13039 // AST; just return the input expression instead.
13040 assert(!Input.get()->getType()->isDependentType() &&
13041 "the co_await expression must be non-dependant before "
13042 "building operator co_await");
13043 return Input;
13044 }
13045 if (resultType.isNull() || Input.isInvalid())
13046 return ExprError();
13047
13048 // Check for array bounds violations in the operand of the UnaryOperator,
13049 // except for the '*' and '&' operators that have to be handled specially
13050 // by CheckArrayAccess (as there are special cases like &array[arraysize]
13051 // that are explicitly defined as valid by the standard).
13052 if (Opc != UO_AddrOf && Opc != UO_Deref)
13053 CheckArrayAccess(Input.get());
13054
13055 auto *UO = new (Context)
13056 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13057
13058 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13059 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13060 ExprEvalContexts.back().PossibleDerefs.insert(UO);
13061
13062 // Convert the result back to a half vector.
13063 if (ConvertHalfVec)
13064 return convertVector(UO, Context.HalfTy, *this);
13065 return UO;
13066 }
13067
13068 /// Determine whether the given expression is a qualified member
13069 /// access expression, of a form that could be turned into a pointer to member
13070 /// with the address-of operator.
13071 bool Sema::isQualifiedMemberAccess(Expr *E) {
13072 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13073 if (!DRE->getQualifier())
13074 return false;
13075
13076 ValueDecl *VD = DRE->getDecl();
13077 if (!VD->isCXXClassMember())
13078 return false;
13079
13080 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13081 return true;
13082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13083 return Method->isInstance();
13084
13085 return false;
13086 }
13087
13088 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13089 if (!ULE->getQualifier())
13090 return false;
13091
13092 for (NamedDecl *D : ULE->decls()) {
13093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13094 if (Method->isInstance())
13095 return true;
13096 } else {
13097 // Overload set does not contain methods.
13098 break;
13099 }
13100 }
13101
13102 return false;
13103 }
13104
13105 return false;
13106 }
13107
13108 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13109 UnaryOperatorKind Opc, Expr *Input) {
13110 // First things first: handle placeholders so that the
13111 // overloaded-operator check considers the right type.
13112 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13113 // Increment and decrement of pseudo-object references.
13114 if (pty->getKind() == BuiltinType::PseudoObject &&
13115 UnaryOperator::isIncrementDecrementOp(Opc))
13116 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13117
13118 // extension is always a builtin operator.
13119 if (Opc == UO_Extension)
13120 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13121
13122 // & gets special logic for several kinds of placeholder.
13123 // The builtin code knows what to do.
13124 if (Opc == UO_AddrOf &&
13125 (pty->getKind() == BuiltinType::Overload ||
13126 pty->getKind() == BuiltinType::UnknownAny ||
13127 pty->getKind() == BuiltinType::BoundMember))
13128 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13129
13130 // Anything else needs to be handled now.
13131 ExprResult Result = CheckPlaceholderExpr(Input);
13132 if (Result.isInvalid()) return ExprError();
13133 Input = Result.get();
13134 }
13135
13136 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13137 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13138 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13139 // Find all of the overloaded operators visible from this
13140 // point. We perform both an operator-name lookup from the local
13141 // scope and an argument-dependent lookup based on the types of
13142 // the arguments.
13143 UnresolvedSet<16> Functions;
13144 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13145 if (S && OverOp != OO_None)
13146 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13147 Functions);
13148
13149 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13150 }
13151
13152 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13153 }
13154
13155 // Unary Operators. 'Tok' is the token for the operator.
13156 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13157 tok::TokenKind Op, Expr *Input) {
13158 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13159 }
13160
13161 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13162 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13163 LabelDecl *TheDecl) {
13164 TheDecl->markUsed(Context);
13165 // Create the AST node. The address of a label always has type 'void*'.
13166 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13167 Context.getPointerType(Context.VoidTy));
13168 }
13169
13170 /// Given the last statement in a statement-expression, check whether
13171 /// the result is a producing expression (like a call to an
13172 /// ns_returns_retained function) and, if so, rebuild it to hoist the
13173 /// release out of the full-expression. Otherwise, return null.
13174 /// Cannot fail.
13175 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
13176 // Should always be wrapped with one of these.
13177 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
13178 if (!cleanups) return nullptr;
13179
13180 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
13181 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
13182 return nullptr;
13183
13184 // Splice out the cast. This shouldn't modify any interesting
13185 // features of the statement.
13186 Expr *producer = cast->getSubExpr();
13187 assert(producer->getType() == cast->getType());
13188 assert(producer->getValueKind() == cast->getValueKind());
13189 cleanups->setSubExpr(producer);
13190 return cleanups;
13191 }
13192
13193 void Sema::ActOnStartStmtExpr() {
13194 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13195 }
13196
13197 void Sema::ActOnStmtExprError() {
13198 // Note that function is also called by TreeTransform when leaving a
13199 // StmtExpr scope without rebuilding anything.
13200
13201 DiscardCleanupsInEvaluationContext();
13202 PopExpressionEvaluationContext();
13203 }
13204
13205 ExprResult
13206 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13207 SourceLocation RPLoc) { // "({..})"
13208 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13209 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13210
13211 if (hasAnyUnrecoverableErrorsInThisFunction())
13212 DiscardCleanupsInEvaluationContext();
13213 assert(!Cleanup.exprNeedsCleanups() &&
13214 "cleanups within StmtExpr not correctly bound!");
13215 PopExpressionEvaluationContext();
13216
13217 // FIXME: there are a variety of strange constraints to enforce here, for
13218 // example, it is not possible to goto into a stmt expression apparently.
13219 // More semantic analysis is needed.
13220
13221 // If there are sub-stmts in the compound stmt, take the type of the last one
13222 // as the type of the stmtexpr.
13223 QualType Ty = Context.VoidTy;
13224 bool StmtExprMayBindToTemp = false;
13225 if (!Compound->body_empty()) {
13226 Stmt *LastStmt = Compound->body_back();
13227 LabelStmt *LastLabelStmt = nullptr;
13228 // If LastStmt is a label, skip down through into the body.
13229 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13230 LastLabelStmt = Label;
13231 LastStmt = Label->getSubStmt();
13232 }
13233
13234 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13235 // Do function/array conversion on the last expression, but not
13236 // lvalue-to-rvalue. However, initialize an unqualified type.
13237 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13238 if (LastExpr.isInvalid())
13239 return ExprError();
13240 Ty = LastExpr.get()->getType().getUnqualifiedType();
13241
13242 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13243 // In ARC, if the final expression ends in a consume, splice
13244 // the consume out and bind it later. In the alternate case
13245 // (when dealing with a retainable type), the result
13246 // initialization will create a produce. In both cases the
13247 // result will be +1, and we'll need to balance that out with
13248 // a bind.
13249 if (Expr *rebuiltLastStmt
13250 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13251 LastExpr = rebuiltLastStmt;
13252 } else {
13253 LastExpr = PerformCopyInitialization(
13254 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13255 SourceLocation(), LastExpr);
13256 }
13257
13258 if (LastExpr.isInvalid())
13259 return ExprError();
13260 if (LastExpr.get() != nullptr) {
13261 if (!LastLabelStmt)
13262 Compound->setLastStmt(LastExpr.get());
13263 else
13264 LastLabelStmt->setSubStmt(LastExpr.get());
13265 StmtExprMayBindToTemp = true;
13266 }
13267 }
13268 }
13269 }
13270
13271 // FIXME: Check that expression type is complete/non-abstract; statement
13272 // expressions are not lvalues.
13273 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13274 if (StmtExprMayBindToTemp)
13275 return MaybeBindToTemporary(ResStmtExpr);
13276 return ResStmtExpr;
13277 }
13278
13279 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13280 TypeSourceInfo *TInfo,
13281 ArrayRef<OffsetOfComponent> Components,
13282 SourceLocation RParenLoc) {
13283 QualType ArgTy = TInfo->getType();
13284 bool Dependent = ArgTy->isDependentType();
13285 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13286
13287 // We must have at least one component that refers to the type, and the first
13288 // one is known to be a field designator. Verify that the ArgTy represents
13289 // a struct/union/class.
13290 if (!Dependent && !ArgTy->isRecordType())
13291 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13292 << ArgTy << TypeRange);
13293
13294 // Type must be complete per C99 7.17p3 because a declaring a variable
13295 // with an incomplete type would be ill-formed.
13296 if (!Dependent
13297 && RequireCompleteType(BuiltinLoc, ArgTy,
13298 diag::err_offsetof_incomplete_type, TypeRange))
13299 return ExprError();
13300
13301 bool DidWarnAboutNonPOD = false;
13302 QualType CurrentType = ArgTy;
13303 SmallVector<OffsetOfNode, 4> Comps;
13304 SmallVector<Expr*, 4> Exprs;
13305 for (const OffsetOfComponent &OC : Components) {
13306 if (OC.isBrackets) {
13307 // Offset of an array sub-field. TODO: Should we allow vector elements?
13308 if (!CurrentType->isDependentType()) {
13309 const ArrayType *AT = Context.getAsArrayType(CurrentType);
13310 if(!AT)
13311 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13312 << CurrentType);
13313 CurrentType = AT->getElementType();
13314 } else
13315 CurrentType = Context.DependentTy;
13316
13317 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13318 if (IdxRval.isInvalid())
13319 return ExprError();
13320 Expr *Idx = IdxRval.get();
13321
13322 // The expression must be an integral expression.
13323 // FIXME: An integral constant expression?
13324 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13325 !Idx->getType()->isIntegerType())
13326 return ExprError(
13327 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13328 << Idx->getSourceRange());
13329
13330 // Record this array index.
13331 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13332 Exprs.push_back(Idx);
13333 continue;
13334 }
13335
13336 // Offset of a field.
13337 if (CurrentType->isDependentType()) {
13338 // We have the offset of a field, but we can't look into the dependent
13339 // type. Just record the identifier of the field.
13340 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13341 CurrentType = Context.DependentTy;
13342 continue;
13343 }
13344
13345 // We need to have a complete type to look into.
13346 if (RequireCompleteType(OC.LocStart, CurrentType,
13347 diag::err_offsetof_incomplete_type))
13348 return ExprError();
13349
13350 // Look for the designated field.
13351 const RecordType *RC = CurrentType->getAs<RecordType>();
13352 if (!RC)
13353 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13354 << CurrentType);
13355 RecordDecl *RD = RC->getDecl();
13356
13357 // C++ [lib.support.types]p5:
13358 // The macro offsetof accepts a restricted set of type arguments in this
13359 // International Standard. type shall be a POD structure or a POD union
13360 // (clause 9).
13361 // C++11 [support.types]p4:
13362 // If type is not a standard-layout class (Clause 9), the results are
13363 // undefined.
13364 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13365 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13366 unsigned DiagID =
13367 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13368 : diag::ext_offsetof_non_pod_type;
13369
13370 if (!IsSafe && !DidWarnAboutNonPOD &&
13371 DiagRuntimeBehavior(BuiltinLoc, nullptr,
13372 PDiag(DiagID)
13373 << SourceRange(Components[0].LocStart, OC.LocEnd)
13374 << CurrentType))
13375 DidWarnAboutNonPOD = true;
13376 }
13377
13378 // Look for the field.
13379 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13380 LookupQualifiedName(R, RD);
13381 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13382 IndirectFieldDecl *IndirectMemberDecl = nullptr;
13383 if (!MemberDecl) {
13384 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13385 MemberDecl = IndirectMemberDecl->getAnonField();
13386 }
13387
13388 if (!MemberDecl)
13389 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13390 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13391 OC.LocEnd));
13392
13393 // C99 7.17p3:
13394 // (If the specified member is a bit-field, the behavior is undefined.)
13395 //
13396 // We diagnose this as an error.
13397 if (MemberDecl->isBitField()) {
13398 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13399 << MemberDecl->getDeclName()
13400 << SourceRange(BuiltinLoc, RParenLoc);
13401 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13402 return ExprError();
13403 }
13404
13405 RecordDecl *Parent = MemberDecl->getParent();
13406 if (IndirectMemberDecl)
13407 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13408
13409 // If the member was found in a base class, introduce OffsetOfNodes for
13410 // the base class indirections.
13411 CXXBasePaths Paths;
13412 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13413 Paths)) {
13414 if (Paths.getDetectedVirtual()) {
13415 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13416 << MemberDecl->getDeclName()
13417 << SourceRange(BuiltinLoc, RParenLoc);
13418 return ExprError();
13419 }
13420
13421 CXXBasePath &Path = Paths.front();
13422 for (const CXXBasePathElement &B : Path)
13423 Comps.push_back(OffsetOfNode(B.Base));
13424 }
13425
13426 if (IndirectMemberDecl) {
13427 for (auto *FI : IndirectMemberDecl->chain()) {
13428 assert(isa<FieldDecl>(FI));
13429 Comps.push_back(OffsetOfNode(OC.LocStart,
13430 cast<FieldDecl>(FI), OC.LocEnd));
13431 }
13432 } else
13433 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13434
13435 CurrentType = MemberDecl->getType().getNonReferenceType();
13436 }
13437
13438 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13439 Comps, Exprs, RParenLoc);
13440 }
13441
13442 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13443 SourceLocation BuiltinLoc,
13444 SourceLocation TypeLoc,
13445 ParsedType ParsedArgTy,
13446 ArrayRef<OffsetOfComponent> Components,
13447 SourceLocation RParenLoc) {
13448
13449 TypeSourceInfo *ArgTInfo;
13450 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13451 if (ArgTy.isNull())
13452 return ExprError();
13453
13454 if (!ArgTInfo)
13455 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13456
13457 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13458 }
13459
13460
13461 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13462 Expr *CondExpr,
13463 Expr *LHSExpr, Expr *RHSExpr,
13464 SourceLocation RPLoc) {
13465 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13466
13467 ExprValueKind VK = VK_RValue;
13468 ExprObjectKind OK = OK_Ordinary;
13469 QualType resType;
13470 bool ValueDependent = false;
13471 bool CondIsTrue = false;
13472 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13473 resType = Context.DependentTy;
13474 ValueDependent = true;
13475 } else {
13476 // The conditional expression is required to be a constant expression.
13477 llvm::APSInt condEval(32);
13478 ExprResult CondICE
13479 = VerifyIntegerConstantExpression(CondExpr, &condEval,
13480 diag::err_typecheck_choose_expr_requires_constant, false);
13481 if (CondICE.isInvalid())
13482 return ExprError();
13483 CondExpr = CondICE.get();
13484 CondIsTrue = condEval.getZExtValue();
13485
13486 // If the condition is > zero, then the AST type is the same as the LHSExpr.
13487 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13488
13489 resType = ActiveExpr->getType();
13490 ValueDependent = ActiveExpr->isValueDependent();
13491 VK = ActiveExpr->getValueKind();
13492 OK = ActiveExpr->getObjectKind();
13493 }
13494
13495 return new (Context)
13496 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13497 CondIsTrue, resType->isDependentType(), ValueDependent);
13498 }
13499
13500 //===----------------------------------------------------------------------===//
13501 // Clang Extensions.
13502 //===----------------------------------------------------------------------===//
13503
13504 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13505 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13506 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13507
13508 if (LangOpts.CPlusPlus) {
13509 Decl *ManglingContextDecl;
13510 if (MangleNumberingContext *MCtx =
13511 getCurrentMangleNumberContext(Block->getDeclContext(),
13512 ManglingContextDecl)) {
13513 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13514 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13515 }
13516 }
13517
13518 PushBlockScope(CurScope, Block);
13519 CurContext->addDecl(Block);
13520 if (CurScope)
13521 PushDeclContext(CurScope, Block);
13522 else
13523 CurContext = Block;
13524
13525 getCurBlock()->HasImplicitReturnType = true;
13526
13527 // Enter a new evaluation context to insulate the block from any
13528 // cleanups from the enclosing full-expression.
13529 PushExpressionEvaluationContext(
13530 ExpressionEvaluationContext::PotentiallyEvaluated);
13531 }
13532
13533 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13534 Scope *CurScope) {
13535 assert(ParamInfo.getIdentifier() == nullptr &&
13536 "block-id should have no identifier!");
13537 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13538 BlockScopeInfo *CurBlock = getCurBlock();
13539
13540 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13541 QualType T = Sig->getType();
13542
13543 // FIXME: We should allow unexpanded parameter packs here, but that would,
13544 // in turn, make the block expression contain unexpanded parameter packs.
13545 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13546 // Drop the parameters.
13547 FunctionProtoType::ExtProtoInfo EPI;
13548 EPI.HasTrailingReturn = false;
13549 EPI.TypeQuals.addConst();
13550 T = Context.getFunctionType(Context.DependentTy, None, EPI);
13551 Sig = Context.getTrivialTypeSourceInfo(T);
13552 }
13553
13554 // GetTypeForDeclarator always produces a function type for a block
13555 // literal signature. Furthermore, it is always a FunctionProtoType
13556 // unless the function was written with a typedef.
13557 assert(T->isFunctionType() &&
13558 "GetTypeForDeclarator made a non-function block signature");
13559
13560 // Look for an explicit signature in that function type.
13561 FunctionProtoTypeLoc ExplicitSignature;
13562
13563 if ((ExplicitSignature =
13564 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13565
13566 // Check whether that explicit signature was synthesized by
13567 // GetTypeForDeclarator. If so, don't save that as part of the
13568 // written signature.
13569 if (ExplicitSignature.getLocalRangeBegin() ==
13570 ExplicitSignature.getLocalRangeEnd()) {
13571 // This would be much cheaper if we stored TypeLocs instead of
13572 // TypeSourceInfos.
13573 TypeLoc Result = ExplicitSignature.getReturnLoc();
13574 unsigned Size = Result.getFullDataSize();
13575 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13576 Sig->getTypeLoc().initializeFullCopy(Result, Size);
13577
13578 ExplicitSignature = FunctionProtoTypeLoc();
13579 }
13580 }
13581
13582 CurBlock->TheDecl->setSignatureAsWritten(Sig);
13583 CurBlock->FunctionType = T;
13584
13585 const FunctionType *Fn = T->getAs<FunctionType>();
13586 QualType RetTy = Fn->getReturnType();
13587 bool isVariadic =
13588 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13589
13590 CurBlock->TheDecl->setIsVariadic(isVariadic);
13591
13592 // Context.DependentTy is used as a placeholder for a missing block
13593 // return type. TODO: what should we do with declarators like:
13594 // ^ * { ... }
13595 // If the answer is "apply template argument deduction"....
13596 if (RetTy != Context.DependentTy) {
13597 CurBlock->ReturnType = RetTy;
13598 CurBlock->TheDecl->setBlockMissingReturnType(false);
13599 CurBlock->HasImplicitReturnType = false;
13600 }
13601
13602 // Push block parameters from the declarator if we had them.
13603 SmallVector<ParmVarDecl*, 8> Params;
13604 if (ExplicitSignature) {
13605 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13606 ParmVarDecl *Param = ExplicitSignature.getParam(I);
13607 if (Param->getIdentifier() == nullptr &&
13608 !Param->isImplicit() &&
13609 !Param->isInvalidDecl() &&
13610 !getLangOpts().CPlusPlus)
13611 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13612 Params.push_back(Param);
13613 }
13614
13615 // Fake up parameter variables if we have a typedef, like
13616 // ^ fntype { ... }
13617 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13618 for (const auto &I : Fn->param_types()) {
13619 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13620 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13621 Params.push_back(Param);
13622 }
13623 }
13624
13625 // Set the parameters on the block decl.
13626 if (!Params.empty()) {
13627 CurBlock->TheDecl->setParams(Params);
13628 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13629 /*CheckParameterNames=*/false);
13630 }
13631
13632 // Finally we can process decl attributes.
13633 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13634
13635 // Put the parameter variables in scope.
13636 for (auto AI : CurBlock->TheDecl->parameters()) {
13637 AI->setOwningFunction(CurBlock->TheDecl);
13638
13639 // If this has an identifier, add it to the scope stack.
13640 if (AI->getIdentifier()) {
13641 CheckShadow(CurBlock->TheScope, AI);
13642
13643 PushOnScopeChains(AI, CurBlock->TheScope);
13644 }
13645 }
13646 }
13647
13648 /// ActOnBlockError - If there is an error parsing a block, this callback
13649 /// is invoked to pop the information about the block from the action impl.
13650 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13651 // Leave the expression-evaluation context.
13652 DiscardCleanupsInEvaluationContext();
13653 PopExpressionEvaluationContext();
13654
13655 // Pop off CurBlock, handle nested blocks.
13656 PopDeclContext();
13657 PopFunctionScopeInfo();
13658 }
13659
13660 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13661 /// literal was successfully completed. ^(int x){...}
13662 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13663 Stmt *Body, Scope *CurScope) {
13664 // If blocks are disabled, emit an error.
13665 if (!LangOpts.Blocks)
13666 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13667
13668 // Leave the expression-evaluation context.
13669 if (hasAnyUnrecoverableErrorsInThisFunction())
13670 DiscardCleanupsInEvaluationContext();
13671 assert(!Cleanup.exprNeedsCleanups() &&
13672 "cleanups within block not correctly bound!");
13673 PopExpressionEvaluationContext();
13674
13675 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13676 BlockDecl *BD = BSI->TheDecl;
13677
13678 if (BSI->HasImplicitReturnType)
13679 deduceClosureReturnType(*BSI);
13680
13681 PopDeclContext();
13682
13683 QualType RetTy = Context.VoidTy;
13684 if (!BSI->ReturnType.isNull())
13685 RetTy = BSI->ReturnType;
13686
13687 bool NoReturn = BD->hasAttr<NoReturnAttr>();
13688 QualType BlockTy;
13689
13690 // Set the captured variables on the block.
13691 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13692 SmallVector<BlockDecl::Capture, 4> Captures;
13693 for (Capture &Cap : BSI->Captures) {
13694 if (Cap.isThisCapture())
13695 continue;
13696 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13697 Cap.isNested(), Cap.getInitExpr());
13698 Captures.push_back(NewCap);
13699 }
13700 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13701
13702 // If the user wrote a function type in some form, try to use that.
13703 if (!BSI->FunctionType.isNull()) {
13704 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13705
13706 FunctionType::ExtInfo Ext = FTy->getExtInfo();
13707 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13708
13709 // Turn protoless block types into nullary block types.
13710 if (isa<FunctionNoProtoType>(FTy)) {
13711 FunctionProtoType::ExtProtoInfo EPI;
13712 EPI.ExtInfo = Ext;
13713 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13714
13715 // Otherwise, if we don't need to change anything about the function type,
13716 // preserve its sugar structure.
13717 } else if (FTy->getReturnType() == RetTy &&
13718 (!NoReturn || FTy->getNoReturnAttr())) {
13719 BlockTy = BSI->FunctionType;
13720
13721 // Otherwise, make the minimal modifications to the function type.
13722 } else {
13723 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13724 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13725 EPI.TypeQuals = Qualifiers();
13726 EPI.ExtInfo = Ext;
13727 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13728 }
13729
13730 // If we don't have a function type, just build one from nothing.
13731 } else {
13732 FunctionProtoType::ExtProtoInfo EPI;
13733 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13734 BlockTy = Context.getFunctionType(RetTy, None, EPI);
13735 }
13736
13737 DiagnoseUnusedParameters(BD->parameters());
13738 BlockTy = Context.getBlockPointerType(BlockTy);
13739
13740 // If needed, diagnose invalid gotos and switches in the block.
13741 if (getCurFunction()->NeedsScopeChecking() &&
13742 !PP.isCodeCompletionEnabled())
13743 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13744
13745 BD->setBody(cast<CompoundStmt>(Body));
13746
13747 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13748 DiagnoseUnguardedAvailabilityViolations(BD);
13749
13750 // Try to apply the named return value optimization. We have to check again
13751 // if we can do this, though, because blocks keep return statements around
13752 // to deduce an implicit return type.
13753 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13754 !BD->isDependentContext())
13755 computeNRVO(Body, BSI);
13756
13757 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13758 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13759 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13760
13761 // If the block isn't obviously global, i.e. it captures anything at
13762 // all, then we need to do a few things in the surrounding context:
13763 if (Result->getBlockDecl()->hasCaptures()) {
13764 // First, this expression has a new cleanup object.
13765 ExprCleanupObjects.push_back(Result->getBlockDecl());
13766 Cleanup.setExprNeedsCleanups(true);
13767
13768 // It also gets a branch-protected scope if any of the captured
13769 // variables needs destruction.
13770 for (const auto &CI : Result->getBlockDecl()->captures()) {
13771 const VarDecl *var = CI.getVariable();
13772 if (var->getType().isDestructedType() != QualType::DK_none) {
13773 setFunctionHasBranchProtectedScope();
13774 break;
13775 }
13776 }
13777 }
13778
13779 if (getCurFunction())
13780 getCurFunction()->addBlock(BD);
13781
13782 return Result;
13783 }
13784
13785 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13786 SourceLocation RPLoc) {
13787 TypeSourceInfo *TInfo;
13788 GetTypeFromParser(Ty, &TInfo);
13789 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13790 }
13791
13792 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13793 Expr *E, TypeSourceInfo *TInfo,
13794 SourceLocation RPLoc) {
13795 Expr *OrigExpr = E;
13796 bool IsMS = false;
13797
13798 // CUDA device code does not support varargs.
13799 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13800 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13801 CUDAFunctionTarget T = IdentifyCUDATarget(F);
13802 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13803 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13804 }
13805 }
13806
13807 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13808 // as Microsoft ABI on an actual Microsoft platform, where
13809 // __builtin_ms_va_list and __builtin_va_list are the same.)
13810 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13811 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13812 QualType MSVaListType = Context.getBuiltinMSVaListType();
13813 if (Context.hasSameType(MSVaListType, E->getType())) {
13814 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13815 return ExprError();
13816 IsMS = true;
13817 }
13818 }
13819
13820 // Get the va_list type
13821 QualType VaListType = Context.getBuiltinVaListType();
13822 if (!IsMS) {
13823 if (VaListType->isArrayType()) {
13824 // Deal with implicit array decay; for example, on x86-64,
13825 // va_list is an array, but it's supposed to decay to
13826 // a pointer for va_arg.
13827 VaListType = Context.getArrayDecayedType(VaListType);
13828 // Make sure the input expression also decays appropriately.
13829 ExprResult Result = UsualUnaryConversions(E);
13830 if (Result.isInvalid())
13831 return ExprError();
13832 E = Result.get();
13833 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13834 // If va_list is a record type and we are compiling in C++ mode,
13835 // check the argument using reference binding.
13836 InitializedEntity Entity = InitializedEntity::InitializeParameter(
13837 Context, Context.getLValueReferenceType(VaListType), false);
13838 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13839 if (Init.isInvalid())
13840 return ExprError();
13841 E = Init.getAs<Expr>();
13842 } else {
13843 // Otherwise, the va_list argument must be an l-value because
13844 // it is modified by va_arg.
13845 if (!E->isTypeDependent() &&
13846 CheckForModifiableLvalue(E, BuiltinLoc, *this))
13847 return ExprError();
13848 }
13849 }
13850
13851 if (!IsMS && !E->isTypeDependent() &&
13852 !Context.hasSameType(VaListType, E->getType()))
13853 return ExprError(
13854 Diag(E->getBeginLoc(),
13855 diag::err_first_argument_to_va_arg_not_of_type_va_list)
13856 << OrigExpr->getType() << E->getSourceRange());
13857
13858 if (!TInfo->getType()->isDependentType()) {
13859 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13860 diag::err_second_parameter_to_va_arg_incomplete,
13861 TInfo->getTypeLoc()))
13862 return ExprError();
13863
13864 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13865 TInfo->getType(),
13866 diag::err_second_parameter_to_va_arg_abstract,
13867 TInfo->getTypeLoc()))
13868 return ExprError();
13869
13870 if (!TInfo->getType().isPODType(Context)) {
13871 Diag(TInfo->getTypeLoc().getBeginLoc(),
13872 TInfo->getType()->isObjCLifetimeType()
13873 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13874 : diag::warn_second_parameter_to_va_arg_not_pod)
13875 << TInfo->getType()
13876 << TInfo->getTypeLoc().getSourceRange();
13877 }
13878
13879 // Check for va_arg where arguments of the given type will be promoted
13880 // (i.e. this va_arg is guaranteed to have undefined behavior).
13881 QualType PromoteType;
13882 if (TInfo->getType()->isPromotableIntegerType()) {
13883 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13884 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13885 PromoteType = QualType();
13886 }
13887 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13888 PromoteType = Context.DoubleTy;
13889 if (!PromoteType.isNull())
13890 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13891 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13892 << TInfo->getType()
13893 << PromoteType
13894 << TInfo->getTypeLoc().getSourceRange());
13895 }
13896
13897 QualType T = TInfo->getType().getNonLValueExprType(Context);
13898 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13899 }
13900
13901 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13902 // The type of __null will be int or long, depending on the size of
13903 // pointers on the target.
13904 QualType Ty;
13905 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13906 if (pw == Context.getTargetInfo().getIntWidth())
13907 Ty = Context.IntTy;
13908 else if (pw == Context.getTargetInfo().getLongWidth())
13909 Ty = Context.LongTy;
13910 else if (pw == Context.getTargetInfo().getLongLongWidth())
13911 Ty = Context.LongLongTy;
13912 else {
13913 llvm_unreachable("I don't know size of pointer!");
13914 }
13915
13916 return new (Context) GNUNullExpr(Ty, TokenLoc);
13917 }
13918
13919 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13920 bool Diagnose) {
13921 if (!getLangOpts().ObjC)
13922 return false;
13923
13924 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13925 if (!PT)
13926 return false;
13927
13928 if (!PT->isObjCIdType()) {
13929 // Check if the destination is the 'NSString' interface.
13930 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13931 if (!ID || !ID->getIdentifier()->isStr("NSString"))
13932 return false;
13933 }
13934
13935 // Ignore any parens, implicit casts (should only be
13936 // array-to-pointer decays), and not-so-opaque values. The last is
13937 // important for making this trigger for property assignments.
13938 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13939 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13940 if (OV->getSourceExpr())
13941 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13942
13943 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13944 if (!SL || !SL->isAscii())
13945 return false;
13946 if (Diagnose) {
13947 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13948 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13949 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13950 }
13951 return true;
13952 }
13953
13954 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13955 const Expr *SrcExpr) {
13956 if (!DstType->isFunctionPointerType() ||
13957 !SrcExpr->getType()->isFunctionType())
13958 return false;
13959
13960 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13961 if (!DRE)
13962 return false;
13963
13964 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13965 if (!FD)
13966 return false;
13967
13968 return !S.checkAddressOfFunctionIsAvailable(FD,
13969 /*Complain=*/true,
13970 SrcExpr->getBeginLoc());
13971 }
13972
13973 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13974 SourceLocation Loc,
13975 QualType DstType, QualType SrcType,
13976 Expr *SrcExpr, AssignmentAction Action,
13977 bool *Complained) {
13978 if (Complained)
13979 *Complained = false;
13980
13981 // Decode the result (notice that AST's are still created for extensions).
13982 bool CheckInferredResultType = false;
13983 bool isInvalid = false;
13984 unsigned DiagKind = 0;
13985 FixItHint Hint;
13986 ConversionFixItGenerator ConvHints;
13987 bool MayHaveConvFixit = false;
13988 bool MayHaveFunctionDiff = false;
13989 const ObjCInterfaceDecl *IFace = nullptr;
13990 const ObjCProtocolDecl *PDecl = nullptr;
13991
13992 switch (ConvTy) {
13993 case Compatible:
13994 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13995 return false;
13996
13997 case PointerToInt:
13998 DiagKind = diag::ext_typecheck_convert_pointer_int;
13999 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14000 MayHaveConvFixit = true;
14001 break;
14002 case IntToPointer:
14003 DiagKind = diag::ext_typecheck_convert_int_pointer;
14004 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14005 MayHaveConvFixit = true;
14006 break;
14007 case IncompatiblePointer:
14008 if (Action == AA_Passing_CFAudited)
14009 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14010 else if (SrcType->isFunctionPointerType() &&
14011 DstType->isFunctionPointerType())
14012 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14013 else
14014 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14015
14016 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14017 SrcType->isObjCObjectPointerType();
14018 if (Hint.isNull() && !CheckInferredResultType) {
14019 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14020 }
14021 else if (CheckInferredResultType) {
14022 SrcType = SrcType.getUnqualifiedType();
14023 DstType = DstType.getUnqualifiedType();
14024 }
14025 MayHaveConvFixit = true;
14026 break;
14027 case IncompatiblePointerSign:
14028 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14029 break;
14030 case FunctionVoidPointer:
14031 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14032 break;
14033 case IncompatiblePointerDiscardsQualifiers: {
14034 // Perform array-to-pointer decay if necessary.
14035 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14036
14037 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14038 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14039 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14040 DiagKind = diag::err_typecheck_incompatible_address_space;
14041 break;
14042
14043 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14044 DiagKind = diag::err_typecheck_incompatible_ownership;
14045 break;
14046 }
14047
14048 llvm_unreachable("unknown error case for discarding qualifiers!");
14049 // fallthrough
14050 }
14051 case CompatiblePointerDiscardsQualifiers:
14052 // If the qualifiers lost were because we were applying the
14053 // (deprecated) C++ conversion from a string literal to a char*
14054 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14055 // Ideally, this check would be performed in
14056 // checkPointerTypesForAssignment. However, that would require a
14057 // bit of refactoring (so that the second argument is an
14058 // expression, rather than a type), which should be done as part
14059 // of a larger effort to fix checkPointerTypesForAssignment for
14060 // C++ semantics.
14061 if (getLangOpts().CPlusPlus &&
14062 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14063 return false;
14064 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14065 break;
14066 case IncompatibleNestedPointerQualifiers:
14067 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14068 break;
14069 case IntToBlockPointer:
14070 DiagKind = diag::err_int_to_block_pointer;
14071 break;
14072 case IncompatibleBlockPointer:
14073 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14074 break;
14075 case IncompatibleObjCQualifiedId: {
14076 if (SrcType->isObjCQualifiedIdType()) {
14077 const ObjCObjectPointerType *srcOPT =
14078 SrcType->getAs<ObjCObjectPointerType>();
14079 for (auto *srcProto : srcOPT->quals()) {
14080 PDecl = srcProto;
14081 break;
14082 }
14083 if (const ObjCInterfaceType *IFaceT =
14084 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14085 IFace = IFaceT->getDecl();
14086 }
14087 else if (DstType->isObjCQualifiedIdType()) {
14088 const ObjCObjectPointerType *dstOPT =
14089 DstType->getAs<ObjCObjectPointerType>();
14090 for (auto *dstProto : dstOPT->quals()) {
14091 PDecl = dstProto;
14092 break;
14093 }
14094 if (const ObjCInterfaceType *IFaceT =
14095 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14096 IFace = IFaceT->getDecl();
14097 }
14098 DiagKind = diag::warn_incompatible_qualified_id;
14099 break;
14100 }
14101 case IncompatibleVectors:
14102 DiagKind = diag::warn_incompatible_vectors;
14103 break;
14104 case IncompatibleObjCWeakRef:
14105 DiagKind = diag::err_arc_weak_unavailable_assign;
14106 break;
14107 case Incompatible:
14108 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14109 if (Complained)
14110 *Complained = true;
14111 return true;
14112 }
14113
14114 DiagKind = diag::err_typecheck_convert_incompatible;
14115 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14116 MayHaveConvFixit = true;
14117 isInvalid = true;
14118 MayHaveFunctionDiff = true;
14119 break;
14120 }
14121
14122 QualType FirstType, SecondType;
14123 switch (Action) {
14124 case AA_Assigning:
14125 case AA_Initializing:
14126 // The destination type comes first.
14127 FirstType = DstType;
14128 SecondType = SrcType;
14129 break;
14130
14131 case AA_Returning:
14132 case AA_Passing:
14133 case AA_Passing_CFAudited:
14134 case AA_Converting:
14135 case AA_Sending:
14136 case AA_Casting:
14137 // The source type comes first.
14138 FirstType = SrcType;
14139 SecondType = DstType;
14140 break;
14141 }
14142
14143 PartialDiagnostic FDiag = PDiag(DiagKind);
14144 if (Action == AA_Passing_CFAudited)
14145 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14146 else
14147 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14148
14149 // If we can fix the conversion, suggest the FixIts.
14150 assert(ConvHints.isNull() || Hint.isNull());
14151 if (!ConvHints.isNull()) {
14152 for (FixItHint &H : ConvHints.Hints)
14153 FDiag << H;
14154 } else {
14155 FDiag << Hint;
14156 }
14157 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14158
14159 if (MayHaveFunctionDiff)
14160 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14161
14162 Diag(Loc, FDiag);
14163 if (DiagKind == diag::warn_incompatible_qualified_id &&
14164 PDecl && IFace && !IFace->hasDefinition())
14165 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14166 << IFace << PDecl;
14167
14168 if (SecondType == Context.OverloadTy)
14169 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14170 FirstType, /*TakingAddress=*/true);
14171
14172 if (CheckInferredResultType)
14173 EmitRelatedResultTypeNote(SrcExpr);
14174
14175 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14176 EmitRelatedResultTypeNoteForReturn(DstType);
14177
14178 if (Complained)
14179 *Complained = true;
14180 return isInvalid;
14181 }
14182
14183 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14184 llvm::APSInt *Result) {
14185 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14186 public:
14187 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14188 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14189 }
14190 } Diagnoser;
14191
14192 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14193 }
14194
14195 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14196 llvm::APSInt *Result,
14197 unsigned DiagID,
14198 bool AllowFold) {
14199 class IDDiagnoser : public VerifyICEDiagnoser {
14200 unsigned DiagID;
14201
14202 public:
14203 IDDiagnoser(unsigned DiagID)
14204 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14205
14206 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14207 S.Diag(Loc, DiagID) << SR;
14208 }
14209 } Diagnoser(DiagID);
14210
14211 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14212 }
14213
14214 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14215 SourceRange SR) {
14216 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14217 }
14218
14219 ExprResult
14220 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14221 VerifyICEDiagnoser &Diagnoser,
14222 bool AllowFold) {
14223 SourceLocation DiagLoc = E->getBeginLoc();
14224
14225 if (getLangOpts().CPlusPlus11) {
14226 // C++11 [expr.const]p5:
14227 // If an expression of literal class type is used in a context where an
14228 // integral constant expression is required, then that class type shall
14229 // have a single non-explicit conversion function to an integral or
14230 // unscoped enumeration type
14231 ExprResult Converted;
14232 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14233 public:
14234 CXX11ConvertDiagnoser(bool Silent)
14235 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14236 Silent, true) {}
14237
14238 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14239 QualType T) override {
14240 return S.Diag(Loc, diag::err_ice_not_integral) << T;
14241 }
14242
14243 SemaDiagnosticBuilder diagnoseIncomplete(
14244 Sema &S, SourceLocation Loc, QualType T) override {
14245 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14246 }
14247
14248 SemaDiagnosticBuilder diagnoseExplicitConv(
14249 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14250 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14251 }
14252
14253 SemaDiagnosticBuilder noteExplicitConv(
14254 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14255 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14256 << ConvTy->isEnumeralType() << ConvTy;
14257 }
14258
14259 SemaDiagnosticBuilder diagnoseAmbiguous(
14260 Sema &S, SourceLocation Loc, QualType T) override {
14261 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14262 }
14263
14264 SemaDiagnosticBuilder noteAmbiguous(
14265 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14266 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14267 << ConvTy->isEnumeralType() << ConvTy;
14268 }
14269
14270 SemaDiagnosticBuilder diagnoseConversion(
14271 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14272 llvm_unreachable("conversion functions are permitted");
14273 }
14274 } ConvertDiagnoser(Diagnoser.Suppress);
14275
14276 Converted = PerformContextualImplicitConversion(DiagLoc, E,
14277 ConvertDiagnoser);
14278 if (Converted.isInvalid())
14279 return Converted;
14280 E = Converted.get();
14281 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14282 return ExprError();
14283 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14284 // An ICE must be of integral or unscoped enumeration type.
14285 if (!Diagnoser.Suppress)
14286 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14287 return ExprError();
14288 }
14289
14290 if (!isa<ConstantExpr>(E))
14291 E = ConstantExpr::Create(Context, E);
14292
14293 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14294 // in the non-ICE case.
14295 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14296 if (Result)
14297 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14298 return E;
14299 }
14300
14301 Expr::EvalResult EvalResult;
14302 SmallVector<PartialDiagnosticAt, 8> Notes;
14303 EvalResult.Diag = &Notes;
14304
14305 // Try to evaluate the expression, and produce diagnostics explaining why it's
14306 // not a constant expression as a side-effect.
14307 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14308 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14309
14310 // In C++11, we can rely on diagnostics being produced for any expression
14311 // which is not a constant expression. If no diagnostics were produced, then
14312 // this is a constant expression.
14313 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14314 if (Result)
14315 *Result = EvalResult.Val.getInt();
14316 return E;
14317 }
14318
14319 // If our only note is the usual "invalid subexpression" note, just point
14320 // the caret at its location rather than producing an essentially
14321 // redundant note.
14322 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14323 diag::note_invalid_subexpr_in_const_expr) {
14324 DiagLoc = Notes[0].first;
14325 Notes.clear();
14326 }
14327
14328 if (!Folded || !AllowFold) {
14329 if (!Diagnoser.Suppress) {
14330 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14331 for (const PartialDiagnosticAt &Note : Notes)
14332 Diag(Note.first, Note.second);
14333 }
14334
14335 return ExprError();
14336 }
14337
14338 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14339 for (const PartialDiagnosticAt &Note : Notes)
14340 Diag(Note.first, Note.second);
14341
14342 if (Result)
14343 *Result = EvalResult.Val.getInt();
14344 return E;
14345 }
14346
14347 namespace {
14348 // Handle the case where we conclude a expression which we speculatively
14349 // considered to be unevaluated is actually evaluated.
14350 class TransformToPE : public TreeTransform<TransformToPE> {
14351 typedef TreeTransform<TransformToPE> BaseTransform;
14352
14353 public:
14354 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14355
14356 // Make sure we redo semantic analysis
14357 bool AlwaysRebuild() { return true; }
14358
14359 // Make sure we handle LabelStmts correctly.
14360 // FIXME: This does the right thing, but maybe we need a more general
14361 // fix to TreeTransform?
14362 StmtResult TransformLabelStmt(LabelStmt *S) {
14363 S->getDecl()->setStmt(nullptr);
14364 return BaseTransform::TransformLabelStmt(S);
14365 }
14366
14367 // We need to special-case DeclRefExprs referring to FieldDecls which
14368 // are not part of a member pointer formation; normal TreeTransforming
14369 // doesn't catch this case because of the way we represent them in the AST.
14370 // FIXME: This is a bit ugly; is it really the best way to handle this
14371 // case?
14372 //
14373 // Error on DeclRefExprs referring to FieldDecls.
14374 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14375 if (isa<FieldDecl>(E->getDecl()) &&
14376 !SemaRef.isUnevaluatedContext())
14377 return SemaRef.Diag(E->getLocation(),
14378 diag::err_invalid_non_static_member_use)
14379 << E->getDecl() << E->getSourceRange();
14380
14381 return BaseTransform::TransformDeclRefExpr(E);
14382 }
14383
14384 // Exception: filter out member pointer formation
14385 ExprResult TransformUnaryOperator(UnaryOperator *E) {
14386 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14387 return E;
14388
14389 return BaseTransform::TransformUnaryOperator(E);
14390 }
14391
14392 ExprResult TransformLambdaExpr(LambdaExpr *E) {
14393 // Lambdas never need to be transformed.
14394 return E;
14395 }
14396 };
14397 }
14398
14399 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14400 assert(isUnevaluatedContext() &&
14401 "Should only transform unevaluated expressions");
14402 ExprEvalContexts.back().Context =
14403 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14404 if (isUnevaluatedContext())
14405 return E;
14406 return TransformToPE(*this).TransformExpr(E);
14407 }
14408
14409 void
14410 Sema::PushExpressionEvaluationContext(
14411 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14412 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14413 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14414 LambdaContextDecl, ExprContext);
14415 Cleanup.reset();
14416 if (!MaybeODRUseExprs.empty())
14417 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14418 }
14419
14420 void
14421 Sema::PushExpressionEvaluationContext(
14422 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14423 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14424 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14425 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14426 }
14427
14428 namespace {
14429
14430 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14431 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14432 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14433 if (E->getOpcode() == UO_Deref)
14434 return CheckPossibleDeref(S, E->getSubExpr());
14435 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14436 return CheckPossibleDeref(S, E->getBase());
14437 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14438 return CheckPossibleDeref(S, E->getBase());
14439 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14440 QualType Inner;
14441 QualType Ty = E->getType();
14442 if (const auto *Ptr = Ty->getAs<PointerType>())
14443 Inner = Ptr->getPointeeType();
14444 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14445 Inner = Arr->getElementType();
14446 else
14447 return nullptr;
14448
14449 if (Inner->hasAttr(attr::NoDeref))
14450 return E;
14451 }
14452 return nullptr;
14453 }
14454
14455 } // namespace
14456
14457 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14458 for (const Expr *E : Rec.PossibleDerefs) {
14459 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14460 if (DeclRef) {
14461 const ValueDecl *Decl = DeclRef->getDecl();
14462 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14463 << Decl->getName() << E->getSourceRange();
14464 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14465 } else {
14466 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14467 << E->getSourceRange();
14468 }
14469 }
14470 Rec.PossibleDerefs.clear();
14471 }
14472
14473 void Sema::PopExpressionEvaluationContext() {
14474 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14475 unsigned NumTypos = Rec.NumTypos;
14476
14477 if (!Rec.Lambdas.empty()) {
14478 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14479 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14480 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14481 unsigned D;
14482 if (Rec.isUnevaluated()) {
14483 // C++11 [expr.prim.lambda]p2:
14484 // A lambda-expression shall not appear in an unevaluated operand
14485 // (Clause 5).
14486 D = diag::err_lambda_unevaluated_operand;
14487 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14488 // C++1y [expr.const]p2:
14489 // A conditional-expression e is a core constant expression unless the
14490 // evaluation of e, following the rules of the abstract machine, would
14491 // evaluate [...] a lambda-expression.
14492 D = diag::err_lambda_in_constant_expression;
14493 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14494 // C++17 [expr.prim.lamda]p2:
14495 // A lambda-expression shall not appear [...] in a template-argument.
14496 D = diag::err_lambda_in_invalid_context;
14497 } else
14498 llvm_unreachable("Couldn't infer lambda error message.");
14499
14500 for (const auto *L : Rec.Lambdas)
14501 Diag(L->getBeginLoc(), D);
14502 } else {
14503 // Mark the capture expressions odr-used. This was deferred
14504 // during lambda expression creation.
14505 for (auto *Lambda : Rec.Lambdas) {
14506 for (auto *C : Lambda->capture_inits())
14507 MarkDeclarationsReferencedInExpr(C);
14508 }
14509 }
14510 }
14511
14512 WarnOnPendingNoDerefs(Rec);
14513
14514 // When are coming out of an unevaluated context, clear out any
14515 // temporaries that we may have created as part of the evaluation of
14516 // the expression in that context: they aren't relevant because they
14517 // will never be constructed.
14518 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14519 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14520 ExprCleanupObjects.end());
14521 Cleanup = Rec.ParentCleanup;
14522 CleanupVarDeclMarking();
14523 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14524 // Otherwise, merge the contexts together.
14525 } else {
14526 Cleanup.mergeFrom(Rec.ParentCleanup);
14527 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14528 Rec.SavedMaybeODRUseExprs.end());
14529 }
14530
14531 // Pop the current expression evaluation context off the stack.
14532 ExprEvalContexts.pop_back();
14533
14534 // The global expression evaluation context record is never popped.
14535 ExprEvalContexts.back().NumTypos += NumTypos;
14536 }
14537
14538 void Sema::DiscardCleanupsInEvaluationContext() {
14539 ExprCleanupObjects.erase(
14540 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14541 ExprCleanupObjects.end());
14542 Cleanup.reset();
14543 MaybeODRUseExprs.clear();
14544 }
14545
14546 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14547 ExprResult Result = CheckPlaceholderExpr(E);
14548 if (Result.isInvalid())
14549 return ExprError();
14550 E = Result.get();
14551 if (!E->getType()->isVariablyModifiedType())
14552 return E;
14553 return TransformToPotentiallyEvaluated(E);
14554 }
14555
14556 /// Are we within a context in which some evaluation could be performed (be it
14557 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14558 /// captured by C++'s idea of an "unevaluated context".
14559 static bool isEvaluatableContext(Sema &SemaRef) {
14560 switch (SemaRef.ExprEvalContexts.back().Context) {
14561 case Sema::ExpressionEvaluationContext::Unevaluated:
14562 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14563 // Expressions in this context are never evaluated.
14564 return false;
14565
14566 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14567 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14568 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14569 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14570 // Expressions in this context could be evaluated.
14571 return true;
14572
14573 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14574 // Referenced declarations will only be used if the construct in the
14575 // containing expression is used, at which point we'll be given another
14576 // turn to mark them.
14577 return false;
14578 }
14579 llvm_unreachable("Invalid context");
14580 }
14581
14582 /// Are we within a context in which references to resolved functions or to
14583 /// variables result in odr-use?
14584 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14585 // An expression in a template is not really an expression until it's been
14586 // instantiated, so it doesn't trigger odr-use.
14587 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14588 return false;
14589
14590 switch (SemaRef.ExprEvalContexts.back().Context) {
14591 case Sema::ExpressionEvaluationContext::Unevaluated:
14592 case Sema::ExpressionEvaluationContext::UnevaluatedList:
14593 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14594 case Sema::ExpressionEvaluationContext::DiscardedStatement:
14595 return false;
14596
14597 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14598 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14599 return true;
14600
14601 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14602 return false;
14603 }
14604 llvm_unreachable("Invalid context");
14605 }
14606
14607 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14608 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14609 return Func->isConstexpr() &&
14610 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14611 }
14612
14613 /// Mark a function referenced, and check whether it is odr-used
14614 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14615 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14616 bool MightBeOdrUse) {
14617 assert(Func && "No function?");
14618
14619 Func->setReferenced();
14620
14621 // C++11 [basic.def.odr]p3:
14622 // A function whose name appears as a potentially-evaluated expression is
14623 // odr-used if it is the unique lookup result or the selected member of a
14624 // set of overloaded functions [...].
14625 //
14626 // We (incorrectly) mark overload resolution as an unevaluated context, so we
14627 // can just check that here.
14628 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14629
14630 // Determine whether we require a function definition to exist, per
14631 // C++11 [temp.inst]p3:
14632 // Unless a function template specialization has been explicitly
14633 // instantiated or explicitly specialized, the function template
14634 // specialization is implicitly instantiated when the specialization is
14635 // referenced in a context that requires a function definition to exist.
14636 //
14637 // That is either when this is an odr-use, or when a usage of a constexpr
14638 // function occurs within an evaluatable context.
14639 bool NeedDefinition =
14640 OdrUse || (isEvaluatableContext(*this) &&
14641 isImplicitlyDefinableConstexprFunction(Func));
14642
14643 // C++14 [temp.expl.spec]p6:
14644 // If a template [...] is explicitly specialized then that specialization
14645 // shall be declared before the first use of that specialization that would
14646 // cause an implicit instantiation to take place, in every translation unit
14647 // in which such a use occurs
14648 if (NeedDefinition &&
14649 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14650 Func->getMemberSpecializationInfo()))
14651 checkSpecializationVisibility(Loc, Func);
14652
14653 // C++14 [except.spec]p17:
14654 // An exception-specification is considered to be needed when:
14655 // - the function is odr-used or, if it appears in an unevaluated operand,
14656 // would be odr-used if the expression were potentially-evaluated;
14657 //
14658 // Note, we do this even if MightBeOdrUse is false. That indicates that the
14659 // function is a pure virtual function we're calling, and in that case the
14660 // function was selected by overload resolution and we need to resolve its
14661 // exception specification for a different reason.
14662 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14663 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14664 ResolveExceptionSpec(Loc, FPT);
14665
14666 // If we don't need to mark the function as used, and we don't need to
14667 // try to provide a definition, there's nothing more to do.
14668 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14669 (!NeedDefinition || Func->getBody()))
14670 return;
14671
14672 // Note that this declaration has been used.
14673 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14674 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14675 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14676 if (Constructor->isDefaultConstructor()) {
14677 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14678 return;
14679 DefineImplicitDefaultConstructor(Loc, Constructor);
14680 } else if (Constructor->isCopyConstructor()) {
14681 DefineImplicitCopyConstructor(Loc, Constructor);
14682 } else if (Constructor->isMoveConstructor()) {
14683 DefineImplicitMoveConstructor(Loc, Constructor);
14684 }
14685 } else if (Constructor->getInheritedConstructor()) {
14686 DefineInheritingConstructor(Loc, Constructor);
14687 }
14688 } else if (CXXDestructorDecl *Destructor =
14689 dyn_cast<CXXDestructorDecl>(Func)) {
14690 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14691 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14692 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14693 return;
14694 DefineImplicitDestructor(Loc, Destructor);
14695 }
14696 if (Destructor->isVirtual() && getLangOpts().AppleKext)
14697 MarkVTableUsed(Loc, Destructor->getParent());
14698 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14699 if (MethodDecl->isOverloadedOperator() &&
14700 MethodDecl->getOverloadedOperator() == OO_Equal) {
14701 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14702 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14703 if (MethodDecl->isCopyAssignmentOperator())
14704 DefineImplicitCopyAssignment(Loc, MethodDecl);
14705 else if (MethodDecl->isMoveAssignmentOperator())
14706 DefineImplicitMoveAssignment(Loc, MethodDecl);
14707 }
14708 } else if (isa<CXXConversionDecl>(MethodDecl) &&
14709 MethodDecl->getParent()->isLambda()) {
14710 CXXConversionDecl *Conversion =
14711 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14712 if (Conversion->isLambdaToBlockPointerConversion())
14713 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14714 else
14715 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14716 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14717 MarkVTableUsed(Loc, MethodDecl->getParent());
14718 }
14719
14720 // Recursive functions should be marked when used from another function.
14721 // FIXME: Is this really right?
14722 if (CurContext == Func) return;
14723
14724 // Implicit instantiation of function templates and member functions of
14725 // class templates.
14726 if (Func->isImplicitlyInstantiable()) {
14727 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14728 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14729 bool FirstInstantiation = PointOfInstantiation.isInvalid();
14730 if (FirstInstantiation) {
14731 PointOfInstantiation = Loc;
14732 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14733 } else if (TSK != TSK_ImplicitInstantiation) {
14734 // Use the point of use as the point of instantiation, instead of the
14735 // point of explicit instantiation (which we track as the actual point of
14736 // instantiation). This gives better backtraces in diagnostics.
14737 PointOfInstantiation = Loc;
14738 }
14739
14740 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14741 Func->isConstexpr()) {
14742 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14743 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14744 CodeSynthesisContexts.size())
14745 PendingLocalImplicitInstantiations.push_back(
14746 std::make_pair(Func, PointOfInstantiation));
14747 else if (Func->isConstexpr())
14748 // Do not defer instantiations of constexpr functions, to avoid the
14749 // expression evaluator needing to call back into Sema if it sees a
14750 // call to such a function.
14751 InstantiateFunctionDefinition(PointOfInstantiation, Func);
14752 else {
14753 Func->setInstantiationIsPending(true);
14754 PendingInstantiations.push_back(std::make_pair(Func,
14755 PointOfInstantiation));
14756 // Notify the consumer that a function was implicitly instantiated.
14757 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14758 }
14759 }
14760 } else {
14761 // Walk redefinitions, as some of them may be instantiable.
14762 for (auto i : Func->redecls()) {
14763 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14764 MarkFunctionReferenced(Loc, i, OdrUse);
14765 }
14766 }
14767
14768 if (!OdrUse) return;
14769
14770 // Keep track of used but undefined functions.
14771 if (!Func->isDefined()) {
14772 if (mightHaveNonExternalLinkage(Func))
14773 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14774 else if (Func->getMostRecentDecl()->isInlined() &&
14775 !LangOpts.GNUInline &&
14776 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14777 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14778 else if (isExternalWithNoLinkageType(Func))
14779 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14780 }
14781
14782 Func->markUsed(Context);
14783 }
14784
14785 static void
14786 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14787 ValueDecl *var, DeclContext *DC) {
14788 DeclContext *VarDC = var->getDeclContext();
14789
14790 // If the parameter still belongs to the translation unit, then
14791 // we're actually just using one parameter in the declaration of
14792 // the next.
14793 if (isa<ParmVarDecl>(var) &&
14794 isa<TranslationUnitDecl>(VarDC))
14795 return;
14796
14797 // For C code, don't diagnose about capture if we're not actually in code
14798 // right now; it's impossible to write a non-constant expression outside of
14799 // function context, so we'll get other (more useful) diagnostics later.
14800 //
14801 // For C++, things get a bit more nasty... it would be nice to suppress this
14802 // diagnostic for certain cases like using a local variable in an array bound
14803 // for a member of a local class, but the correct predicate is not obvious.
14804 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14805 return;
14806
14807 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14808 unsigned ContextKind = 3; // unknown
14809 if (isa<CXXMethodDecl>(VarDC) &&
14810 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14811 ContextKind = 2;
14812 } else if (isa<FunctionDecl>(VarDC)) {
14813 ContextKind = 0;
14814 } else if (isa<BlockDecl>(VarDC)) {
14815 ContextKind = 1;
14816 }
14817
14818 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14819 << var << ValueKind << ContextKind << VarDC;
14820 S.Diag(var->getLocation(), diag::note_entity_declared_at)
14821 << var;
14822
14823 // FIXME: Add additional diagnostic info about class etc. which prevents
14824 // capture.
14825 }
14826
14827
14828 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14829 bool &SubCapturesAreNested,
14830 QualType &CaptureType,
14831 QualType &DeclRefType) {
14832 // Check whether we've already captured it.
14833 if (CSI->CaptureMap.count(Var)) {
14834 // If we found a capture, any subcaptures are nested.
14835 SubCapturesAreNested = true;
14836
14837 // Retrieve the capture type for this variable.
14838 CaptureType = CSI->getCapture(Var).getCaptureType();
14839
14840 // Compute the type of an expression that refers to this variable.
14841 DeclRefType = CaptureType.getNonReferenceType();
14842
14843 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14844 // are mutable in the sense that user can change their value - they are
14845 // private instances of the captured declarations.
14846 const Capture &Cap = CSI->getCapture(Var);
14847 if (Cap.isCopyCapture() &&
14848 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14849 !(isa<CapturedRegionScopeInfo>(CSI) &&
14850 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14851 DeclRefType.addConst();
14852 return true;
14853 }
14854 return false;
14855 }
14856
14857 // Only block literals, captured statements, and lambda expressions can
14858 // capture; other scopes don't work.
14859 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14860 SourceLocation Loc,
14861 const bool Diagnose, Sema &S) {
14862 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14863 return getLambdaAwareParentOfDeclContext(DC);
14864 else if (Var->hasLocalStorage()) {
14865 if (Diagnose)
14866 diagnoseUncapturableValueReference(S, Loc, Var, DC);
14867 }
14868 return nullptr;
14869 }
14870
14871 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14872 // certain types of variables (unnamed, variably modified types etc.)
14873 // so check for eligibility.
14874 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14875 SourceLocation Loc,
14876 const bool Diagnose, Sema &S) {
14877
14878 bool IsBlock = isa<BlockScopeInfo>(CSI);
14879 bool IsLambda = isa<LambdaScopeInfo>(CSI);
14880
14881 // Lambdas are not allowed to capture unnamed variables
14882 // (e.g. anonymous unions).
14883 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14884 // assuming that's the intent.
14885 if (IsLambda && !Var->getDeclName()) {
14886 if (Diagnose) {
14887 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14888 S.Diag(Var->getLocation(), diag::note_declared_at);
14889 }
14890 return false;
14891 }
14892
14893 // Prohibit variably-modified types in blocks; they're difficult to deal with.
14894 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14895 if (Diagnose) {
14896 S.Diag(Loc, diag::err_ref_vm_type);
14897 S.Diag(Var->getLocation(), diag::note_previous_decl)
14898 << Var->getDeclName();
14899 }
14900 return false;
14901 }
14902 // Prohibit structs with flexible array members too.
14903 // We cannot capture what is in the tail end of the struct.
14904 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14905 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14906 if (Diagnose) {
14907 if (IsBlock)
14908 S.Diag(Loc, diag::err_ref_flexarray_type);
14909 else
14910 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14911 << Var->getDeclName();
14912 S.Diag(Var->getLocation(), diag::note_previous_decl)
14913 << Var->getDeclName();
14914 }
14915 return false;
14916 }
14917 }
14918 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14919 // Lambdas and captured statements are not allowed to capture __block
14920 // variables; they don't support the expected semantics.
14921 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14922 if (Diagnose) {
14923 S.Diag(Loc, diag::err_capture_block_variable)
14924 << Var->getDeclName() << !IsLambda;
14925 S.Diag(Var->getLocation(), diag::note_previous_decl)
14926 << Var->getDeclName();
14927 }
14928 return false;
14929 }
14930 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14931 if (S.getLangOpts().OpenCL && IsBlock &&
14932 Var->getType()->isBlockPointerType()) {
14933 if (Diagnose)
14934 S.Diag(Loc, diag::err_opencl_block_ref_block);
14935 return false;
14936 }
14937
14938 return true;
14939 }
14940
14941 // Returns true if the capture by block was successful.
14942 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14943 SourceLocation Loc,
14944 const bool BuildAndDiagnose,
14945 QualType &CaptureType,
14946 QualType &DeclRefType,
14947 const bool Nested,
14948 Sema &S) {
14949 Expr *CopyExpr = nullptr;
14950 bool ByRef = false;
14951
14952 // Blocks are not allowed to capture arrays, excepting OpenCL.
14953 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14954 // (decayed to pointers).
14955 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14956 if (BuildAndDiagnose) {
14957 S.Diag(Loc, diag::err_ref_array_type);
14958 S.Diag(Var->getLocation(), diag::note_previous_decl)
14959 << Var->getDeclName();
14960 }
14961 return false;
14962 }
14963
14964 // Forbid the block-capture of autoreleasing variables.
14965 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14966 if (BuildAndDiagnose) {
14967 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14968 << /*block*/ 0;
14969 S.Diag(Var->getLocation(), diag::note_previous_decl)
14970 << Var->getDeclName();
14971 }
14972 return false;
14973 }
14974
14975 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14976 if (const auto *PT = CaptureType->getAs<PointerType>()) {
14977 // This function finds out whether there is an AttributedType of kind
14978 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14979 // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14980 // rather than being added implicitly by the compiler.
14981 auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14982 while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14983 if (AttrTy->getAttrKind() == attr::ObjCOwnership)
14984 return true;
14985
14986 // Peel off AttributedTypes that are not of kind ObjCOwnership.
14987 Ty = AttrTy->getModifiedType();
14988 }
14989
14990 return false;
14991 };
14992
14993 QualType PointeeTy = PT->getPointeeType();
14994
14995 if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14996 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14997 !IsObjCOwnershipAttributedType(PointeeTy)) {
14998 if (BuildAndDiagnose) {
14999 SourceLocation VarLoc = Var->getLocation();
15000 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15001 S.Diag(VarLoc, diag::note_declare_parameter_strong);
15002 }
15003 }
15004 }
15005
15006 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15007 if (HasBlocksAttr || CaptureType->isReferenceType() ||
15008 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15009 // Block capture by reference does not change the capture or
15010 // declaration reference types.
15011 ByRef = true;
15012 } else {
15013 // Block capture by copy introduces 'const'.
15014 CaptureType = CaptureType.getNonReferenceType().withConst();
15015 DeclRefType = CaptureType;
15016
15017 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15018 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15019 // The capture logic needs the destructor, so make sure we mark it.
15020 // Usually this is unnecessary because most local variables have
15021 // their destructors marked at declaration time, but parameters are
15022 // an exception because it's technically only the call site that
15023 // actually requires the destructor.
15024 if (isa<ParmVarDecl>(Var))
15025 S.FinalizeVarWithDestructor(Var, Record);
15026
15027 // Enter a new evaluation context to insulate the copy
15028 // full-expression.
15029 EnterExpressionEvaluationContext scope(
15030 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15031
15032 // According to the blocks spec, the capture of a variable from
15033 // the stack requires a const copy constructor. This is not true
15034 // of the copy/move done to move a __block variable to the heap.
15035 Expr *DeclRef = new (S.Context) DeclRefExpr(
15036 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15037
15038 ExprResult Result
15039 = S.PerformCopyInitialization(
15040 InitializedEntity::InitializeBlock(Var->getLocation(),
15041 CaptureType, false),
15042 Loc, DeclRef);
15043
15044 // Build a full-expression copy expression if initialization
15045 // succeeded and used a non-trivial constructor. Recover from
15046 // errors by pretending that the copy isn't necessary.
15047 if (!Result.isInvalid() &&
15048 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15049 ->isTrivial()) {
15050 Result = S.MaybeCreateExprWithCleanups(Result);
15051 CopyExpr = Result.get();
15052 }
15053 }
15054 }
15055 }
15056
15057 // Actually capture the variable.
15058 if (BuildAndDiagnose)
15059 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15060 SourceLocation(), CaptureType, CopyExpr);
15061
15062 return true;
15063
15064 }
15065
15066
15067 /// Capture the given variable in the captured region.
15068 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15069 VarDecl *Var,
15070 SourceLocation Loc,
15071 const bool BuildAndDiagnose,
15072 QualType &CaptureType,
15073 QualType &DeclRefType,
15074 const bool RefersToCapturedVariable,
15075 Sema &S) {
15076 // By default, capture variables by reference.
15077 bool ByRef = true;
15078 // Using an LValue reference type is consistent with Lambdas (see below).
15079 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15080 if (S.isOpenMPCapturedDecl(Var)) {
15081 bool HasConst = DeclRefType.isConstQualified();
15082 DeclRefType = DeclRefType.getUnqualifiedType();
15083 // Don't lose diagnostics about assignments to const.
15084 if (HasConst)
15085 DeclRefType.addConst();
15086 }
15087 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15088 }
15089
15090 if (ByRef)
15091 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15092 else
15093 CaptureType = DeclRefType;
15094
15095 Expr *CopyExpr = nullptr;
15096 if (BuildAndDiagnose) {
15097 // The current implementation assumes that all variables are captured
15098 // by references. Since there is no capture by copy, no expression
15099 // evaluation will be needed.
15100 RecordDecl *RD = RSI->TheRecordDecl;
15101
15102 FieldDecl *Field
15103 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15104 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15105 nullptr, false, ICIS_NoInit);
15106 Field->setImplicit(true);
15107 Field->setAccess(AS_private);
15108 RD->addDecl(Field);
15109 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15110 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15111
15112 CopyExpr = new (S.Context) DeclRefExpr(
15113 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15114 Var->setReferenced(true);
15115 Var->markUsed(S.Context);
15116 }
15117
15118 // Actually capture the variable.
15119 if (BuildAndDiagnose)
15120 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15121 SourceLocation(), CaptureType, CopyExpr);
15122
15123
15124 return true;
15125 }
15126
15127 /// Create a field within the lambda class for the variable
15128 /// being captured.
15129 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15130 QualType FieldType, QualType DeclRefType,
15131 SourceLocation Loc,
15132 bool RefersToCapturedVariable) {
15133 CXXRecordDecl *Lambda = LSI->Lambda;
15134
15135 // Build the non-static data member.
15136 FieldDecl *Field
15137 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15138 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15139 nullptr, false, ICIS_NoInit);
15140 // If the variable being captured has an invalid type, mark the lambda class
15141 // as invalid as well.
15142 if (!FieldType->isDependentType()) {
15143 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15144 Lambda->setInvalidDecl();
15145 Field->setInvalidDecl();
15146 } else {
15147 NamedDecl *Def;
15148 FieldType->isIncompleteType(&Def);
15149 if (Def && Def->isInvalidDecl()) {
15150 Lambda->setInvalidDecl();
15151 Field->setInvalidDecl();
15152 }
15153 }
15154 }
15155 Field->setImplicit(true);
15156 Field->setAccess(AS_private);
15157 Lambda->addDecl(Field);
15158 }
15159
15160 /// Capture the given variable in the lambda.
15161 static bool captureInLambda(LambdaScopeInfo *LSI,
15162 VarDecl *Var,
15163 SourceLocation Loc,
15164 const bool BuildAndDiagnose,
15165 QualType &CaptureType,
15166 QualType &DeclRefType,
15167 const bool RefersToCapturedVariable,
15168 const Sema::TryCaptureKind Kind,
15169 SourceLocation EllipsisLoc,
15170 const bool IsTopScope,
15171 Sema &S) {
15172
15173 // Determine whether we are capturing by reference or by value.
15174 bool ByRef = false;
15175 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15176 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15177 } else {
15178 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15179 }
15180
15181 // Compute the type of the field that will capture this variable.
15182 if (ByRef) {
15183 // C++11 [expr.prim.lambda]p15:
15184 // An entity is captured by reference if it is implicitly or
15185 // explicitly captured but not captured by copy. It is
15186 // unspecified whether additional unnamed non-static data
15187 // members are declared in the closure type for entities
15188 // captured by reference.
15189 //
15190 // FIXME: It is not clear whether we want to build an lvalue reference
15191 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15192 // to do the former, while EDG does the latter. Core issue 1249 will
15193 // clarify, but for now we follow GCC because it's a more permissive and
15194 // easily defensible position.
15195 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15196 } else {
15197 // C++11 [expr.prim.lambda]p14:
15198 // For each entity captured by copy, an unnamed non-static
15199 // data member is declared in the closure type. The
15200 // declaration order of these members is unspecified. The type
15201 // of such a data member is the type of the corresponding
15202 // captured entity if the entity is not a reference to an
15203 // object, or the referenced type otherwise. [Note: If the
15204 // captured entity is a reference to a function, the
15205 // corresponding data member is also a reference to a
15206 // function. - end note ]
15207 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15208 if (!RefType->getPointeeType()->isFunctionType())
15209 CaptureType = RefType->getPointeeType();
15210 }
15211
15212 // Forbid the lambda copy-capture of autoreleasing variables.
15213 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15214 if (BuildAndDiagnose) {
15215 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15216 S.Diag(Var->getLocation(), diag::note_previous_decl)
15217 << Var->getDeclName();
15218 }
15219 return false;
15220 }
15221
15222 // Make sure that by-copy captures are of a complete and non-abstract type.
15223 if (BuildAndDiagnose) {
15224 if (!CaptureType->isDependentType() &&
15225 S.RequireCompleteType(Loc, CaptureType,
15226 diag::err_capture_of_incomplete_type,
15227 Var->getDeclName()))
15228 return false;
15229
15230 if (S.RequireNonAbstractType(Loc, CaptureType,
15231 diag::err_capture_of_abstract_type))
15232 return false;
15233 }
15234 }
15235
15236 // Capture this variable in the lambda.
15237 if (BuildAndDiagnose)
15238 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15239 RefersToCapturedVariable);
15240
15241 // Compute the type of a reference to this captured variable.
15242 if (ByRef)
15243 DeclRefType = CaptureType.getNonReferenceType();
15244 else {
15245 // C++ [expr.prim.lambda]p5:
15246 // The closure type for a lambda-expression has a public inline
15247 // function call operator [...]. This function call operator is
15248 // declared const (9.3.1) if and only if the lambda-expression's
15249 // parameter-declaration-clause is not followed by mutable.
15250 DeclRefType = CaptureType.getNonReferenceType();
15251 if (!LSI->Mutable && !CaptureType->isReferenceType())
15252 DeclRefType.addConst();
15253 }
15254
15255 // Add the capture.
15256 if (BuildAndDiagnose)
15257 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15258 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15259
15260 return true;
15261 }
15262
15263 bool Sema::tryCaptureVariable(
15264 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15265 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15266 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15267 // An init-capture is notionally from the context surrounding its
15268 // declaration, but its parent DC is the lambda class.
15269 DeclContext *VarDC = Var->getDeclContext();
15270 if (Var->isInitCapture())
15271 VarDC = VarDC->getParent();
15272
15273 DeclContext *DC = CurContext;
15274 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15275 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15276 // We need to sync up the Declaration Context with the
15277 // FunctionScopeIndexToStopAt
15278 if (FunctionScopeIndexToStopAt) {
15279 unsigned FSIndex = FunctionScopes.size() - 1;
15280 while (FSIndex != MaxFunctionScopesIndex) {
15281 DC = getLambdaAwareParentOfDeclContext(DC);
15282 --FSIndex;
15283 }
15284 }
15285
15286
15287 // If the variable is declared in the current context, there is no need to
15288 // capture it.
15289 if (VarDC == DC) return true;
15290
15291 // Capture global variables if it is required to use private copy of this
15292 // variable.
15293 bool IsGlobal = !Var->hasLocalStorage();
15294 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15295 return true;
15296 Var = Var->getCanonicalDecl();
15297
15298 // Walk up the stack to determine whether we can capture the variable,
15299 // performing the "simple" checks that don't depend on type. We stop when
15300 // we've either hit the declared scope of the variable or find an existing
15301 // capture of that variable. We start from the innermost capturing-entity
15302 // (the DC) and ensure that all intervening capturing-entities
15303 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15304 // declcontext can either capture the variable or have already captured
15305 // the variable.
15306 CaptureType = Var->getType();
15307 DeclRefType = CaptureType.getNonReferenceType();
15308 bool Nested = false;
15309 bool Explicit = (Kind != TryCapture_Implicit);
15310 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15311 do {
15312 // Only block literals, captured statements, and lambda expressions can
15313 // capture; other scopes don't work.
15314 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15315 ExprLoc,
15316 BuildAndDiagnose,
15317 *this);
15318 // We need to check for the parent *first* because, if we *have*
15319 // private-captured a global variable, we need to recursively capture it in
15320 // intermediate blocks, lambdas, etc.
15321 if (!ParentDC) {
15322 if (IsGlobal) {
15323 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15324 break;
15325 }
15326 return true;
15327 }
15328
15329 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
15330 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15331
15332
15333 // Check whether we've already captured it.
15334 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15335 DeclRefType)) {
15336 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15337 break;
15338 }
15339 // If we are instantiating a generic lambda call operator body,
15340 // we do not want to capture new variables. What was captured
15341 // during either a lambdas transformation or initial parsing
15342 // should be used.
15343 if (isGenericLambdaCallOperatorSpecialization(DC)) {
15344 if (BuildAndDiagnose) {
15345 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15346 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15347 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15348 Diag(Var->getLocation(), diag::note_previous_decl)
15349 << Var->getDeclName();
15350 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15351 } else
15352 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15353 }
15354 return true;
15355 }
15356 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15357 // certain types of variables (unnamed, variably modified types etc.)
15358 // so check for eligibility.
15359 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15360 return true;
15361
15362 // Try to capture variable-length arrays types.
15363 if (Var->getType()->isVariablyModifiedType()) {
15364 // We're going to walk down into the type and look for VLA
15365 // expressions.
15366 QualType QTy = Var->getType();
15367 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15368 QTy = PVD->getOriginalType();
15369 captureVariablyModifiedType(Context, QTy, CSI);
15370 }
15371
15372 if (getLangOpts().OpenMP) {
15373 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15374 // OpenMP private variables should not be captured in outer scope, so
15375 // just break here. Similarly, global variables that are captured in a
15376 // target region should not be captured outside the scope of the region.
15377 if (RSI->CapRegionKind == CR_OpenMP) {
15378 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15379 auto IsTargetCap = !IsOpenMPPrivateDecl &&
15380 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15381 // When we detect target captures we are looking from inside the
15382 // target region, therefore we need to propagate the capture from the
15383 // enclosing region. Therefore, the capture is not initially nested.
15384 if (IsTargetCap)
15385 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15386
15387 if (IsTargetCap || IsOpenMPPrivateDecl) {
15388 Nested = !IsTargetCap;
15389 DeclRefType = DeclRefType.getUnqualifiedType();
15390 CaptureType = Context.getLValueReferenceType(DeclRefType);
15391 break;
15392 }
15393 }
15394 }
15395 }
15396 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15397 // No capture-default, and this is not an explicit capture
15398 // so cannot capture this variable.
15399 if (BuildAndDiagnose) {
15400 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15401 Diag(Var->getLocation(), diag::note_previous_decl)
15402 << Var->getDeclName();
15403 if (cast<LambdaScopeInfo>(CSI)->Lambda)
15404 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15405 diag::note_lambda_decl);
15406 // FIXME: If we error out because an outer lambda can not implicitly
15407 // capture a variable that an inner lambda explicitly captures, we
15408 // should have the inner lambda do the explicit capture - because
15409 // it makes for cleaner diagnostics later. This would purely be done
15410 // so that the diagnostic does not misleadingly claim that a variable
15411 // can not be captured by a lambda implicitly even though it is captured
15412 // explicitly. Suggestion:
15413 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15414 // at the function head
15415 // - cache the StartingDeclContext - this must be a lambda
15416 // - captureInLambda in the innermost lambda the variable.
15417 }
15418 return true;
15419 }
15420
15421 FunctionScopesIndex--;
15422 DC = ParentDC;
15423 Explicit = false;
15424 } while (!VarDC->Equals(DC));
15425
15426 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15427 // computing the type of the capture at each step, checking type-specific
15428 // requirements, and adding captures if requested.
15429 // If the variable had already been captured previously, we start capturing
15430 // at the lambda nested within that one.
15431 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15432 ++I) {
15433 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15434
15435 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15436 if (!captureInBlock(BSI, Var, ExprLoc,
15437 BuildAndDiagnose, CaptureType,
15438 DeclRefType, Nested, *this))
15439 return true;
15440 Nested = true;
15441 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15442 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15443 BuildAndDiagnose, CaptureType,
15444 DeclRefType, Nested, *this))
15445 return true;
15446 Nested = true;
15447 } else {
15448 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15449 if (!captureInLambda(LSI, Var, ExprLoc,
15450 BuildAndDiagnose, CaptureType,
15451 DeclRefType, Nested, Kind, EllipsisLoc,
15452 /*IsTopScope*/I == N - 1, *this))
15453 return true;
15454 Nested = true;
15455 }
15456 }
15457 return false;
15458 }
15459
15460 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15461 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15462 QualType CaptureType;
15463 QualType DeclRefType;
15464 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15465 /*BuildAndDiagnose=*/true, CaptureType,
15466 DeclRefType, nullptr);
15467 }
15468
15469 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15470 QualType CaptureType;
15471 QualType DeclRefType;
15472 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15473 /*BuildAndDiagnose=*/false, CaptureType,
15474 DeclRefType, nullptr);
15475 }
15476
15477 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15478 QualType CaptureType;
15479 QualType DeclRefType;
15480
15481 // Determine whether we can capture this variable.
15482 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15483 /*BuildAndDiagnose=*/false, CaptureType,
15484 DeclRefType, nullptr))
15485 return QualType();
15486
15487 return DeclRefType;
15488 }
15489
15490
15491
15492 // If either the type of the variable or the initializer is dependent,
15493 // return false. Otherwise, determine whether the variable is a constant
15494 // expression. Use this if you need to know if a variable that might or
15495 // might not be dependent is truly a constant expression.
15496 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15497 ASTContext &Context) {
15498
15499 if (Var->getType()->isDependentType())
15500 return false;
15501 const VarDecl *DefVD = nullptr;
15502 Var->getAnyInitializer(DefVD);
15503 if (!DefVD)
15504 return false;
15505 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15506 Expr *Init = cast<Expr>(Eval->Value);
15507 if (Init->isValueDependent())
15508 return false;
15509 return IsVariableAConstantExpression(Var, Context);
15510 }
15511
15512
15513 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15514 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15515 // an object that satisfies the requirements for appearing in a
15516 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15517 // is immediately applied." This function handles the lvalue-to-rvalue
15518 // conversion part.
15519 MaybeODRUseExprs.erase(E->IgnoreParens());
15520
15521 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15522 // to a variable that is a constant expression, and if so, identify it as
15523 // a reference to a variable that does not involve an odr-use of that
15524 // variable.
15525 if (LambdaScopeInfo *LSI = getCurLambda()) {
15526 Expr *SansParensExpr = E->IgnoreParens();
15527 VarDecl *Var = nullptr;
15528 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15529 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15530 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15531 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15532
15533 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15534 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15535 }
15536 }
15537
15538 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15539 Res = CorrectDelayedTyposInExpr(Res);
15540
15541 if (!Res.isUsable())
15542 return Res;
15543
15544 // If a constant-expression is a reference to a variable where we delay
15545 // deciding whether it is an odr-use, just assume we will apply the
15546 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
15547 // (a non-type template argument), we have special handling anyway.
15548 UpdateMarkingForLValueToRValue(Res.get());
15549 return Res;
15550 }
15551
15552 void Sema::CleanupVarDeclMarking() {
15553 for (Expr *E : MaybeODRUseExprs) {
15554 VarDecl *Var;
15555 SourceLocation Loc;
15556 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15557 Var = cast<VarDecl>(DRE->getDecl());
15558 Loc = DRE->getLocation();
15559 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15560 Var = cast<VarDecl>(ME->getMemberDecl());
15561 Loc = ME->getMemberLoc();
15562 } else {
15563 llvm_unreachable("Unexpected expression");
15564 }
15565
15566 MarkVarDeclODRUsed(Var, Loc, *this,
15567 /*MaxFunctionScopeIndex Pointer*/ nullptr);
15568 }
15569
15570 MaybeODRUseExprs.clear();
15571 }
15572
15573
15574 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15575 VarDecl *Var, Expr *E) {
15576 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15577 "Invalid Expr argument to DoMarkVarDeclReferenced");
15578 Var->setReferenced();
15579
15580 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15581
15582 bool OdrUseContext = isOdrUseContext(SemaRef);
15583 bool UsableInConstantExpr =
15584 Var->isUsableInConstantExpressions(SemaRef.Context);
15585 bool NeedDefinition =
15586 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15587
15588 VarTemplateSpecializationDecl *VarSpec =
15589 dyn_cast<VarTemplateSpecializationDecl>(Var);
15590 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15591 "Can't instantiate a partial template specialization.");
15592
15593 // If this might be a member specialization of a static data member, check
15594 // the specialization is visible. We already did the checks for variable
15595 // template specializations when we created them.
15596 if (NeedDefinition && TSK != TSK_Undeclared &&
15597 !isa<VarTemplateSpecializationDecl>(Var))
15598 SemaRef.checkSpecializationVisibility(Loc, Var);
15599
15600 // Perform implicit instantiation of static data members, static data member
15601 // templates of class templates, and variable template specializations. Delay
15602 // instantiations of variable templates, except for those that could be used
15603 // in a constant expression.
15604 if (NeedDefinition && isTemplateInstantiation(TSK)) {
15605 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15606 // instantiation declaration if a variable is usable in a constant
15607 // expression (among other cases).
15608 bool TryInstantiating =
15609 TSK == TSK_ImplicitInstantiation ||
15610 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15611
15612 if (TryInstantiating) {
15613 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15614 bool FirstInstantiation = PointOfInstantiation.isInvalid();
15615 if (FirstInstantiation) {
15616 PointOfInstantiation = Loc;
15617 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15618 }
15619
15620 bool InstantiationDependent = false;
15621 bool IsNonDependent =
15622 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15623 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15624 : true;
15625
15626 // Do not instantiate specializations that are still type-dependent.
15627 if (IsNonDependent) {
15628 if (UsableInConstantExpr) {
15629 // Do not defer instantiations of variables that could be used in a
15630 // constant expression.
15631 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15632 } else if (FirstInstantiation ||
15633 isa<VarTemplateSpecializationDecl>(Var)) {
15634 // FIXME: For a specialization of a variable template, we don't
15635 // distinguish between "declaration and type implicitly instantiated"
15636 // and "implicit instantiation of definition requested", so we have
15637 // no direct way to avoid enqueueing the pending instantiation
15638 // multiple times.
15639 SemaRef.PendingInstantiations
15640 .push_back(std::make_pair(Var, PointOfInstantiation));
15641 }
15642 }
15643 }
15644 }
15645
15646 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15647 // the requirements for appearing in a constant expression (5.19) and, if
15648 // it is an object, the lvalue-to-rvalue conversion (4.1)
15649 // is immediately applied." We check the first part here, and
15650 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15651 // Note that we use the C++11 definition everywhere because nothing in
15652 // C++03 depends on whether we get the C++03 version correct. The second
15653 // part does not apply to references, since they are not objects.
15654 if (OdrUseContext && E &&
15655 IsVariableAConstantExpression(Var, SemaRef.Context)) {
15656 // A reference initialized by a constant expression can never be
15657 // odr-used, so simply ignore it.
15658 if (!Var->getType()->isReferenceType() ||
15659 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15660 SemaRef.MaybeODRUseExprs.insert(E);
15661 } else if (OdrUseContext) {
15662 MarkVarDeclODRUsed(Var, Loc, SemaRef,
15663 /*MaxFunctionScopeIndex ptr*/ nullptr);
15664 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15665 // If this is a dependent context, we don't need to mark variables as
15666 // odr-used, but we may still need to track them for lambda capture.
15667 // FIXME: Do we also need to do this inside dependent typeid expressions
15668 // (which are modeled as unevaluated at this point)?
15669 const bool RefersToEnclosingScope =
15670 (SemaRef.CurContext != Var->getDeclContext() &&
15671 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15672 if (RefersToEnclosingScope) {
15673 LambdaScopeInfo *const LSI =
15674 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15675 if (LSI && (!LSI->CallOperator ||
15676 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15677 // If a variable could potentially be odr-used, defer marking it so
15678 // until we finish analyzing the full expression for any
15679 // lvalue-to-rvalue
15680 // or discarded value conversions that would obviate odr-use.
15681 // Add it to the list of potential captures that will be analyzed
15682 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15683 // unless the variable is a reference that was initialized by a constant
15684 // expression (this will never need to be captured or odr-used).
15685 assert(E && "Capture variable should be used in an expression.");
15686 if (!Var->getType()->isReferenceType() ||
15687 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15688 LSI->addPotentialCapture(E->IgnoreParens());
15689 }
15690 }
15691 }
15692 }
15693
15694 /// Mark a variable referenced, and check whether it is odr-used
15695 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
15696 /// used directly for normal expressions referring to VarDecl.
15697 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15698 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15699 }
15700
15701 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15702 Decl *D, Expr *E, bool MightBeOdrUse) {
15703 if (SemaRef.isInOpenMPDeclareTargetContext())
15704 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15705
15706 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15707 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15708 return;
15709 }
15710
15711 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15712
15713 // If this is a call to a method via a cast, also mark the method in the
15714 // derived class used in case codegen can devirtualize the call.
15715 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15716 if (!ME)
15717 return;
15718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15719 if (!MD)
15720 return;
15721 // Only attempt to devirtualize if this is truly a virtual call.
15722 bool IsVirtualCall = MD->isVirtual() &&
15723 ME->performsVirtualDispatch(SemaRef.getLangOpts());
15724 if (!IsVirtualCall)
15725 return;
15726
15727 // If it's possible to devirtualize the call, mark the called function
15728 // referenced.
15729 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15730 ME->getBase(), SemaRef.getLangOpts().AppleKext);
15731 if (DM)
15732 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15733 }
15734
15735 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15736 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15737 // TODO: update this with DR# once a defect report is filed.
15738 // C++11 defect. The address of a pure member should not be an ODR use, even
15739 // if it's a qualified reference.
15740 bool OdrUse = true;
15741 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15742 if (Method->isVirtual() &&
15743 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15744 OdrUse = false;
15745 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15746 }
15747
15748 /// Perform reference-marking and odr-use handling for a MemberExpr.
15749 void Sema::MarkMemberReferenced(MemberExpr *E) {
15750 // C++11 [basic.def.odr]p2:
15751 // A non-overloaded function whose name appears as a potentially-evaluated
15752 // expression or a member of a set of candidate functions, if selected by
15753 // overload resolution when referred to from a potentially-evaluated
15754 // expression, is odr-used, unless it is a pure virtual function and its
15755 // name is not explicitly qualified.
15756 bool MightBeOdrUse = true;
15757 if (E->performsVirtualDispatch(getLangOpts())) {
15758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15759 if (Method->isPure())
15760 MightBeOdrUse = false;
15761 }
15762 SourceLocation Loc =
15763 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15764 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15765 }
15766
15767 /// Perform marking for a reference to an arbitrary declaration. It
15768 /// marks the declaration referenced, and performs odr-use checking for
15769 /// functions and variables. This method should not be used when building a
15770 /// normal expression which refers to a variable.
15771 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15772 bool MightBeOdrUse) {
15773 if (MightBeOdrUse) {
15774 if (auto *VD = dyn_cast<VarDecl>(D)) {
15775 MarkVariableReferenced(Loc, VD);
15776 return;
15777 }
15778 }
15779 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15780 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15781 return;
15782 }
15783 D->setReferenced();
15784 }
15785
15786 namespace {
15787 // Mark all of the declarations used by a type as referenced.
15788 // FIXME: Not fully implemented yet! We need to have a better understanding
15789 // of when we're entering a context we should not recurse into.
15790 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15791 // TreeTransforms rebuilding the type in a new context. Rather than
15792 // duplicating the TreeTransform logic, we should consider reusing it here.
15793 // Currently that causes problems when rebuilding LambdaExprs.
15794 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15795 Sema &S;
15796 SourceLocation Loc;
15797
15798 public:
15799 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15800
15801 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15802
15803 bool TraverseTemplateArgument(const TemplateArgument &Arg);
15804 };
15805 }
15806
15807 bool MarkReferencedDecls::TraverseTemplateArgument(
15808 const TemplateArgument &Arg) {
15809 {
15810 // A non-type template argument is a constant-evaluated context.
15811 EnterExpressionEvaluationContext Evaluated(
15812 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15813 if (Arg.getKind() == TemplateArgument::Declaration) {
15814 if (Decl *D = Arg.getAsDecl())
15815 S.MarkAnyDeclReferenced(Loc, D, true);
15816 } else if (Arg.getKind() == TemplateArgument::Expression) {
15817 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15818 }
15819 }
15820
15821 return Inherited::TraverseTemplateArgument(Arg);
15822 }
15823
15824 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15825 MarkReferencedDecls Marker(*this, Loc);
15826 Marker.TraverseType(T);
15827 }
15828
15829 namespace {
15830 /// Helper class that marks all of the declarations referenced by
15831 /// potentially-evaluated subexpressions as "referenced".
15832 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15833 Sema &S;
15834 bool SkipLocalVariables;
15835
15836 public:
15837 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15838
15839 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15840 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15841
15842 void VisitDeclRefExpr(DeclRefExpr *E) {
15843 // If we were asked not to visit local variables, don't.
15844 if (SkipLocalVariables) {
15845 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15846 if (VD->hasLocalStorage())
15847 return;
15848 }
15849
15850 S.MarkDeclRefReferenced(E);
15851 }
15852
15853 void VisitMemberExpr(MemberExpr *E) {
15854 S.MarkMemberReferenced(E);
15855 Inherited::VisitMemberExpr(E);
15856 }
15857
15858 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15859 S.MarkFunctionReferenced(
15860 E->getBeginLoc(),
15861 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15862 Visit(E->getSubExpr());
15863 }
15864
15865 void VisitCXXNewExpr(CXXNewExpr *E) {
15866 if (E->getOperatorNew())
15867 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15868 if (E->getOperatorDelete())
15869 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15870 Inherited::VisitCXXNewExpr(E);
15871 }
15872
15873 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15874 if (E->getOperatorDelete())
15875 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15876 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15877 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15878 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15879 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15880 }
15881
15882 Inherited::VisitCXXDeleteExpr(E);
15883 }
15884
15885 void VisitCXXConstructExpr(CXXConstructExpr *E) {
15886 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15887 Inherited::VisitCXXConstructExpr(E);
15888 }
15889
15890 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15891 Visit(E->getExpr());
15892 }
15893
15894 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15895 Inherited::VisitImplicitCastExpr(E);
15896
15897 if (E->getCastKind() == CK_LValueToRValue)
15898 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15899 }
15900 };
15901 }
15902
15903 /// Mark any declarations that appear within this expression or any
15904 /// potentially-evaluated subexpressions as "referenced".
15905 ///
15906 /// \param SkipLocalVariables If true, don't mark local variables as
15907 /// 'referenced'.
15908 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15909 bool SkipLocalVariables) {
15910 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15911 }
15912
15913 /// Emit a diagnostic that describes an effect on the run-time behavior
15914 /// of the program being compiled.
15915 ///
15916 /// This routine emits the given diagnostic when the code currently being
15917 /// type-checked is "potentially evaluated", meaning that there is a
15918 /// possibility that the code will actually be executable. Code in sizeof()
15919 /// expressions, code used only during overload resolution, etc., are not
15920 /// potentially evaluated. This routine will suppress such diagnostics or,
15921 /// in the absolutely nutty case of potentially potentially evaluated
15922 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15923 /// later.
15924 ///
15925 /// This routine should be used for all diagnostics that describe the run-time
15926 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15927 /// Failure to do so will likely result in spurious diagnostics or failures
15928 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15929 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15930 const PartialDiagnostic &PD) {
15931 switch (ExprEvalContexts.back().Context) {
15932 case ExpressionEvaluationContext::Unevaluated:
15933 case ExpressionEvaluationContext::UnevaluatedList:
15934 case ExpressionEvaluationContext::UnevaluatedAbstract:
15935 case ExpressionEvaluationContext::DiscardedStatement:
15936 // The argument will never be evaluated, so don't complain.
15937 break;
15938
15939 case ExpressionEvaluationContext::ConstantEvaluated:
15940 // Relevant diagnostics should be produced by constant evaluation.
15941 break;
15942
15943 case ExpressionEvaluationContext::PotentiallyEvaluated:
15944 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15945 if (Statement && getCurFunctionOrMethodDecl()) {
15946 FunctionScopes.back()->PossiblyUnreachableDiags.
15947 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15948 return true;
15949 }
15950
15951 // The initializer of a constexpr variable or of the first declaration of a
15952 // static data member is not syntactically a constant evaluated constant,
15953 // but nonetheless is always required to be a constant expression, so we
15954 // can skip diagnosing.
15955 // FIXME: Using the mangling context here is a hack.
15956 if (auto *VD = dyn_cast_or_null<VarDecl>(
15957 ExprEvalContexts.back().ManglingContextDecl)) {
15958 if (VD->isConstexpr() ||
15959 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15960 break;
15961 // FIXME: For any other kind of variable, we should build a CFG for its
15962 // initializer and check whether the context in question is reachable.
15963 }
15964
15965 Diag(Loc, PD);
15966 return true;
15967 }
15968
15969 return false;
15970 }
15971
15972 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15973 CallExpr *CE, FunctionDecl *FD) {
15974 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15975 return false;
15976
15977 // If we're inside a decltype's expression, don't check for a valid return
15978 // type or construct temporaries until we know whether this is the last call.
15979 if (ExprEvalContexts.back().ExprContext ==
15980 ExpressionEvaluationContextRecord::EK_Decltype) {
15981 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15982 return false;
15983 }
15984
15985 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15986 FunctionDecl *FD;
15987 CallExpr *CE;
15988
15989 public:
15990 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15991 : FD(FD), CE(CE) { }
15992
15993 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15994 if (!FD) {
15995 S.Diag(Loc, diag::err_call_incomplete_return)
15996 << T << CE->getSourceRange();
15997 return;
15998 }
15999
16000 S.Diag(Loc, diag::err_call_function_incomplete_return)
16001 << CE->getSourceRange() << FD->getDeclName() << T;
16002 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16003 << FD->getDeclName();
16004 }
16005 } Diagnoser(FD, CE);
16006
16007 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16008 return true;
16009
16010 return false;
16011 }
16012
16013 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16014 // will prevent this condition from triggering, which is what we want.
16015 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16016 SourceLocation Loc;
16017
16018 unsigned diagnostic = diag::warn_condition_is_assignment;
16019 bool IsOrAssign = false;
16020
16021 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16022 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16023 return;
16024
16025 IsOrAssign = Op->getOpcode() == BO_OrAssign;
16026
16027 // Greylist some idioms by putting them into a warning subcategory.
16028 if (ObjCMessageExpr *ME
16029 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16030 Selector Sel = ME->getSelector();
16031
16032 // self = [<foo> init...]
16033 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16034 diagnostic = diag::warn_condition_is_idiomatic_assignment;
16035
16036 // <foo> = [<bar> nextObject]
16037 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16038 diagnostic = diag::warn_condition_is_idiomatic_assignment;
16039 }
16040
16041 Loc = Op->getOperatorLoc();
16042 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16043 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16044 return;
16045
16046 IsOrAssign = Op->getOperator() == OO_PipeEqual;
16047 Loc = Op->getOperatorLoc();
16048 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16049 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16050 else {
16051 // Not an assignment.
16052 return;
16053 }
16054
16055 Diag(Loc, diagnostic) << E->getSourceRange();
16056
16057 SourceLocation Open = E->getBeginLoc();
16058 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16059 Diag(Loc, diag::note_condition_assign_silence)
16060 << FixItHint::CreateInsertion(Open, "(")
16061 << FixItHint::CreateInsertion(Close, ")");
16062
16063 if (IsOrAssign)
16064 Diag(Loc, diag::note_condition_or_assign_to_comparison)
16065 << FixItHint::CreateReplacement(Loc, "!=");
16066 else
16067 Diag(Loc, diag::note_condition_assign_to_comparison)
16068 << FixItHint::CreateReplacement(Loc, "==");
16069 }
16070
16071 /// Redundant parentheses over an equality comparison can indicate
16072 /// that the user intended an assignment used as condition.
16073 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16074 // Don't warn if the parens came from a macro.
16075 SourceLocation parenLoc = ParenE->getBeginLoc();
16076 if (parenLoc.isInvalid() || parenLoc.isMacroID())
16077 return;
16078 // Don't warn for dependent expressions.
16079 if (ParenE->isTypeDependent())
16080 return;
16081
16082 Expr *E = ParenE->IgnoreParens();
16083
16084 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16085 if (opE->getOpcode() == BO_EQ &&
16086 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16087 == Expr::MLV_Valid) {
16088 SourceLocation Loc = opE->getOperatorLoc();
16089
16090 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16091 SourceRange ParenERange = ParenE->getSourceRange();
16092 Diag(Loc, diag::note_equality_comparison_silence)
16093 << FixItHint::CreateRemoval(ParenERange.getBegin())
16094 << FixItHint::CreateRemoval(ParenERange.getEnd());
16095 Diag(Loc, diag::note_equality_comparison_to_assign)
16096 << FixItHint::CreateReplacement(Loc, "=");
16097 }
16098 }
16099
16100 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16101 bool IsConstexpr) {
16102 DiagnoseAssignmentAsCondition(E);
16103 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16104 DiagnoseEqualityWithExtraParens(parenE);
16105
16106 ExprResult result = CheckPlaceholderExpr(E);
16107 if (result.isInvalid()) return ExprError();
16108 E = result.get();
16109
16110 if (!E->isTypeDependent()) {
16111 if (getLangOpts().CPlusPlus)
16112 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16113
16114 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16115 if (ERes.isInvalid())
16116 return ExprError();
16117 E = ERes.get();
16118
16119 QualType T = E->getType();
16120 if (!T->isScalarType()) { // C99 6.8.4.1p1
16121 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16122 << T << E->getSourceRange();
16123 return ExprError();
16124 }
16125 CheckBoolLikeConversion(E, Loc);
16126 }
16127
16128 return E;
16129 }
16130
16131 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16132 Expr *SubExpr, ConditionKind CK) {
16133 // Empty conditions are valid in for-statements.
16134 if (!SubExpr)
16135 return ConditionResult();
16136
16137 ExprResult Cond;
16138 switch (CK) {
16139 case ConditionKind::Boolean:
16140 Cond = CheckBooleanCondition(Loc, SubExpr);
16141 break;
16142
16143 case ConditionKind::ConstexprIf:
16144 Cond = CheckBooleanCondition(Loc, SubExpr, true);
16145 break;
16146
16147 case ConditionKind::Switch:
16148 Cond = CheckSwitchCondition(Loc, SubExpr);
16149 break;
16150 }
16151 if (Cond.isInvalid())
16152 return ConditionError();
16153
16154 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16155 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16156 if (!FullExpr.get())
16157 return ConditionError();
16158
16159 return ConditionResult(*this, nullptr, FullExpr,
16160 CK == ConditionKind::ConstexprIf);
16161 }
16162
16163 namespace {
16164 /// A visitor for rebuilding a call to an __unknown_any expression
16165 /// to have an appropriate type.
16166 struct RebuildUnknownAnyFunction
16167 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16168
16169 Sema &S;
16170
16171 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16172
16173 ExprResult VisitStmt(Stmt *S) {
16174 llvm_unreachable("unexpected statement!");
16175 }
16176
16177 ExprResult VisitExpr(Expr *E) {
16178 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16179 << E->getSourceRange();
16180 return ExprError();
16181 }
16182
16183 /// Rebuild an expression which simply semantically wraps another
16184 /// expression which it shares the type and value kind of.
16185 template <class T> ExprResult rebuildSugarExpr(T *E) {
16186 ExprResult SubResult = Visit(E->getSubExpr());
16187 if (SubResult.isInvalid()) return ExprError();
16188
16189 Expr *SubExpr = SubResult.get();
16190 E->setSubExpr(SubExpr);
16191 E->setType(SubExpr->getType());
16192 E->setValueKind(SubExpr->getValueKind());
16193 assert(E->getObjectKind() == OK_Ordinary);
16194 return E;
16195 }
16196
16197 ExprResult VisitParenExpr(ParenExpr *E) {
16198 return rebuildSugarExpr(E);
16199 }
16200
16201 ExprResult VisitUnaryExtension(UnaryOperator *E) {
16202 return rebuildSugarExpr(E);
16203 }
16204
16205 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16206 ExprResult SubResult = Visit(E->getSubExpr());
16207 if (SubResult.isInvalid()) return ExprError();
16208
16209 Expr *SubExpr = SubResult.get();
16210 E->setSubExpr(SubExpr);
16211 E->setType(S.Context.getPointerType(SubExpr->getType()));
16212 assert(E->getValueKind() == VK_RValue);
16213 assert(E->getObjectKind() == OK_Ordinary);
16214 return E;
16215 }
16216
16217 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16218 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16219
16220 E->setType(VD->getType());
16221
16222 assert(E->getValueKind() == VK_RValue);
16223 if (S.getLangOpts().CPlusPlus &&
16224 !(isa<CXXMethodDecl>(VD) &&
16225 cast<CXXMethodDecl>(VD)->isInstance()))
16226 E->setValueKind(VK_LValue);
16227
16228 return E;
16229 }
16230
16231 ExprResult VisitMemberExpr(MemberExpr *E) {
16232 return resolveDecl(E, E->getMemberDecl());
16233 }
16234
16235 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16236 return resolveDecl(E, E->getDecl());
16237 }
16238 };
16239 }
16240
16241 /// Given a function expression of unknown-any type, try to rebuild it
16242 /// to have a function type.
16243 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16244 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16245 if (Result.isInvalid()) return ExprError();
16246 return S.DefaultFunctionArrayConversion(Result.get());
16247 }
16248
16249 namespace {
16250 /// A visitor for rebuilding an expression of type __unknown_anytype
16251 /// into one which resolves the type directly on the referring
16252 /// expression. Strict preservation of the original source
16253 /// structure is not a goal.
16254 struct RebuildUnknownAnyExpr
16255 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16256
16257 Sema &S;
16258
16259 /// The current destination type.
16260 QualType DestType;
16261
16262 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16263 : S(S), DestType(CastType) {}
16264
16265 ExprResult VisitStmt(Stmt *S) {
16266 llvm_unreachable("unexpected statement!");
16267 }
16268
16269 ExprResult VisitExpr(Expr *E) {
16270 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16271 << E->getSourceRange();
16272 return ExprError();
16273 }
16274
16275 ExprResult VisitCallExpr(CallExpr *E);
16276 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16277
16278 /// Rebuild an expression which simply semantically wraps another
16279 /// expression which it shares the type and value kind of.
16280 template <class T> ExprResult rebuildSugarExpr(T *E) {
16281 ExprResult SubResult = Visit(E->getSubExpr());
16282 if (SubResult.isInvalid()) return ExprError();
16283 Expr *SubExpr = SubResult.get();
16284 E->setSubExpr(SubExpr);
16285 E->setType(SubExpr->getType());
16286 E->setValueKind(SubExpr->getValueKind());
16287 assert(E->getObjectKind() == OK_Ordinary);
16288 return E;
16289 }
16290
16291 ExprResult VisitParenExpr(ParenExpr *E) {
16292 return rebuildSugarExpr(E);
16293 }
16294
16295 ExprResult VisitUnaryExtension(UnaryOperator *E) {
16296 return rebuildSugarExpr(E);
16297 }
16298
16299 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16300 const PointerType *Ptr = DestType->getAs<PointerType>();
16301 if (!Ptr) {
16302 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16303 << E->getSourceRange();
16304 return ExprError();
16305 }
16306
16307 if (isa<CallExpr>(E->getSubExpr())) {
16308 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16309 << E->getSourceRange();
16310 return ExprError();
16311 }
16312
16313 assert(E->getValueKind() == VK_RValue);
16314 assert(E->getObjectKind() == OK_Ordinary);
16315 E->setType(DestType);
16316
16317 // Build the sub-expression as if it were an object of the pointee type.
16318 DestType = Ptr->getPointeeType();
16319 ExprResult SubResult = Visit(E->getSubExpr());
16320 if (SubResult.isInvalid()) return ExprError();
16321 E->setSubExpr(SubResult.get());
16322 return E;
16323 }
16324
16325 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16326
16327 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16328
16329 ExprResult VisitMemberExpr(MemberExpr *E) {
16330 return resolveDecl(E, E->getMemberDecl());
16331 }
16332
16333 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16334 return resolveDecl(E, E->getDecl());
16335 }
16336 };
16337 }
16338
16339 /// Rebuilds a call expression which yielded __unknown_anytype.
16340 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16341 Expr *CalleeExpr = E->getCallee();
16342
16343 enum FnKind {
16344 FK_MemberFunction,
16345 FK_FunctionPointer,
16346 FK_BlockPointer
16347 };
16348
16349 FnKind Kind;
16350 QualType CalleeType = CalleeExpr->getType();
16351 if (CalleeType == S.Context.BoundMemberTy) {
16352 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16353 Kind = FK_MemberFunction;
16354 CalleeType = Expr::findBoundMemberType(CalleeExpr);
16355 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16356 CalleeType = Ptr->getPointeeType();
16357 Kind = FK_FunctionPointer;
16358 } else {
16359 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16360 Kind = FK_BlockPointer;
16361 }
16362 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16363
16364 // Verify that this is a legal result type of a function.
16365 if (DestType->isArrayType() || DestType->isFunctionType()) {
16366 unsigned diagID = diag::err_func_returning_array_function;
16367 if (Kind == FK_BlockPointer)
16368 diagID = diag::err_block_returning_array_function;
16369
16370 S.Diag(E->getExprLoc(), diagID)
16371 << DestType->isFunctionType() << DestType;
16372 return ExprError();
16373 }
16374
16375 // Otherwise, go ahead and set DestType as the call's result.
16376 E->setType(DestType.getNonLValueExprType(S.Context));
16377 E->setValueKind(Expr::getValueKindForType(DestType));
16378 assert(E->getObjectKind() == OK_Ordinary);
16379
16380 // Rebuild the function type, replacing the result type with DestType.
16381 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16382 if (Proto) {
16383 // __unknown_anytype(...) is a special case used by the debugger when
16384 // it has no idea what a function's signature is.
16385 //
16386 // We want to build this call essentially under the K&R
16387 // unprototyped rules, but making a FunctionNoProtoType in C++
16388 // would foul up all sorts of assumptions. However, we cannot
16389 // simply pass all arguments as variadic arguments, nor can we
16390 // portably just call the function under a non-variadic type; see
16391 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16392 // However, it turns out that in practice it is generally safe to
16393 // call a function declared as "A foo(B,C,D);" under the prototype
16394 // "A foo(B,C,D,...);". The only known exception is with the
16395 // Windows ABI, where any variadic function is implicitly cdecl
16396 // regardless of its normal CC. Therefore we change the parameter
16397 // types to match the types of the arguments.
16398 //
16399 // This is a hack, but it is far superior to moving the
16400 // corresponding target-specific code from IR-gen to Sema/AST.
16401
16402 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16403 SmallVector<QualType, 8> ArgTypes;
16404 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16405 ArgTypes.reserve(E->getNumArgs());
16406 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16407 Expr *Arg = E->getArg(i);
16408 QualType ArgType = Arg->getType();
16409 if (E->isLValue()) {
16410 ArgType = S.Context.getLValueReferenceType(ArgType);
16411 } else if (E->isXValue()) {
16412 ArgType = S.Context.getRValueReferenceType(ArgType);
16413 }
16414 ArgTypes.push_back(ArgType);
16415 }
16416 ParamTypes = ArgTypes;
16417 }
16418 DestType = S.Context.getFunctionType(DestType, ParamTypes,
16419 Proto->getExtProtoInfo());
16420 } else {
16421 DestType = S.Context.getFunctionNoProtoType(DestType,
16422 FnType->getExtInfo());
16423 }
16424
16425 // Rebuild the appropriate pointer-to-function type.
16426 switch (Kind) {
16427 case FK_MemberFunction:
16428 // Nothing to do.
16429 break;
16430
16431 case FK_FunctionPointer:
16432 DestType = S.Context.getPointerType(DestType);
16433 break;
16434
16435 case FK_BlockPointer:
16436 DestType = S.Context.getBlockPointerType(DestType);
16437 break;
16438 }
16439
16440 // Finally, we can recurse.
16441 ExprResult CalleeResult = Visit(CalleeExpr);
16442 if (!CalleeResult.isUsable()) return ExprError();
16443 E->setCallee(CalleeResult.get());
16444
16445 // Bind a temporary if necessary.
16446 return S.MaybeBindToTemporary(E);
16447 }
16448
16449 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16450 // Verify that this is a legal result type of a call.
16451 if (DestType->isArrayType() || DestType->isFunctionType()) {
16452 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16453 << DestType->isFunctionType() << DestType;
16454 return ExprError();
16455 }
16456
16457 // Rewrite the method result type if available.
16458 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16459 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16460 Method->setReturnType(DestType);
16461 }
16462
16463 // Change the type of the message.
16464 E->setType(DestType.getNonReferenceType());
16465 E->setValueKind(Expr::getValueKindForType(DestType));
16466
16467 return S.MaybeBindToTemporary(E);
16468 }
16469
16470 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16471 // The only case we should ever see here is a function-to-pointer decay.
16472 if (E->getCastKind() == CK_FunctionToPointerDecay) {
16473 assert(E->getValueKind() == VK_RValue);
16474 assert(E->getObjectKind() == OK_Ordinary);
16475
16476 E->setType(DestType);
16477
16478 // Rebuild the sub-expression as the pointee (function) type.
16479 DestType = DestType->castAs<PointerType>()->getPointeeType();
16480
16481 ExprResult Result = Visit(E->getSubExpr());
16482 if (!Result.isUsable()) return ExprError();
16483
16484 E->setSubExpr(Result.get());
16485 return E;
16486 } else if (E->getCastKind() == CK_LValueToRValue) {
16487 assert(E->getValueKind() == VK_RValue);
16488 assert(E->getObjectKind() == OK_Ordinary);
16489
16490 assert(isa<BlockPointerType>(E->getType()));
16491
16492 E->setType(DestType);
16493
16494 // The sub-expression has to be a lvalue reference, so rebuild it as such.
16495 DestType = S.Context.getLValueReferenceType(DestType);
16496
16497 ExprResult Result = Visit(E->getSubExpr());
16498 if (!Result.isUsable()) return ExprError();
16499
16500 E->setSubExpr(Result.get());
16501 return E;
16502 } else {
16503 llvm_unreachable("Unhandled cast type!");
16504 }
16505 }
16506
16507 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16508 ExprValueKind ValueKind = VK_LValue;
16509 QualType Type = DestType;
16510
16511 // We know how to make this work for certain kinds of decls:
16512
16513 // - functions
16514 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16515 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16516 DestType = Ptr->getPointeeType();
16517 ExprResult Result = resolveDecl(E, VD);
16518 if (Result.isInvalid()) return ExprError();
16519 return S.ImpCastExprToType(Result.get(), Type,
16520 CK_FunctionToPointerDecay, VK_RValue);
16521 }
16522
16523 if (!Type->isFunctionType()) {
16524 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16525 << VD << E->getSourceRange();
16526 return ExprError();
16527 }
16528 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16529 // We must match the FunctionDecl's type to the hack introduced in
16530 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16531 // type. See the lengthy commentary in that routine.
16532 QualType FDT = FD->getType();
16533 const FunctionType *FnType = FDT->castAs<FunctionType>();
16534 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16536 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16537 SourceLocation Loc = FD->getLocation();
16538 FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16539 FD->getDeclContext(),
16540 Loc, Loc, FD->getNameInfo().getName(),
16541 DestType, FD->getTypeSourceInfo(),
16542 SC_None, false/*isInlineSpecified*/,
16543 FD->hasPrototype(),
16544 false/*isConstexprSpecified*/);
16545
16546 if (FD->getQualifier())
16547 NewFD->setQualifierInfo(FD->getQualifierLoc());
16548
16549 SmallVector<ParmVarDecl*, 16> Params;
16550 for (const auto &AI : FT->param_types()) {
16551 ParmVarDecl *Param =
16552 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16553 Param->setScopeInfo(0, Params.size());
16554 Params.push_back(Param);
16555 }
16556 NewFD->setParams(Params);
16557 DRE->setDecl(NewFD);
16558 VD = DRE->getDecl();
16559 }
16560 }
16561
16562 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16563 if (MD->isInstance()) {
16564 ValueKind = VK_RValue;
16565 Type = S.Context.BoundMemberTy;
16566 }
16567
16568 // Function references aren't l-values in C.
16569 if (!S.getLangOpts().CPlusPlus)
16570 ValueKind = VK_RValue;
16571
16572 // - variables
16573 } else if (isa<VarDecl>(VD)) {
16574 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16575 Type = RefTy->getPointeeType();
16576 } else if (Type->isFunctionType()) {
16577 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16578 << VD << E->getSourceRange();
16579 return ExprError();
16580 }
16581
16582 // - nothing else
16583 } else {
16584 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16585 << VD << E->getSourceRange();
16586 return ExprError();
16587 }
16588
16589 // Modifying the declaration like this is friendly to IR-gen but
16590 // also really dangerous.
16591 VD->setType(DestType);
16592 E->setType(Type);
16593 E->setValueKind(ValueKind);
16594 return E;
16595 }
16596
16597 /// Check a cast of an unknown-any type. We intentionally only
16598 /// trigger this for C-style casts.
16599 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16600 Expr *CastExpr, CastKind &CastKind,
16601 ExprValueKind &VK, CXXCastPath &Path) {
16602 // The type we're casting to must be either void or complete.
16603 if (!CastType->isVoidType() &&
16604 RequireCompleteType(TypeRange.getBegin(), CastType,
16605 diag::err_typecheck_cast_to_incomplete))
16606 return ExprError();
16607
16608 // Rewrite the casted expression from scratch.
16609 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16610 if (!result.isUsable()) return ExprError();
16611
16612 CastExpr = result.get();
16613 VK = CastExpr->getValueKind();
16614 CastKind = CK_NoOp;
16615
16616 return CastExpr;
16617 }
16618
16619 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16620 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16621 }
16622
16623 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16624 Expr *arg, QualType &paramType) {
16625 // If the syntactic form of the argument is not an explicit cast of
16626 // any sort, just do default argument promotion.
16627 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16628 if (!castArg) {
16629 ExprResult result = DefaultArgumentPromotion(arg);
16630 if (result.isInvalid()) return ExprError();
16631 paramType = result.get()->getType();
16632 return result;
16633 }
16634
16635 // Otherwise, use the type that was written in the explicit cast.
16636 assert(!arg->hasPlaceholderType());
16637 paramType = castArg->getTypeAsWritten();
16638
16639 // Copy-initialize a parameter of that type.
16640 InitializedEntity entity =
16641 InitializedEntity::InitializeParameter(Context, paramType,
16642 /*consumed*/ false);
16643 return PerformCopyInitialization(entity, callLoc, arg);
16644 }
16645
16646 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16647 Expr *orig = E;
16648 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16649 while (true) {
16650 E = E->IgnoreParenImpCasts();
16651 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16652 E = call->getCallee();
16653 diagID = diag::err_uncasted_call_of_unknown_any;
16654 } else {
16655 break;
16656 }
16657 }
16658
16659 SourceLocation loc;
16660 NamedDecl *d;
16661 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16662 loc = ref->getLocation();
16663 d = ref->getDecl();
16664 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16665 loc = mem->getMemberLoc();
16666 d = mem->getMemberDecl();
16667 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16668 diagID = diag::err_uncasted_call_of_unknown_any;
16669 loc = msg->getSelectorStartLoc();
16670 d = msg->getMethodDecl();
16671 if (!d) {
16672 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16673 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16674 << orig->getSourceRange();
16675 return ExprError();
16676 }
16677 } else {
16678 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16679 << E->getSourceRange();
16680 return ExprError();
16681 }
16682
16683 S.Diag(loc, diagID) << d << orig->getSourceRange();
16684
16685 // Never recoverable.
16686 return ExprError();
16687 }
16688
16689 /// Check for operands with placeholder types and complain if found.
16690 /// Returns ExprError() if there was an error and no recovery was possible.
16691 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16692 if (!getLangOpts().CPlusPlus) {
16693 // C cannot handle TypoExpr nodes on either side of a binop because it
16694 // doesn't handle dependent types properly, so make sure any TypoExprs have
16695 // been dealt with before checking the operands.
16696 ExprResult Result = CorrectDelayedTyposInExpr(E);
16697 if (!Result.isUsable()) return ExprError();
16698 E = Result.get();
16699 }
16700
16701 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16702 if (!placeholderType) return E;
16703
16704 switch (placeholderType->getKind()) {
16705
16706 // Overloaded expressions.
16707 case BuiltinType::Overload: {
16708 // Try to resolve a single function template specialization.
16709 // This is obligatory.
16710 ExprResult Result = E;
16711 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16712 return Result;
16713
16714 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16715 // leaves Result unchanged on failure.
16716 Result = E;
16717 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16718 return Result;
16719
16720 // If that failed, try to recover with a call.
16721 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16722 /*complain*/ true);
16723 return Result;
16724 }
16725
16726 // Bound member functions.
16727 case BuiltinType::BoundMember: {
16728 ExprResult result = E;
16729 const Expr *BME = E->IgnoreParens();
16730 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16731 // Try to give a nicer diagnostic if it is a bound member that we recognize.
16732 if (isa<CXXPseudoDestructorExpr>(BME)) {
16733 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16734 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16735 if (ME->getMemberNameInfo().getName().getNameKind() ==
16736 DeclarationName::CXXDestructorName)
16737 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16738 }
16739 tryToRecoverWithCall(result, PD,
16740 /*complain*/ true);
16741 return result;
16742 }
16743
16744 // ARC unbridged casts.
16745 case BuiltinType::ARCUnbridgedCast: {
16746 Expr *realCast = stripARCUnbridgedCast(E);
16747 diagnoseARCUnbridgedCast(realCast);
16748 return realCast;
16749 }
16750
16751 // Expressions of unknown type.
16752 case BuiltinType::UnknownAny:
16753 return diagnoseUnknownAnyExpr(*this, E);
16754
16755 // Pseudo-objects.
16756 case BuiltinType::PseudoObject:
16757 return checkPseudoObjectRValue(E);
16758
16759 case BuiltinType::BuiltinFn: {
16760 // Accept __noop without parens by implicitly converting it to a call expr.
16761 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16762 if (DRE) {
16763 auto *FD = cast<FunctionDecl>(DRE->getDecl());
16764 if (FD->getBuiltinID() == Builtin::BI__noop) {
16765 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16766 CK_BuiltinFnToFnPtr)
16767 .get();
16768 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16769 VK_RValue, SourceLocation());
16770 }
16771 }
16772
16773 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16774 return ExprError();
16775 }
16776
16777 // Expressions of unknown type.
16778 case BuiltinType::OMPArraySection:
16779 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16780 return ExprError();
16781
16782 // Everything else should be impossible.
16783 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16784 case BuiltinType::Id:
16785 #include "clang/Basic/OpenCLImageTypes.def"
16786 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16787 case BuiltinType::Id:
16788 #include "clang/Basic/OpenCLExtensionTypes.def"
16789 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16790 #define PLACEHOLDER_TYPE(Id, SingletonId)
16791 #include "clang/AST/BuiltinTypes.def"
16792 break;
16793 }
16794
16795 llvm_unreachable("invalid placeholder type!");
16796 }
16797
16798 bool Sema::CheckCaseExpression(Expr *E) {
16799 if (E->isTypeDependent())
16800 return true;
16801 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16802 return E->getType()->isIntegralOrEnumerationType();
16803 return false;
16804 }
16805
16806 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16807 ExprResult
16808 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16809 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16810 "Unknown Objective-C Boolean value!");
16811 QualType BoolT = Context.ObjCBuiltinBoolTy;
16812 if (!Context.getBOOLDecl()) {
16813 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16814 Sema::LookupOrdinaryName);
16815 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16816 NamedDecl *ND = Result.getFoundDecl();
16817 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16818 Context.setBOOLDecl(TD);
16819 }
16820 }
16821 if (Context.getBOOLDecl())
16822 BoolT = Context.getBOOLType();
16823 return new (Context)
16824 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16825 }
16826
16827 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16828 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16829 SourceLocation RParen) {
16830
16831 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16832
16833 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16834 [&](const AvailabilitySpec &Spec) {
16835 return Spec.getPlatform() == Platform;
16836 });
16837
16838 VersionTuple Version;
16839 if (Spec != AvailSpecs.end())
16840 Version = Spec->getVersion();
16841
16842 // The use of `@available` in the enclosing function should be analyzed to
16843 // warn when it's used inappropriately (i.e. not if(@available)).
16844 if (getCurFunctionOrMethodDecl())
16845 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16846 else if (getCurBlock() || getCurLambda())
16847 getCurFunction()->HasPotentialAvailabilityViolations = true;
16848
16849 return new (Context)
16850 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16851 }
clang::Sema::TypeDiagnoser
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1510
diagnoseArithmeticOnFunctionPointer
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:8998
clang::OMF_finalize
Definition: IdentifierTable.h:629
clang::FullExpr::getSubExpr
const Expr * getSubExpr() const
Definition: Expr.h:890
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
clang::Expr::LV_IncompleteVoidType
Definition: Expr.h:257
clang::AR_Unavailable
Definition: DeclBase.h:77
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:1782
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:720
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:1530
clang::Builtin::ID
ID
Definition: Builtins.h:49
clang::ast_matchers::type
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchersInternal.cpp:592
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:12488
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:2652
clang::BlockExpr::getBlockDecl
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5191
clang::ObjCInterfaceDecl::hasDefinition
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1535
clang::QualType::isNonWeakInMRRWithObjCWeak
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2242
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:15908
clang::Sema::VariadicCallType
VariadicCallType
Definition: Sema.h:9462
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1583
clang::CharacterLiteral::Ascii
Definition: Expr.h:1395
clang::Sema::getCurrentThisType
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
Definition: SemaExprCXX.cpp:1061
clang::CanQual::withConst
QualType withConst() const
Retrieves a version of this type with const applied.
Definition: CanonicalType.h:162
clang::Sema::ActOnCondition
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:16131
clang::CXXTemporary::getDestructor
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1196
clang::ObjCMethodDecl::isClassMethod
bool isClassMethod() const
Definition: DeclObjC.h:430
isOverflowingIntegerType
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:12844
clang::ASTContext::LongLongTy
CanQualType LongLongTy
Definition: ASTContext.h:1025
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5296
clang::Decl::setImplicit
void setImplicit(bool I=true)
Definition: DeclBase.h:548
clang::MarkVarDeclODRUsed
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:70
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1738
isVariableAlreadyCapturedInScopeInfo
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:14828
clang::CompoundStmt::body_back
Stmt * body_back()
Definition: Stmt.h:1279
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:1630
clang::CallExpr::getArgs
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:2543
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:78
clang::Sema::ActOnCastExpr
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:6325
clang::LookupResult::isForRedeclaration
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:256
clang::TypoCorrection::getCorrectionRange
SourceRange getCorrectionRange() const
Definition: TypoCorrection.h:227
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:141
clang::TargetInfo::hasBuiltinMSVaList
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:759
clang::LangOptions::isSignedOverflowDefined
bool isSignedOverflowDefined() const
Definition: LangOptions.h:272
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:134
clang::UnqualifiedId::setKind
void setKind(UnqualifiedIdKind kind)
Definition: DeclSpec.h:1017
clang::Selector
Smart pointer class that efficiently represents Objective-C method names.
Definition: IdentifierTable.h:673
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1849
clang::BlockDecl::Capture
A class which contains all the information about a particular captured value.
Definition: Decl.h:3864
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:81
clang::Sema::PushExpressionEvaluationContext
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:14410
clang::if
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
clang::Type::STK_FixedPoint
Definition: Type.h:2071
OEK_Member
Definition: SemaExpr.cpp:11097
clang::EvaluatedExprVisitor
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
Definition: EvaluatedExprVisitor.h:112
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2550
clang::Sema::CheckLoopHintExpr
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3235
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:638
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:5777
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6304
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:6596
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:43
clang::ArraySubscriptExpr::getBase
Expr * getBase()
Definition: Expr.h:2355
clang::Sema::CheckAssignmentOperands
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType)
Definition: SemaExpr.cpp:11338
clang::ASTContext::areCommonBaseCompatible
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
Definition: ASTContext.cpp:8233
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:2101
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6345
clang::Sema::getExprRange
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:430
clang::Type::isMemberPointerType
bool isMemberPointerType() const
Definition: Type.h:6327
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2773
clang::ImplicitConversionKind
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter&#39;s...
Definition: Overload.h:79
checkBlockType
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:6989
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2376
clang::ASTContext::getFixedPointScale
unsigned char getFixedPointScale(QualType Ty) const
Definition: ASTContext.cpp:10398
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2553
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:3977
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:12086
clang::ObjCMethodDecl::getClassInterface
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1144
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2902
clang::LocalInstantiationScope
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:228
diagnoseArithmeticOnTwoFunctionPointers
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:8982
clang::ASTContext::getBuiltinVaListType
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1904
clang::Sema::ActOnConditionalOp
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:7454
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:389
clang::Sema::getFunctionLevelDeclContext
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1183
clang::Sema::ActOnIntegerConstant
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3197
clang::Expr::EvaluateKnownConstIntCheckOverflow
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Definition: ExprConstant.cpp:11061
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:1021
clang::APFixedPoint::getValue
llvm::APSInt getValue() const
Definition: FixedPoint.h:86
breakDownVectorType
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:6176
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:6252
clang::Sema::LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3055
clang::Sema::ActOnParenListExpr
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:6498
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:6583
diagnoseUnknownAnyExpr
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:16646
clang::LookupResult::setLookupName
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:246
addAsFieldToClosureType
static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, QualType FieldType, QualType DeclRefType, SourceLocation Loc, bool RefersToCapturedVariable)
Create a field within the lambda class for the variable being captured.
Definition: SemaExpr.cpp:15129
clang::ASTContext::getPointerDiffType
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Definition: ASTContext.cpp:5002
clang::TemplateIdAnnotation::TemplateNameLoc
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
Definition: ParsedTemplate.h:161
ConvertUTF8ToWideString
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3060
clang::Type::STK_FloatingComplex
Definition: Type.h:2070
clang::NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:219
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
Definition: ExprConstant.cpp:10951
clang::Type::isArithmeticType
bool isArithmeticType() const
Definition: Type.cpp:1952
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:2540
clang::isGenericLambdaCallOperatorSpecialization
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
clang::NullabilityKind
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:286
clang::BuiltinType::getKind
Kind getKind() const
Definition: Type.h:2418
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
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:505
clang::Type::isRealFloatingType
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
clang::sema::CapturingScopeInfo::ReturnType
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:650
clang::Sema::LookupMethodInObjectType
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
Definition: SemaExprObjC.cpp:1758
clang::sema::CapturingScopeInfo::isVLATypeCaptured
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:116
IsReadonlyMessage
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:10904
clang::QualType::DK_nontrivial_c_struct
Definition: Type.h:1145
clang::Expr::hasPlaceholderType
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:1934
Base
clang::Sema::ActOnArraySubscriptExpr
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4214
clang::TypedefDecl
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3018
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:51
clang::QualType::addConst
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:807
clang::Sema::BuildCXXDefaultArgExpr
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4773
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2094
clang::ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:114
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:87
diagnoseObjCLiteralComparison
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:9831
clang::StringLiteral::isAscii
bool isAscii() const
Definition: Expr.h:1685
clang::Expr::MLV_IncompleteType
Definition: Expr.h:276
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6369
clang::Sema::InvalidLogicalVectorOperands
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Definition: SemaExpr.cpp:8393
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:2767
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:11293
clang::Type::isSpecificPlaceholderType
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6531
clang::InitializedEntity::InitializeParameter
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Definition: Initialization.h:249
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1933
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:2967
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:2898
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
clang::Sema::CheckRemainderOperands
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:8923
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:608
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:6507
clang::Sema::ActOnBlockArguments
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:13533
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
DiagnoseRecursiveConstFields
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:11101
clang::FunctionProtoType::isVariadic
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4002
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:35
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:2086
clang::OverloadCandidateSet::CSK_Normal
Normal lookup.
Definition: Overload.h:841
clang::CXXNewExpr::getOperatorNew
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2033
clang::Type::isExtVectorType
bool isExtVectorType() const
Definition: Type.h:6385
clang::Expr::setType
void setType(QualType t)
Definition: Expr.h:129
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:7649
clang::Sema::AssignConvertType
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:9522
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:2828
isReferenceToNonConstCapture
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:10918
DeclTemplate.h
Defines the C++ template declaration subclasses.
clang::BinaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:3322
clang::Scope::BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it...
Definition: Scope.h:52
clang::Sema::TUScope
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:828
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:6790
clang::NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:205
CheckObjCTraitOperandConstraints
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3653
clang::Sema::DefaultArgumentPromotion
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:732
clang::sema::Capture::isCopyCapture
bool isCopyCapture() const
Definition: ScopeInfo.h:569
clang::ParenExpr
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1844
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:6245
clang::Sema::CheckVecStepExpr
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:3893
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:16619
clang::Sema::CreateBuiltinArraySubscriptExpr
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4487
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:2763
clang::IntegerLiteral
Definition: Expr.h:1308
clang::Sema::ActOnVAArg
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13785
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:2935
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1407
clang::CanQual::getUnqualifiedType
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Definition: CanonicalType.h:619
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:9590
clang::Type::isClkEventT
bool isClkEventT() const
Definition: Type.h:6458
clang::Sema::CheckSubtractionOperands
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9305
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1890
clang::Expr::MLV_ArrayTemporary
Definition: Expr.h:286
clang::CXXRecordDecl::isDerivedFrom
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Definition: CXXInheritance.cpp:92
clang::sema::CapturingScopeInfo::ImpCap_LambdaByref
Definition: ScopeInfo.h:625
CXXInheritance.h
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2812
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:2862
clang::ASTContext::getCorrespondingUnsignedType
QualType getCorrespondingUnsignedType(QualType T) const
Definition: ASTContext.cpp:9161
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:64
clang::Sema::getLocForEndOfToken
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
clang::CXXConstructExpr
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
clang::DeclarationNameInfo::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclarationName.h:806
clang::Expr::getValueKindForType
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:395
clang::ObjCRuntime::allowsPointerArithmetic
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:308
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:810
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:9689
clang::FunctionType::getNoReturnAttr
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:3621
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
clang::TemplateIdAnnotation::Kind
TemplateNameKind Kind
The kind of template that Template refers to.
Definition: ParsedTemplate.h:174
DeclObjC.h
clang::ASTContext::adjustStringLiteralBaseType
QualType adjustStringLiteralBaseType(QualType StrLTy) const
Definition: ASTContext.cpp:3811
clang::TypeSourceInfo
A container of type source information.
Definition: Decl.h:87
clang::FunctionDecl::getCallResultType
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2324
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:965
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:1785
clang::AutoTypeKeyword::Auto
auto
clang::FPOptions
Floating point control options.
Definition: LangOptions.h:307
clang::XRayInstrKind::Function
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
clang::MSPropertySubscriptExpr
MS property subscript expression.
Definition: ExprCXX.h:828
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:2720
clang::Sema::CheckVectorLogicalOperands
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10756
CheckForModifiableLvalue
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:11165
clang::VarDecl::getAnyInitializer
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1210
clang::DecayedTypeLoc
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1163
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:3362
clang::Sema::VerifyICEDiagnoser
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9977
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:71
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:6929
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2484
clang::LookupResult::clear
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:543
clang::Sema::CheckCXXDefaultArgExpr
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4652
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:4821
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:14615
clang::FunctionDecl::param_size
size_t param_size() const
Definition: Decl.h:2278
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:13071
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:4341
clang::Expr::isModifiableLvalueResult
isModifiableLvalueResult
Definition: Expr.h:269
clang::ASTContext::HalfTy
CanQualType HalfTy
Definition: ASTContext.h:1040
clang::Sema::ActOnGNUNullExpr
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:13901
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:2847
clang::InitializedEntity::InitializeTemporary
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
Definition: Initialization.h:319
clang::Type::getAsUnionType
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:540
Value
Value
Definition: UninitializedValues.cpp:102
clang::CharacterLiteral::UTF16
Definition: Expr.h:1398
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:13279
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:97
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:1884
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:6237
hasIsEqualMethod
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:9743
clang::TemplateArgumentListInfo::setRAngleLoc
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:575
clang::CXXConstructExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.cpp:508
clang::Sema::UseArgumentDependentLookup
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:2695
clang::EnterExpressionEvaluationContext
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10853
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:813
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
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:59
clang::ImplicitConversionSequence::isFailure
bool isFailure() const
Definition: Overload.h:606
clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:1012
clang::Expr::MLV_LValueCast
Definition: Expr.h:275
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:241
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
clang::ObjCIsaExpr
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC &#39;id&#39; type.
Definition: ExprObjC.h:1437
clang::Qualifiers::removeObjCLifetime
void removeObjCLifetime()
Definition: Type.h:332
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2302
clang::CompoundLiteralExpr
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2925
clang::FunctionProtoType::isParamConsumed
bool isParamConsumed(unsigned I) const
Definition: Type.h:4092
diagnoseFunctionPointerToVoidComparison
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:9720
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:3888
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6373
clang::SC_None
Definition: Specifiers.h:208
clang::DeclarationNameInfo::setCXXLiteralOperatorNameLoc
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
Definition: DeclarationName.h:780
clang::ASTContext::getFixedPointMax
APFixedPoint getFixedPointMax(QualType Ty) const
Definition: ASTContext.cpp:10496
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
clang::Type::isOverloadableType
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:6670
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:54
ConstMethod
Definition: SemaExpr.cpp:10967
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:3767
clang::ASTContext::ShortAccumTy
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
clang::Sema::getDeletedOrUnavailableSuffix
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD)
Retrieve the message suffix that should be added to a diagnostic complaining about the given function...
Definition: SemaExpr.cpp:327
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
clang::PredefinedExpr::FuncDName
Definition: Expr.h:1773
rewriteBuiltinFunctionDecl
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, const 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:5225
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:8495
clang::VarTemplateSpecializationDecl
Represents a variable template specialization, which refers to a variable template with a given set o...
Definition: DeclTemplate.h:2475
TreeTransform.h
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:432
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:290
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:92
clang::Expr::IgnoreImplicit
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
Definition: Expr.h:747
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:3040
clang::TypoCorrection::getCorrectionDeclAs
DeclClass * getCorrectionDeclAs() const
Definition: TypoCorrection.h:157
checkEnumComparison
static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
If two different enums are compared, raise a warning.
Definition: SemaExpr.cpp:9649
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:943
clang::Sema::ActOnStartStmtExpr
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:13193
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:542
clang::TypoCorrection::isOverloaded
bool isOverloaded() const
Definition: TypoCorrection.h:216
CheckAlignOfExpr
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:3836
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:177
clang::InitializationKind::CreateDirectList
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Definition: Initialization.h:608
clang::PredefinedExpr::Function
Definition: Expr.h:1771
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:13108
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:15263
clang::ExprWithCleanups
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3089
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:10976
clang::ConversionFixItGenerator::Hints
std::vector< FixItHint > Hints
The list of Hints generated so far.
Definition: SemaFixItUtils.h:42
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1550
clang::Sema::CheckComparisonCategoryType
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
Definition: SemaDeclCXX.cpp:9064
clang::Expr::LV_ClassTemporary
Definition: Expr.h:263
ExprCXX.h
Defines the clang::Expr interface and subclasses for C++ expressions.
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:90
clang::BinaryOperator::isAdditiveOp
bool isAdditiveOp() const
Definition: Expr.h:3364
clang::BinaryOperator::isEqualityOp
bool isEqualityOp() const
Definition: Expr.h:3375
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1952
diagnosePointerIncompatibility
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:9201
clang::Qualifiers
The collection of all-type qualifiers we support.
Definition: Type.h:141
GCCTypeClass::Bool
clang::Type::isVariableArrayType
bool isVariableArrayType() const
Definition: Type.h:6357
ContextKind
tok::TokenKind ContextKind
Definition: TokenAnnotator.cpp:1169
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:1930
clang::VarDecl::isARCPseudoStrong
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1360
clang::Sema::ActOnCallExpr
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5408
clang::Expr::isXValue
bool isXValue() const
Definition: Expr.h:251
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3202
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:15824
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:57
clang::LabelStmt
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1593
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:3162
checkObjCPointerTypesForAssignment
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:7738
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3593
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:6875
clang::TreeTransform
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
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:7139
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:349
clang::Expr::isOrdinaryOrBitFieldObject
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:416
clang::UnqualifiedId::TemplateId
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:986
clang::Sema::UsualUnaryConversions
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:683
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
clang::Sema::ActOnPostfixUnaryOp
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4172
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1148
clang::NamedDecl::getFormalLinkage
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:371
clang::FunctionProtoType::ExtProtoInfo::ExtInfo
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3768
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:58
clang::Sema::NSAPIObj
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:860
clang::Type::STK_MemberPointer
Definition: Type.h:2065
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1022
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:1197
clang::DeclaratorDecl::getOuterLocStart
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations. ...
Definition: Decl.cpp:1817
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:12232
clang::Sema::DiagnoseUnusedExprResult
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:199
ConstFunction
Definition: SemaExpr.cpp:10964
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:137
clang::ObjCObjectType
Represents a class type in Objective C.
Definition: Type.h:5538
clang::OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:132
clang::ComparisonCategoryType::PartialOrdering
clang::TemplateArgument::getAsExpr
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:330
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:7372
captureInCapturedRegion
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema &S)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:15068
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:237
clang::TypoCorrection::getCorrection
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
Definition: TypoCorrection.h:85
clang::Sema::inTemplateInstantiation
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7520
clang::ExprEmpty
ExprResult ExprEmpty()
Definition: Ownership.h:289
checkArithmeticOpPointerOperand
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:9033
llvm::Optional
Definition: LLVM.h:38
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3895
State
LineState State
Definition: UnwrappedLineFormatter.cpp:877
clang::Type::isObjCLifetimeType
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3941
clang::Expr::ClassifyLValue
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
Definition: ExprClassification.cpp:652
clang::ObjCMethodFamily
ObjCMethodFamily
A family of Objective-C methods.
Definition: IdentifierTable.h:611
clang::UETT_PreferredAlignOf
Used for GCC&#39;s __alignof.
Definition: TypeTraits.h:107
clang::FullExpr
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:877
clang::TemplateSpecializationType::anyDependentTemplateArguments
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3297
checkPointerTypesForAssignment
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
Definition: SemaExpr.cpp:7563
clang::Type::isCharType
bool isCharType() const
Definition: Type.cpp:1787
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:3784
clang::TypeLocBuilder::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Definition: TypeLocBuilder.h:104
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
clang::DeclarationName::getNameKind
NameKind getNameKind() const
Determine what kind of name this is.
Definition: DeclarationName.h:385
clang::Type::isObjCIdType
bool isObjCIdType() const
Definition: Type.h:6422
NCCK_Block
Definition: SemaExpr.cpp:10917
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2579
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:195
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:10151
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:1885
clang::CharacterLiteral::UTF32
Definition: Expr.h:1399
clang::ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:81
clang::ArrayType::Static
Definition: Type.h:2819
clang::TemplateArgumentListInfo::size
unsigned size() const
Definition: TemplateBase.h:577
clang::UnaryExprOrTypeTrait
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:97
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:231
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:3771
clang::ASTContext::LongAccumTy
CanQualType LongAccumTy
Definition: ASTContext.h:1029
clang::ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:111
clang::GNUNullExpr
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4057
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6308
clang::CallExpr::setArg
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2563
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:16073
DiagnoseDirectIsaAccess
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:496
clang::CallExpr::shrinkNumArgs
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:2574
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::Decl::isDefinedOutsideFunctionOrMethod
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:848
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)
Definition: Expr.cpp:406
ScopeInfo.h
clang::Sema::CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:9550
diagnoseArithmeticOnTwoVoidPointers
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:8948
clang::Type::isSpecificBuiltinType
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6511
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1872
clang::UnresolvedMemberExpr
Represents a C++ member access expression for which lookup produced a set of overloaded functions...
Definition: ExprCXX.h:3538
clang::FixItHint::isNull
bool isNull() const
Definition: Diagnostic.h:86
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:91
clang::ExtVectorElementExpr
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:5116
clang::Sema::ActOnObjCBoolLiteral
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:16808
clang::LookupResult::getResultKind
LookupResultKind getResultKind() const
Definition: Lookup.h:310
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3050
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:739
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:7003
clang::DeclarationName::CXXLiteralOperatorName
Definition: DeclarationName.h:213
clang::Type::isObjCQualifiedClassType
bool isObjCQualifiedClassType() const
Definition: Type.h:6416
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:439
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:14473
clang::Sema::FinalizeVarWithDestructor
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
Definition: SemaDeclCXX.cpp:13053
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:6226
clang::BinaryOperator::isAssignmentOp
bool isAssignmentOp() const
Definition: Expr.h:3413
clang::Type::isIntegralOrEnumerationType
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6644
clang::LookupResult::NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:56
llvm::SmallVectorImpl
Definition: LLVM.h:37
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:566
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:110
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2443
clang::InitializedEntity::InitializeBlock
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Definition: Initialization.h:296
clang::NullabilityKind::Nullable
Values of this type can be null.
clang::Selector::isUnarySelector
bool isUnarySelector() const
Definition: IdentifierTable.h:750
clang::FullExpr::setSubExpr
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition: Expr.h:895
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:63
clang::Type::STK_ObjCObjectPointer
Definition: Type.h:2064
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:496
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:2444
clang::BinaryOperator::getOpcodeStr
StringRef getOpcodeStr() const
Definition: Expr.h:3343
clang::ObjCIvarRefExpr::getOpLoc
SourceLocation getOpLoc() const
Definition: ExprObjC.h:564
checkCondition
static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:6546
clang::TypeLocBuilder
Definition: TypeLocBuilder.h:23
clang::Expr::isGLValue
bool isGLValue() const
Definition: Expr.h:252
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
clang::Expr::MLV_MemberFunction
Definition: Expr.h:282
clang::ParenListExpr::Create
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4051
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4185
clang::Expr::EvaluateAsBooleanCondition
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
Definition: ExprConstant.cpp:10944
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:5105
IsTypeModifiable
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:10954
clang::ObjCIvarRefExpr::isArrow
bool isArrow() const
Definition: ExprObjC.h:551
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:13662
clang::sema::Capture::isThisCapture
bool isThisCapture() const
Definition: ScopeInfo.h:561
CheckVecStepTraitOperandType
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:3605
clang::BinaryOperatorKind
BinaryOperatorKind
Definition: OperationKinds.h:26
clang::sema::Capture::getInitExpr
Expr * getInitExpr() const
Definition: ScopeInfo.h:613
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:934
clang::FixedPointLiteral::CreateFromRawInt
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:814
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:10121
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2657
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:558
clang::StringLiteral::getLength
unsigned getLength() const
Definition: Expr.h:1678
clang::TypeSpecTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:521
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:47
OpenCLArithmeticConversions
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:6820
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:174
clang::Sema::CallExprUnaryConversions
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:661
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:8533
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:437
clang::FunctionDecl::getBody
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:2731
clang::CXXDeleteExpr::getOperatorDelete
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2210
clang::DeclAccessPair::make
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
Definition: DeclAccessPair.h:36
clang::AS_private
Definition: Specifiers.h:101
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:6482
isVariableCapturable
static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14874
clang::Sema::ActOnBlockStart
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:13505
clang::ParmVarDecl::getOriginalType
QualType getOriginalType() const
Definition: Decl.cpp:2544
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:1208
clang::OverloadExpr::FindResult::HasFormOfMemberPointer
bool HasFormOfMemberPointer
Definition: ExprCXX.h:2687
clang::Sema::LK_Block
Definition: Sema.h:2744
clang::CharUnits
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
clang::Expr::EvalResult::Val
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:555
DiagnoseDivisionSizeofPointer
static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:8859
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:4961
clang::Expr::MLV_InvalidExpression
Definition: Expr.h:274
clang::Expr::LV_Valid
Definition: Expr.h:255
clang::format::Tok
const FormatToken & Tok
Definition: BreakableToken.h:244
clang::CXXBindTemporaryExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1244
clang::Qualifiers::hasAddressSpace
bool hasAddressSpace() const
Definition: Type.h:351
clang::LabelStmt::getDecl
LabelDecl * getDecl() const
Definition: Stmt.h:1610
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:32
clang::PredefinedExpr::PrettyFunction
Definition: Expr.h:1776
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:6797
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:7772
clang::Scope::ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:56
clang::Sema::CheckFloatComparison
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS)
Check for comparisons of floating point operands using != and ==.
Definition: SemaChecking.cpp:9472
clang::VarTemplateSpecializationDecl::getTemplateKeywordLoc
SourceLocation getTemplateKeywordLoc() const
Gets the location of the template keyword, if present.
Definition: DeclTemplate.h:2707
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:2067
clang::NullabilityKind::Unspecified
Whether values of this type can be null is (explicitly) unspecified.
clang::FunctionCallFilterCCC
Definition: TypoCorrection.h:359
clang::VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:119
clang::Expr::getValueKind
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
clang::ComparisonCategoryType::First
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:7771
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:1167
checkDirectCallValidity
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:5298
clang::TypeDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:2901
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:1468
clang::Sema::MarkDeclRefReferenced
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:15736
clang::Type::STK_CPointer
Definition: Type.h:2062
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:2026
clang::sema::BlockScopeInfo::FunctionType
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:721
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:2434
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:2874
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3287
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6142
clang::DeclaratorDecl::getQualifierLoc
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:753
clang::ASTContext::PseudoObjectTy
CanQualType PseudoObjectTy
Definition: ASTContext.h:1047
clang::Qualifiers::getAddressSpace
LangAS getAddressSpace() const
Definition: Type.h:352
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:6725
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:241
clang::Sema::ActOnObjCAvailabilityCheckExpr
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:16827
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:188
ExprObjC.h
clang::MemberExpr::isArrow
bool isArrow() const
Definition: Expr.h:2874
clang::NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:211
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:1649
clang::ASTContext::LongDoubleTy
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
clang::Expr::IgnoreParenCasts
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2595
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:15477
clang::Expr::MLV_IncompleteVoidType
Definition: Expr.h:272
clang::getLambdaAwareParentOfDeclContext
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:71
clang::VariableArrayType::getSizeExpr
Expr * getSizeExpr() const
Definition: Type.h:2991
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
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:7284
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6072
clang::ASTContext::getBOOLDecl
TypedefDecl * getBOOLDecl() const
Retrieve declaration of &#39;BOOL&#39; typedef.
Definition: ASTContext.h:1880
CheckExtensionTraitOperandType
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:3623
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:728
clang::StringLiteral::StringKind
StringKind
StringLiteral is followed by several trailing objects.
Definition: Expr.h:1588
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:5584
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1158
clang::ParmVarDecl::hasUnparsedDefaultArg
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1660
clang::TypoExpr
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5562
clang::Expr::MLV_ArrayType
Definition: Expr.h:280
clang::Sema::WarnOnPendingNoDerefs
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:14457
clang::frontend::CPlusPlus
Definition: LangStandard.h:26
clang::APValue::isInt
bool isInt() const
Definition: APValue.h:234
clang::ParenListExpr
Definition: Expr.h:4919
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:349
clang::BinaryOperator::isRelationalOp
bool isRelationalOp() const
Definition: Expr.h:3372
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:3903
clang::CastExpr
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2998
CheckIndirectionOperand
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc)
CheckIndirectionOperand - Type check unary indirection (prefix &#39;*&#39;).
Definition: SemaExpr.cpp:11962
clang::OffsetOfNode
Helper class for OffsetOfExpr.
Definition: Expr.h:2013
clang::Sema::ExpressionEvaluationContext::DiscardedStatement
The current expression occurs within a discarded statement.
clang::ObjCProtocolDecl
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2064
clang::CXXBindTemporaryExpr
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1217
clang::CXXBindTemporaryExpr::getTemporary
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1236
clang::Type::isBlockCompatibleObjCPointerType
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3844
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:9560
clang::LambdaExpr
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
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:792
clang::CXXMethodDecl::isInstance
bool isInstance() const
Definition: DeclCXX.h:2069
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:167
clang::Sema::DefaultFunctionArrayLvalueConversion
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:649
clang::Type::isScalarType
bool isScalarType() const
Definition: Type.h:6629
clang::Sema::ActOnNumericConstant
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3263
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:8194
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:503
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:100
clang::OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
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:12581
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:7549
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
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:986
clang::UnaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:1930
clang::ObjCMethodDecl::getReturnType
QualType getReturnType() const
Definition: DeclObjC.h:323
clang::LookupResult::addDecl
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:415
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:5965
llvm::ArrayRef
Definition: LLVM.h:32
enclosingClassIsRelatedToClassInWhichMembersWereFound
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:5324
clang::Sema::IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:9546
llvm::SmallString
Definition: LLVM.h:35
clang::Sema::BuildDeclarationNameExpr
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2784
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:325
clang::Type::STK_Floating
Definition: Type.h:2068
clang::ASTContext::getBOOLType
QualType getBOOLType() const
type of &#39;BOOL&#39; type.
Definition: ASTContext.h:1890
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:3339
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:143
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:16623
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:15697
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2127
clang::ASTContext::UnsignedCharTy
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
clang::CXXDefaultArgExpr
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1073
Template.h
clang::LabelDecl::setStmt
void setStmt(LabelStmt *T)
Definition: Decl.h:494
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, bool isConstexprSpecified=false)
Definition: Decl.h:1875
clang::Sema::LangOpts
const LangOptions & LangOpts
Definition: Sema.h:322
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:870
clang::Expr::MLV_ClassTemporary
Definition: Expr.h:285
CheckForNullPointerDereference
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:477
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:1914
clang::TypeLocBuilder::pushTypeSpec
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Definition: TypeLocBuilder.h:71
clang::Sema::ActOnStmtExprError
void ActOnStmtExprError()
Definition: SemaExpr.cpp:13197
clang::Sema::VarArgKind
VarArgKind
Definition: Sema.h:9476
clang::TypeLocBuilder::push
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Definition: TypeLocBuilder.h:96
clang::ObjCIvarRefExpr::getDecl
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
clang::Qualifiers::withoutObjCGCAttr
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:314
clang::Sema::ExpressionEvaluationContextRecord::NumCleanupObjects
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:976
clang::BinaryOperator::isNullPointerArithmeticExtension
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, Expr *LHS, Expr *RHS)
Definition: Expr.cpp:1960
clang::AS_none
Definition: Specifiers.h:102
OEK_Variable
Definition: SemaExpr.cpp:11096
clang::ComparisonCategoryType::StrongOrdering
clang::sema::CapturingScopeInfo::ImpCaptureStyle
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:629
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
Definition: ParsedTemplate.h:178
clang::Sema::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1235
clang::Type::isIntegralOrUnscopedEnumerationType
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1772
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:904
clang::Sema::CXXSpecialMember
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1167
clang::Type::isHalfType
bool isHalfType() const
Definition: Type.h:6550
Parent
NodeId Parent
Definition: ASTDiff.cpp:192
clang::ConversionFixItGenerator::Kind
OverloadFixItKind Kind
The type of fix applied.
Definition: SemaFixItUtils.h:50
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:3213
clang::OMPArraySectionExpr
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
clang::Sema::BuildPredefinedExpr
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK)
Definition: SemaExpr.cpp:3072
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:531
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3582
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
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:12655
clang::Type::isPromotableIntegerType
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2455
clang::LookupResult::setNamingClass
void setNamingClass(CXXRecordDecl *Record)
Sets the &#39;naming class&#39; for this lookup.
Definition: Lookup.h:397
clang::TypoCorrection::getFoundDecl
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Definition: TypoCorrection.h:147
ExprLooksBoolean
static bool ExprLooksBoolean(Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:7351
clang::sema::LambdaScopeInfo::Mutable
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:805
clang::CompoundStmt
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1241
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:1613
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:834
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
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:119
computeConditionalNullability
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:7404
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:589
clang::Sema::MarkAnyDeclReferenced
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:15771
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:2214
clang::Qualifiers::compatiblyIncludes
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:482
getDeclFromExpr
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12163
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:12242
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3300
clang::Expr::IgnoreParenNoopCasts
Expr * IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY
IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the value (including ptr->int ...
Definition: Expr.cpp:2726
clang::Type::isComplexType
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:481
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:7147
clang::sema::CapturedRegionScopeInfo
Retains information about a captured region.
Definition: ScopeInfo.h:737
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1334
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:12598
clang::CastKind
CastKind
CastKind - The kind of operation required for a conversion.
Definition: OperationKinds.h:21
clang::TypeLoc::getLocalSourceRange
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:157
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:1782
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1844
checkConditionalVoidType
static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, ExprResult &RHS)
Handle when one or both operands are void type.
Definition: SemaExpr.cpp:6565
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:569
clang::Expr::NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:711
clang::Sema::CheckAdditionOperands
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:9211
clang::Sema::FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:9536
clang::Type::STK_IntegralComplex
Definition: Type.h:2069
clang::UnaryOperator::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:1927
clang::UnaryExprOrTypeTraitExpr
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Definition: Expr.h:2222
clang::Type::isNonOverloadPlaceholderType
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6538
clang::BinaryOperator::getOpcodeStr
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to...
Definition: Expr.cpp:1888
clang::Expr::MLV_InvalidMessageExpression
Definition: Expr.h:284
clang::Sema::DiagnoseEmptyLookup
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, std::unique_ptr< CorrectionCandidateCallback > CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr *> Args=None, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:1819
clang::ASTContext::isObjCSelType
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2543
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6147
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:9150
clang::DeclRefExpr::getLocation
SourceLocation getLocation() const
Definition: Expr.h:1122
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:1814
clang::Sema::ICEConvertDiagnoser
Definition: Sema.h:2701
clang::VAArgExpr
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4091
clang::CXXDefaultArgExpr::Create
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param)
Definition: ExprCXX.h:1096
clang::NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:208
clang::Type::STK_BlockPointer
Definition: Type.h:2063
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:2600
clang::TemplateArgument::getAsDecl
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:264
clang::Sema::CTK_ErrorRecovery
Definition: Sema.h:3273
handleIntegerConversion
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1147
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:1504
clang::ArrayType::Normal
Definition: Type.h:2819
diagnoseArithmeticOnVoidPointer
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:8958
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:5705
clang::TypoCorrection::getAsString
std::string getAsString(const LangOptions &LO) const
Definition: SemaLookup.cpp:4907
clang::Sema::CheckLogicalOperands
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10813
Offset
unsigned Offset
Definition: Format.cpp:1631
clang::CharacterLiteral::getValue
unsigned getValue() const
Definition: Expr.h:1426
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:3101
clang::Sema::ActOnCompoundLiteral
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:5809
clang::MultiLevelTemplateArgumentList::getInnermost
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:155
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:136
clang::sema::CapturingScopeInfo::ImpCap_None
Definition: ScopeInfo.h:625
clang::Sema::DiagnoseAssignmentAsCondition
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition...
Definition: SemaExpr.cpp:16015
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
clang::Sema::ActOnBinOp
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12690
clang::Sema::CreateOverloadedBinOp
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true)
Create a binary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:12397
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:983
clang::sema::BlockScopeInfo
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:711
clang::DeclContext::getLexicalParent
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1768
Designator.h
clang::sema::LambdaScopeInfo::CallOperator
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:791
clang::ComplexType::getElementType
QualType getElementType() const
Definition: Type.h:2490
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:1283
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:4394
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:440
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:3385
clang::BlockDecl
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3858
clang::Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
clang::PredefinedExpr::LFunction
Definition: Expr.h:1772
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
clang::Expr
This represents one expression.
Definition: Expr.h:106
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::ConversionFixItGenerator::isNull
bool isNull()
Definition: SemaFixItUtils.h:85
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:236
isEvaluatableContext
static bool isEvaluatableContext(Sema &SemaRef)
Are we within a context in which some evaluation could be performed (be it constant evaluation or run...
Definition: SemaExpr.cpp:14559
clang::ExprValueKind
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
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:12559
clang::FunctionDecl::isVariadic
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2689
NCCK_None
Definition: SemaExpr.cpp:10917
clang::CallExpr::setCallee
void setCallee(Expr *F)
Definition: Expr.h:2516
llvm::MutableArrayRef
Definition: LLVM.h:33
Label
std::string Label
Definition: UsingDeclarationsSorter.cpp:70
getParentOfCapturingContextOrNull
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:14859
Id
int Id
Definition: ASTDiff.cpp:191
clang::ObjCInterfaceDecl::ivar_begin
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1460
clang::VarDecl::hasLocalStorage
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1036
clang::AttributedType::getNullabilityAttrKind
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4481
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:384
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:12544
clang::DeclContext::containsDecl
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1384
clang::OverloadExpr::find
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2695
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:1435
clang::ObjCRuntime::allowsSizeofAlignof
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:300
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:6440
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
maybeDiagnoseAssignmentToFunction
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:13954
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)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:15161
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:6087
clang::BlockExpr
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5177
maybeRebuildARCConsumingStmt
static Expr * maybeRebuildARCConsumingStmt(Stmt *Statement)
Given the last statement in a statement-expression, check whether the result is a producing expressio...
Definition: SemaExpr.cpp:13175
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:87
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2706
clang::ASTContext::OMPArraySectionTy
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1055
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2514
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::DeclarationName::getAsString
std::string getAsString() const
Retrieve the human-readable string for this name.
Definition: DeclarationName.cpp:229
Lookup.h
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:547
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
clang::Expr::MLV_SubObjCPropertySetting
Definition: Expr.h:283
Preprocessor.h
Defines the clang::Preprocessor interface.
clang::OMF_dealloc
Definition: IdentifierTable.h:628
clang::Type::isNullPtrType
bool isNullPtrType() const
Definition: Type.h:6569
clang::IsVariableAConstantExpression
bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaInternal.h:44
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:14220
clang::Sema::LK_String
Definition: Sema.h:2743
clang::CharLiteralParser
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Definition: LiteralSupport.h:176
DelayedDiagnostic.h
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
bool
#define bool
Definition: stdbool.h:31
clang::MemberExpr::performsVirtualDispatch
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:2908
clang::Qualifiers::getObjCLifetime
ObjCLifetime getObjCLifetime() const
Definition: Type.h:326
clang::Selector::getNameForSlot
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
Definition: IdentifierTable.cpp:436
clang::Type::isObjCClassType
bool isObjCClassType() const
Definition: Type.h:6428
DiagnoseShiftCompare
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12627
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:427
clang::ParenListExpr::getLParenLoc
SourceLocation getLParenLoc() const
Definition: Expr.h:4964
clang::StringLiteral::getCodeUnit
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1664
clang::OR_Success
Overload resolution succeeded.
Definition: Overload.h:54
clang::ObjCObjectPointerType::isObjCIdType
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:5856
clang::Type::isAnyComplexType
bool isAnyComplexType() const
Definition: Type.h:6377
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:7787
clang::UnaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode. ...
Definition: Expr.cpp:1217
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:12704
clang::ObjCInterfaceDecl::getSuperClass
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:338
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:1350
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:13973
clang::CXXRecordDecl::hasAnyDependentBases
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:526
clang::ASTContext::ShortTy
CanQualType ShortTy
Definition: ASTContext.h:1025
getCompareDecl
static ValueDecl * getCompareDecl(Expr *E)
Definition: SemaExpr.cpp:9924
clang::ASTMutationListener
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Definition: ASTMutationListener.h:47
clang::AsTypeExpr
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:5226
diagnoseUncapturableValueReference
static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, ValueDecl *var, DeclContext *DC)
Definition: SemaExpr.cpp:14786
Scope.h
clang::Sema::IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don&#39;t permit to be...
Definition: Sema.h:9555
clang::Sema::CheckPlaceholderExpr
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:16691
clang::Type::getScalarTypeKind
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:1967
clang::CallExpr::getDirectCallee
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2532
clang::DeclRefExpr::refersToEnclosingVariableOrCapture
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1239
clang::FloatingLiteral::Create
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:848
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:179
isMSPropertySubscriptExpr
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4206
clang::Sema::FullExprArg
Definition: Sema.h:3664
clang::Sema::RequireCompleteType
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7603
TypeLoc.h
Defines the clang::TypeLoc interface and its subclasses.
clang::ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:117
clang::UnqualifiedId::getKind
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1016
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:14538
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:411
clang::EvaluatedStmt::Value
Stmt * Value
Definition: Decl.h:804
clang::Expr::NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:715
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2695
clang::Expr::getType
QualType getType() const
Definition: Expr.h:128
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1800
clang::Type::STK_Bool
Definition: Type.h:2066
clang::Sema::ExpressionEvaluationContextRecord::ParentCleanup
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:969
clang::sema::CapturingScopeInfo::getCapture
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:692
clang::ObjCInterfaceDecl::lookupInstanceVariable
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:621
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:10754
clang::Expr::setValueKind
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:422
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:297
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:207
clang::ASTContext::getConstantArrayType
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, 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:3070
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
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:13518
clang::Qualifiers::setAddressSpace
void setAddressSpace(LangAS space)
Definition: Type.h:372
clang::PredefinedExpr::Create
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:497
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:4867
clang::Type::ScalarTypeKind
ScalarTypeKind
Definition: Type.h:2061
clang::Sema::isOpenMPCapturedDecl
VarDecl * isOpenMPCapturedDecl(ValueDecl *D)
Check if the specified variable is used in one of the private clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP constructs.
Definition: SemaOpenMP.cpp:1568
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
clang::MultiLevelTemplateArgumentList
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:65
clang::Sema::ExpressionEvaluationContextRecord::PossibleDerefs
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:1008
clang::Sema::ConditionKind
ConditionKind
Definition: Sema.h:9921
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:170
ConvertTokenKindToUnaryOpcode
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:12064
clang::Sema::OffsetOfComponent
Definition: Sema.h:4473
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:208
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:1896
clang::ObjCMethodDecl::isInstanceMethod
bool isInstanceMethod() const
Definition: DeclObjC.h:422
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:1380
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:2879
clang::VectorType
Represents a GCC generic vector type.
Definition: Type.h:3168
clang::ArrayType::getSizeModifier
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2849
clang::Sema::ActOnChooseExpr
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13461
clang::Expr::LV_MemberFunction
Definition: Expr.h:261
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:2512
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1078
clang::Sema::CleanupVarDeclMarking
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:15552
clang::sema::Capture
Definition: ScopeInfo.h:493
clang::ComparisonCategoryType::WeakEquality
clang::Type::getAsPlaceholderType
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:6524
ASTConsumer.h
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1114
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:171
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2768
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:1396
clang::TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
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:2815
clang::PredefinedExpr::IdentKind
IdentKind
Definition: Expr.h:1769
clang::CXXDeleteExpr::getDestroyedType
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:222
clang::ParenExpr::getSubExpr
const Expr * getSubExpr() const
Definition: Expr.h:1860
clang::CXXBindTemporaryExpr::getSubExpr
const Expr * getSubExpr() const
Definition: ExprCXX.h:1240
clang::sema::CapturedRegionScopeInfo::CapRegionKind
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:752
clang::Sema::BuildCompoundLiteralExpr
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:5823
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
clang::ObjCMethodDecl::getSelfDecl
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:414
clang::BlockDecl::setBlockMangling
void setBlockMangling(unsigned Number, Decl *Ctx)
Definition: Decl.h:4025
clang::Qualifiers::removeCVRQualifiers
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:281
clang::Sema::checkDeclIsAllowedInOpenMPTarget
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
Definition: SemaOpenMP.cpp:13691
clang::Sema::setOpenMPCaptureKind
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level)
Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) for FD based on DSA for the...
Definition: SemaOpenMP.cpp:1700
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:170
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:5198
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:2282
OEK_LValue
Definition: SemaExpr.cpp:11098
hasAnyExplicitStorageClass
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:129
clang::VarDecl::getCanonicalDecl
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2026
CorrectDelayedTyposInBinOp
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12211
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:1517
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
clang::Sema::LookupDestructor
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
Definition: SemaLookup.cpp:3138
clang::Stmt::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
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:166
clang::InitializationKind::CreateCopy
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Definition: Initialization.h:647
DiagnoseCalleeStaticArrayParam
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5087
clang::Expr::getObjectKind
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
clang::NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed...
Definition: Overload.h:215
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:5149
clang::IdentifierInfo::getBuiltinID
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
Definition: IdentifierTable.h:239
clang::LookupResult::isUnresolvableResult
bool isUnresolvableResult() const
Definition: Lookup.h:306
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:248
clang::ASTContext::getAttributedType
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
Definition: ASTContext.cpp:3929
clang::FunctionType::ExtInfo::withNoReturn
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3537
clang::ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:84
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6131
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:469
clang::Sema::ActOnParenExpr
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3600
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:6202
clang::FunctionProtoType::ExtProtoInfo::HasTrailingReturn
bool HasTrailingReturn
Definition: Type.h:3770
clang::BinaryOperator::isComparisonOp
bool isComparisonOp() const
Definition: Expr.h:3378
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:294
diagnoseAddressOfInvalidType
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:11715
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4380
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:15701
clang::BinaryOperator::isBitwiseOp
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3368
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:723
clang::ASTContext::getWideCharType
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1565
clang::BinaryOperator::getOverloadedOpcode
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:1897
clang::ObjCIvarDecl::Private
Definition: DeclObjC.h:1950
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:6751
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1460
clang::Expr::IgnoreConversionOperator
Expr * IgnoreConversionOperator() LLVM_READONLY
IgnoreConversionOperator - Ignore conversion operator.
Definition: Expr.cpp:2715
clang::TargetInfo::getIntMaxTWidth
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:630
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:10937
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:9012
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:945
clang::ASTContext::getBuiltinMSVaListType
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:1918
clang::ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:108
clang::OverloadCandidateSet::iterator
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:924
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:1636
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:6334
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:169
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:2635
clang::ImplicitConversionSequence
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:487
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6111
clang::Sema::CheckCaseExpression
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:16798
clang::VectorType::GenericVector
not a target-specific vector type
Definition: Type.h:3172
clang::ActionResult
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
clang::Sema::LookupInObjCMethod
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
LookupInObjCMethod - The parser has read a name in, and Sema has detected that we&#39;re currently inside...
Definition: SemaExpr.cpp:2400
clang::PseudoObjectExpr
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5299
clang::FunctionProtoType::param_types
param_type_range param_types() const
Definition: Type.h:4030
clang::Sema::InstantiatingTemplate
A stack object to be created when performing template instantiation.
Definition: Sema.h:7394
clang::FunctionProtoType::getExtParameterInfo
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4078
clang::sema::Capture::getVariable
VarDecl * getVariable() const
Definition: ScopeInfo.h:593
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3899
clang::Expr::MLV_NotObjectType
Definition: Expr.h:271
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1238
ConstMember
Definition: SemaExpr.cpp:10966
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
clang::ParenListExpr::getNumExprs
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:4945
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:3438
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::Sema::ActOnConvertVectorExpr
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:5570
clang::Sema::MaybeODRUseExprs
llvm::SmallPtrSet< Expr *, 2 > MaybeODRUseExprs
Store a list of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) ...
Definition: Sema.h:546
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3613
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:519
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:1038
clang::Expr::MLV_ConstQualifiedField
Definition: Expr.h:278
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
clang::BinaryOperator::getOperatorLoc
SourceLocation getOperatorLoc() const
Definition: Expr.h:3319
clang::Sema::ExpressionEvaluationContextRecord::SavedMaybeODRUseExprs
llvm::SmallPtrSet< Expr *, 2 > SavedMaybeODRUseExprs
Definition: Sema.h:982
clang::Sema::PrepareCastToObjCObjectPointer
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:5950
clang::QualType::getAddressSpace
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6188
clang::OMPDeclareReductionDecl
This represents &#39;#pragma omp declare reduction ...&#39; directive.
Definition: DeclOpenMP.h:103
clang::DependentScopeDeclRefExpr::Create
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:477
clang::Expr::NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:688
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:951
clang::Sema::isValidVarArgType
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:784
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:1926
clang::ObjCInterfaceType
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5738
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:7280
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2095
clang::sema::LambdaScopeInfo::Lambda
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:788
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:1662
clang::FunctionType::ExtParameterInfo::isNoEscape
bool isNoEscape() const
Definition: Type.h:3420
CheckCommaOperands
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11526
checkArithmeticOrEnumeralCompare
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10211
clang::Sema::ConversionToObjCStringLiteralCheck
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:13919
clang::Type::getAsComplexIntegerType
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:498
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3044
clang::Expr::MLV_NoSetterProperty
Definition: Expr.h:281
clang::CXXNewExpr
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1914
clang::CXXNewExpr::getBeginLoc
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2154
getPrimaryDecl
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:11658
clang::CompoundStmt::setLastStmt
void setLastStmt(Stmt *S)
Definition: Stmt.h:1283
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:3671
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:714
clang::ConstantExpr::Create
static ConstantExpr * Create(const ASTContext &Context, Expr *E)
Definition: Expr.h:909
IgnoreCommaOperand
static bool IgnoreCommaOperand(const Expr *E)
Definition: SemaExpr.cpp:11456
clang::ASTContext::CreateTypeSourceInfo
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
Definition: ASTContext.cpp:2586
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:394
clang::VectorType::getElementType
QualType getElementType() const
Definition: Type.h:3203
clang::Decl::setReferenced
void setReferenced(bool R=true)
Definition: DeclBase.h:577
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:469
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:9540
clang::Sema::ActOnCharacterConstant
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3140
clang::LookupResult::isOverloadedResult
bool isOverloadedResult() const
Determines if the results are overloaded.
Definition: Lookup.h:302
clang::ExprObjectKind
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:124
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:5519
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
Definition: PartialDiagnostic.h:419
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:1447
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
clang::prec::Shift
Definition: OperatorPrecedence.h:40
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:8476
clang::Token::setIdentifierInfo
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:186
clang::PredefinedExpr::FuncSig
Definition: Expr.h:1774
clang::ASTContext::getAsConstantArrayType
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2413
clang::OverloadExpr::FindResult
Definition: ExprCXX.h:2684
clang::Sema::TransformToPotentiallyEvaluated
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:14399
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:3456
clang::PredefinedExpr::ComputeName
static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl)
Definition: Expr.cpp:537
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:5206
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:49
clang::Sema::DefaultLvalueConversion
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:553
clang::InitializedEntity::InitializeCompoundLiteralInit
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
Definition: Initialization.h:397
clang::ASTContext::FloatTy
CanQualType FloatTy
Definition: ASTContext.h:1028
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
clang::OverloadExpr::FindResult::IsAddressOfOperand
bool IsAddressOfOperand
Definition: ExprCXX.h:2686
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:5409
clang::Sema::TryCapture_ExplicitByRef
Definition: Sema.h:4072
clang::Sema::ActOnInitList
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:5909
clang::Expr::NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:719
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:9377
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1016
Paren
Definition: PPMacroExpansion.cpp:619
CheckBoolLikeConversion
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
Definition: SemaChecking.cpp:11194
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::ParenListExpr::getExpr
Expr * getExpr(unsigned Init)
Definition: Expr.h:4947
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1485
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:540
clang::Sema::isOpenMPCapturedByRef
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const
Return true if the provided declaration VD should be captured by reference.
Definition: SemaOpenMP.cpp:1397
clang::Expr::isValueDependent
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
clang::VarTemplateSpecializationDecl::getTemplateArgsInfo
const TemplateArgumentListInfo & getTemplateArgsInfo() const
Definition: DeclTemplate.h:2571
clang::CharacterLiteral::UTF8
Definition: Expr.h:1397
clang::StringLiteral::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1741
clang::Qualifiers::withoutObjCLifetime
Qualifiers withoutObjCLifetime() const
Definition: Type.h:319
clang::Sema::CheckTransparentUnionArgumentConstraints
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8142
clang::ASTContext::Float16Ty
CanQualType Float16Ty
Definition: ASTContext.h:1041
clang::Expr::isKnownToHaveBooleanValue
bool isKnownToHaveBooleanValue() const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:134
llvm::SmallVector
Definition: LLVM.h:36
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6300
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6393
clang::Sema::TryCapture_Implicit
Definition: Sema.h:4072
clang::VectorType::AltiVecBool
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3181
clang::sema::CapturingScopeInfo::Captures
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:642
clang::StandardConversionSequence::setAsIdentityConversion
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion...
Definition: SemaOverload.cpp:185
clang::TargetInfo::getBuiltinVaListKind
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
clang::Sema::ExpressionEvaluationContextRecord::NumTypos
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:980
clang::ObjCPropertyDecl
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3115
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:1152
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:2536
clang::FunctionProtoTypeLoc
Definition: TypeLoc.h:1442
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:249
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:672
clang::VectorType::AltiVecVector
is AltiVec vector
Definition: Type.h:3175
clang::ParmVarDecl::hasUninstantiatedDefaultArg
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1664
SemaFixItUtils.h
clang::Sema::VerifyICEDiagnoser::diagnoseFold
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR)
Definition: SemaExpr.cpp:14214
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:212
clang::Sema::ActOnOMPArraySectionExpr
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4339
clang::PointerType::isAddressSpaceOverlapping
bool isAddressSpaceOverlapping(const PointerType &other) const
Returns true if address spaces of pointers overlap.
Definition: Type.h:2560
clang::sema::LambdaScopeInfo::addPotentialThisCapture
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:909
clang::Type::getTypeClass
TypeClass getTypeClass() const
Definition: Type.h:1811
clang::UETT_AlignOf
Used for C&#39;s _Alignof and C++&#39;s alignof.
Definition: TypeTraits.h:101
clang::FunctionDecl::getMinRequiredArguments
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3076
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:397
clang::TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
clang::ASTContext::typesAreBlockPointerCompatible
bool typesAreBlockPointerCompatible(QualType, QualType)
Definition: ASTContext.cpp:8452
clang::Type::isAnyCharacterType
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1823
clang::AtomicType
Definition: Type.h:5968
clang::CharacterLiteral
Definition: Expr.h:1392
clang::EnumType::getDecl
EnumDecl * getDecl() const
Definition: Type.h:4403
clang::ObjCMessageExpr::getMethodDecl
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1303
ExprOpenMP.h
clang::Type::isVectorType
bool isVectorType() const
Definition: Type.h:6381
clang::ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:141
clang::Qualifiers::OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
clang::StmtExpr
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3801
clang::PredefinedExpr::LFuncSig
Definition: Expr.h:1775
clang::OverloadCandidateSet
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:837
clang::TypeLoc::getFullDataSize
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:162
clang::UnresolvedMemberExpr::getNamingClass
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1473
clang::Sema::HandleExprEvaluationContextForTypeof
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:14546
clang::QualType::isCanonical
bool isCanonical() const
Definition: Type.h:6116
clang::TemplateArgumentListInfo::setLAngleLoc
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:574
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
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:2293
clang::TemplateArgumentListInfo::addArgument
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:595
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:9504
clang::CXXNewExpr::getOperatorDelete
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2035
isEnabled
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
Definition: AnalysisBasedWarnings.cpp:1966
FixedPoint.h
Defines the fixed point number interface.
clang::Sema::ActOnStmtExpr
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13206
clang::FunctionProtoType::getExceptionSpecType
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3922
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:215
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:5497
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:1541
clang::ComparisonCategoryType::StrongEquality
DiagnoseBadShiftValues
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:9421
PerformCastFn
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1129
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:12178
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:16599
clang::CompoundAssignOperator
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:3504
clang::DeclAccessPair
A POD class for pairing a NamedDecl* with an access specifier.
Definition: DeclAccessPair.h:30
clang::ImplicitParamDecl
Definition: Decl.h:1486
clang::Type::isRealType
bool isRealType() const
Definition: Type.cpp:1943
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:6518
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:5935
clang::GenericSelectionExpr
Represents a C11 generic selection.
Definition: Expr.h:5010
clang::Sema::ReuseLambdaContextDecl_t
ReuseLambdaContextDecl_t
Definition: Sema.h:4035
ConstUnknown
Definition: SemaExpr.cpp:10969
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:2495
clang::CXXBasePathElement
Represents an element in a path from a derived class to a base class.
Definition: CXXInheritance.h:45
clang::AddrLabelExpr
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3757
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5014
clang::Sema::MarkMemberReferenced
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:15749
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1018
clang::Expr::LV_ArrayTemporary
Definition: Expr.h:264
clang::TemplateArgument
Represents a template argument.
Definition: TemplateBase.h:51
clang::Sema::PerformCopyInitialization
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9125
clang::Type::isPipeType
bool isPipeType() const
Definition: Type.h:6477
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:1760
isInvalid
static bool isInvalid(LocType Loc, bool *Invalid)
Definition: SourceManager.cpp:1166
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:10917
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:8123
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:2535
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:22
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:5601
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:108
clang::StringLiteral::Wide
Definition: Expr.h:1588
clang::FunctionType::getExtInfo
ExtInfo getExtInfo() const
Definition: Type.h:3624
clang::StringLiteral::UTF32
Definition: Expr.h:1588
clang::Sema::BuildParmVarDeclForTypedef
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:12470
isScopedEnumerationType
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:9415
clang::ASTContext::mergeTypes
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
Definition: ASTContext.cpp:8697
clang::UnaryOperatorKind
UnaryOperatorKind
Definition: OperationKinds.h:31
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
clang::Sema::ActOnUnaryOp
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input)
Definition: SemaExpr.cpp:13156
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
clang::Sema::getCurObjCLexicalContext
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:10744
clang::CXXDeleteExpr
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2170
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:1361
clang::BlockDecl::captures
ArrayRef< Capture > captures() const
Definition: Decl.h:3985
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:9120
clang::ASTContext::isSentinelNullExpr
bool isSentinelNullExpr(const Expr *E)
Definition: ASTContext.cpp:2489
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
clang::OverloadedOperatorKind
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
clang::CharacterLiteral::CharacterKind
CharacterKind
Definition: Expr.h:1394
clang::Sema::GetSignedVectorType
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:10681
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:474
clang::TargetInfo::CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:184
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:1091
clang::TypeLoc::getType
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:131
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:10721
clang::FunctionDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3558
clang::tooling::fixit::internal::getSourceRange
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
clang::BinaryOperator::isShiftOp
bool isShiftOp() const
Definition: Expr.h:3366
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:1827
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:182
clang::Sema::CheckLiteralKind
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:9789
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:2109
IsVariableNonDependentAndAConstantExpression
static bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaExpr.cpp:15496
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2825
clang::SC_Extern
Definition: Specifiers.h:209
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:8429
clang::CastExpr::setSubExpr
void setSubExpr(Expr *E)
Definition: Expr.h:3052
clang::Sema::ActOnAsTypeExpr
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:5549
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:15929
type
IteratorComparison::getOpcode
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
checkArithmeticNull
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:8823
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
clang::StringLiteral::UTF16
Definition: Expr.h:1588
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:1773
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:9939
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1220
clang::ASTContext::hasCvrSimilarType
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
Definition: ASTContext.cpp:5186
clang::ObjCIvarRefExpr::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:562
clang::ObjCAvailabilityCheckExpr
A runtime availability query.
Definition: ExprObjC.h:1636
clang::ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:87
clang::TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:160
ShouldLookupResultBeMultiVersionOverload
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:2777
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:639
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:3694
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:146
clang::Stmt::getStmtClass
StmtClass getStmtClass() const
Definition: Stmt.h:1029
clang::VectorType::getVectorKind
VectorKind getVectorKind() const
Definition: Type.h:3213
clang::CastExpr::getCastKindName
const char * getCastKindName() const
Definition: Expr.h:3048
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:506
clang::ParmVarDecl::getDefaultArg
Expr * getDefaultArg()
Definition: Decl.cpp:2573
clang::FunctionDecl::setInstantiationIsPending
void setInstantiationIsPending(bool IC)
State that the instantiation of this function is pending.
Definition: Decl.h:2109
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:971
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:346
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
clang::CXXDefaultArgExpr::getExpr
const Expr * getExpr() const
Definition: ExprCXX.h:1106
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:6657
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:421
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:16243
clang::OverloadExpr::FindResult::Expression
OverloadExpr * Expression
Definition: ExprCXX.h:2685
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:3570
clang::Expr::NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
Definition: Expr.h:695
clang::cast
U cast(CodeGen::Address addr)
Definition: Address.h:109
clang::Sema::prepareVectorSplat
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6257
clang::UnresolvedSet
A set of unresolved declarations.
Definition: UnresolvedSet.h:144
clang::frontend::CPlusPlus11
Definition: LangStandard.h:27
clang::Sema::ExpressionEvaluationContextRecord::isConstantEvaluated
bool isConstantEvaluated() const
Definition: Sema.h:1035
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:9573
clang::Expr::NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:701
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:9881
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:3636
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:12531
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:11569
clang::TemplateSpecializationKind
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:146
clang::DeclarationName::CXXDestructorName
Definition: DeclarationName.h:208
clang::InitializationKind::CreateCStyleCast
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Definition: Initialization.h:628
clang::StringLiteral::Ascii
Definition: Expr.h:1588
clang::Sema::FullExprArg::get
Expr * get() const
Definition: Sema.h:3673
clang::VarDecl::isInitCapture
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1391
clang::CXXMethodDecl::isUserProvided
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:2144
clang::DeclarationName::CXXConversionFunctionName
Definition: DeclarationName.h:209
clang::sema::CapturedRegionScopeInfo::OpenMPLevel
unsigned short OpenMPLevel
Definition: ScopeInfo.h:754
clang::ExplicitCastExpr
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3190
checkArithmeticOnObjCPointer
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4192
clang::Sema::ActOnPredefinedExpr
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3123
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:691
clang::InitListExpr::setInitializedFieldInUnion
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4303
clang::Sema::ActOnConstantExpression
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:15538
clang::Token::getLength
unsigned getLength() const
Definition: Token.h:127
clang::TypoCorrection::getCorrectionAsIdentifierInfo
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Definition: TypoCorrection.h:87
clang::TargetInfo::hasFeature
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1085
clang::ASTContext::areComparableObjCPointerTypes
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
Definition: ASTContext.cpp:8418
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:4983
clang::Sema::CreateGenericSelectionExpr
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo *> Types, ArrayRef< Expr *> Exprs)
Definition: SemaExpr.cpp:1350
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
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2693
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:261
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:101
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:7299
clang::Sema::LookupOverloadedOperatorName
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions)
Definition: SemaLookup.cpp:2833
clang::Sema::VerifyICEDiagnoser::Suppress
bool Suppress
Definition: Sema.h:9979
clang::ObjCObjectPointerType
Represents a pointer to an Objective C object.
Definition: Type.h:5794
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
clang::BlockPointerType
Pointer to a block type.
Definition: Type.h:2639
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:3636
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:12552
clang::CXXDeleteExpr::getBeginLoc
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2221
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:9152
DiagnoseBadDivideOrRemainderValues
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:8885
clang::OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:23
clang::sema::CapturedRegionScopeInfo::TheRecordDecl
RecordDecl * TheRecordDecl
The captured record type.
Definition: ScopeInfo.h:743
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:4118
clang::Expr::EvalStatus::HasSideEffects
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
clang::ComplexType
Complex values, per C99 6.2.5p11.
Definition: Type.h:2477
clang::TemplateArgumentLoc
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
clang::CharacterLiteral::Wide
Definition: Expr.h:1396
clang::ParmVarDecl::getUninstantiatedDefaultArg
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2615
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:3575
clang::CompoundStmt::body_empty
bool body_empty() const
Definition: Stmt.h:1268
clang::ObjCObjectPointerType::getInterfaceDecl
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5850
clang::ArraySubscriptExpr
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2312
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:1952
clang::Sema::ObjCLiteralKind
ObjCLiteralKind
Definition: Sema.h:2738
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:6957
clang::Type::isIntegerType
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
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:2317
clang::ASTContext::UnsignedLongTy
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
clang::DeclaratorDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1771
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:7814
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:527
clang::Sema::CheckExtVectorCast
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6290
clang::ObjCIvarRefExpr::getLocation
SourceLocation getLocation() const
Definition: ExprObjC.h:556
DiagnoseAdditionInShift
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:12613
clang::ConstantArrayType::getSize
const llvm::APInt & getSize() const
Definition: Type.h:2890
clang::ASTContext::getCharWidth
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2074
clang::QualType::DK_none
Definition: Type.h:1141
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1045
clang::Type::isImageType
bool isImageType() const
Definition: Type.h:6470
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:1203
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:9065
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:6406
checkThreeWayNarrowingConversion
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:10078
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6292
clang::Qualifiers::isAddressSpaceSupersetOf
bool isAddressSpaceSupersetOf(Qualifiers other) const
Returns true if this address space is a superset of the other one.
Definition: Type.h:469
clang::Type::isObjCQualifiedIdType
bool isObjCQualifiedIdType() const
Definition: Type.h:6410
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:1496
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
clang::ExtVectorType
ExtVectorType - Extended vector type.
Definition: Type.h:3287
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:1921
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2673
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1730
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2269
clang::ASTContext::BoundMemberTy
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
clang::Expr::LValueClassification
LValueClassification
Definition: Expr.h:254
clang::Sema::ExprEvalContexts
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1041
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:7687
clang::Sema::isInOpenMPDeclareTargetContext
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:8823
clang::Sema::CreateBuiltinUnaryOp
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12854
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:11562
clang::ObjCObjectPointerType::quals
qual_range quals() const
Definition: Type.h:5917
clang::InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:32
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:2753
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::DeclContext::addDecl
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1507
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:7998
clang::Sema::ExpressionEvaluationContextRecord::isUnevaluated
bool isUnevaluated() const
Definition: Sema.h:1030
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:251
clang::ObjCIvarRefExpr::getBase
const Expr * getBase() const
Definition: ExprObjC.h:547
clang::Type::getNullability
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3696
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:2806
clang::Type::isConstantArrayType
bool isConstantArrayType() const
Definition: Type.h:6349
clang::sema::CapturingScopeInfo::CaptureMap
llvm::DenseMap< VarDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:635
clang::APValue
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
NCCK_Lambda
Definition: SemaExpr.cpp:10917
clang::Sema::ActOnBuiltinOffsetOf
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:13442
clang::OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:129
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:8577
clang::Decl::markUsed
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
clang::ObjCIvarRefExpr
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
clang::Scope::DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:60
clang::InitializedEntity::InitializeStmtExprResult
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
Definition: Initialization.h:291
diagnoseDistinctPointerComparison
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:9678
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:8366
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:6397
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:2031
clang::Sema::ActOnIdExpression
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2067
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:2356
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:9602
clang::QualType::withCVRQualifiers
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:830
clang::PredefinedExpr::Func
Definition: Expr.h:1770
clang::Sema::getScopeForContext
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:1360
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2253
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:238
clang::LookupResult::getNamingClass
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:392
clang::BlockDecl::Create
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4442
clang::Qualifiers::OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
clang::Type::isQueueT
bool isQueueT() const
Definition: Type.h:6462
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:4029
clang::TemplateArgument::getKind
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
clang::AttributedType
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4425
clang::DeclarationNameTable::getCXXLiteralOperatorName
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
Definition: DeclarationName.cpp:368
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:3890
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:881
clang::Expr::NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:698
clang::Sema::MaybeCreateExprWithCleanups
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
Definition: SemaExprCXX.cpp:6503
clang::Sema::BuildDeclRefExpr
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1687
clang::ASTContext::typesAreCompatible
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Definition: ASTContext.cpp:8440
DoMarkVarDeclReferenced
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E)
Definition: SemaExpr.cpp:15574
clang::ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:90
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:1324
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2682
clang::Expr::MLV_ConstQualified
Definition: Expr.h:277
clang::UETT_SizeOf
Definition: TypeTraits.h:98
clang::Sema::ExpressionEvaluationContextRecord
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:964
clang::Sema::CheckBitwiseOperands
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10778
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:759
clang::StringLiteral::UTF8
Definition: Expr.h:1588
clang::ExprResult
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6152
clang::sema::PossiblyUnreachableDiag
Definition: ScopeInfo.h:84
clang::TagDecl::getTypedefNameForAnonDecl
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3274
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:1052
clang::ParmVarDecl::setDefaultArg
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2585
isObjCObjectLiteral
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:9730
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:1874
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
clang::Sema::Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9524
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:3006
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6544
clang::ASTContext::getTypeInfo
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
Definition: ASTContext.cpp:1737
clang::FunctionDecl::getBuiltinID
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2994
clang::Sema::CUDAFunctionTarget
CUDAFunctionTarget
Definition: Sema.h:10156
clang::sema::Capture::markUsed
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:591
clang::Sema::getCurFunction
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1358
clang::OMPArraySectionExpr::getBaseOriginalType
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4257
clang::ParenExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1864
clang::ChooseExpr
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3977
clang::Expr::hasAnyTypeDependentArguments
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2886
clang::sema::Capture::isNested
bool isNested() const
Definition: ScopeInfo.h:585
clang::Sema::LK_None
Definition: Sema.h:2745
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:7305
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3655
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:1733
clang::ParenListExpr::getRParenLoc
SourceLocation getRParenLoc() const
Definition: Expr.h:4965
clang::frontend::CPlusPlus14
Definition: LangStandard.h:28
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:109
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:3151
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1945
clang::UETT_VecStep
Definition: TypeTraits.h:102
clang::ASTContext::Char16Ty
CanQualType Char16Ty
Definition: ASTContext.h:1023
clang::BinaryOperator::isMultiplicativeOp
bool isMultiplicativeOp() const
Definition: Expr.h:3362
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:6229
clang::sema::LambdaScopeInfo
Definition: ScopeInfo.h:785
clang::Sema::TryCaptureKind
TryCaptureKind
Definition: Sema.h:4071
clang::Sema::NeedToCaptureVariable
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:15469
clang::Sema::CheckCompareOperands
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:10240
clang::Sema::CheckMultiplyDivideOperands
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:8898
clang::sema::BlockScopeInfo::TheDecl
BlockDecl * TheDecl
Definition: ScopeInfo.h:713
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:568
clang::TemplateArgumentLocInfo
Location information for a TemplateArgument.
Definition: TemplateBase.h:393
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:336
clang::Type::isSamplerT
bool isSamplerT() const
Definition: Type.h:6450
clang::sema::CapturingScopeInfo::isCXXThisCaptured
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:674
clang::Sema::MaybeSuggestAddingStaticToDecl
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:189
clang::Expr::containsUnexpandedParameterPack
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
Definition: Expr.h:214
clang::Expr::isRValue
bool isRValue() const
Definition: Expr.h:250
clang::StringLiteralParser
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Definition: LiteralSupport.h:206
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:2847
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:2391
clang::sema::CapturingScopeInfo::addVLATypeCapture
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType)
Definition: ScopeInfo.h:660
clang::Sema::getSourceManager
SourceManager & getSourceManager() const
Definition: Sema.h:1236
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:325
clang::UnqualifiedIdKind::IK_TemplateId
A template-id, e.g., f<int>.
clang::sema::CapturingScopeInfo
Definition: ScopeInfo.h:619
clang::InitializedEntity::setParameterCFAudited
void setParameterCFAudited()
Definition: Initialization.h:523
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:276
clang::OMF_init
Definition: IdentifierTable.h:621
clang::Sema::DiagnoseCommaOperator
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11477
NestedConstMember
Definition: SemaExpr.cpp:10968
clang::Sema::ExpressionEvaluationContext
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all...
Definition: Sema.h:917
BuildFloatingLiteral
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3203
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1566
TargetInfo.h
Defines the clang::TargetInfo interface.
clang::Type::isComplexIntegerType
bool isComplexIntegerType() const
Definition: Type.cpp:487
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
castKindToImplicitConversionKind
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:10041
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:8652
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
clang::Expr::MLV_Valid
Definition: Expr.h:270
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:1639
clang::Sema::UpdateMarkingForLValueToRValue
void UpdateMarkingForLValueToRValue(Expr *E)
Definition: SemaExpr.cpp:15513
clang::FunctionDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3637
clang::sema::CapturingScopeInfo::HasImplicitReturnType
bool HasImplicitReturnType
Definition: ScopeInfo.h:646
clang::NamedDecl::getName
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
clang::Qualifiers::getCVRQualifiers
unsigned getCVRQualifiers() const
Definition: Type.h:274
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:283
clang::NumericLiteralParser
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber...
Definition: LiteralSupport.h:43
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:2547
clang::TypeInfo::Width
uint64_t Width
Definition: ASTContext.h:144
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1025
clang::CR_OpenMP
Definition: CapturedStmt.h:20
captureInBlock
static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S)
Definition: SemaExpr.cpp:14942
clang::VectorType::getNumElements
unsigned getNumElements() const
Definition: Type.h:3204
clang::SC_Register
Definition: Specifiers.h:215
clang::ObjCBoolLiteralExpr
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:82
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
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:2079
clang::CallExpr::ADLCallKind
ADLCallKind
Definition: Expr.h:2443
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:5366
clang::MemberExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1600
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
clang::frontend::C99
Definition: LangStandard.h:23
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:819
clang::ConversionFixItGenerator
The class facilities generation and storage of conversion FixIts.
Definition: SemaFixItUtils.h:33
clang::sema::AnalysisBasedWarnings::Policy
Definition: AnalysisBasedWarnings.h:35
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3329
clang::Sema::BuildVAArgExpr
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:13792
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2136
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6296
clang::BinaryOperator::isBitwiseOp
bool isBitwiseOp() const
Definition: Expr.h:3369
clang::UnaryOperator::isIncrementDecrementOp
bool isIncrementDecrementOp() const
Definition: Expr.h:1970
isOdrUseContext
static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses=true)
Are we within a context in which references to resolved functions or to variables result in odr-use...
Definition: SemaExpr.cpp:14584
clang::LabelStmt::setSubStmt
void setSubStmt(Stmt *SS)
Definition: Stmt.h:1617
clang::TypedefType
Definition: Type.h:4151
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:1540
clang::BinaryOperator::getOverloadedOperator
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:1935
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:119
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2167
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
clang::sema::CapturingScopeInfo::addCapture
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:652
clang::prec::Comma
Definition: OperatorPrecedence.h:29
clang::TypeLoc::initializeFullCopy
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:196
clang::Declarator::getContext
DeclaratorContext getContext() const
Definition: DeclSpec.h:1879
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
clang::Token::setLocation
void setLocation(SourceLocation L)
Definition: Token.h:132
clang::ActionResult::getAs
T * getAs()
Definition: Ownership.h:175
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:648
clang::Expr::MLV_DuplicateVectorComponents
Definition: Expr.h:273
clang::VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:328
clang::Type::isFloatingType
bool isFloatingType() const
Definition: Type.cpp:1921
clang::isUnresolvedExceptionSpec
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
Definition: ExceptionSpecificationType.h:48
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:198
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:324
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< 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:4722
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2983
clang::CallExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1428
clang::Sema::IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:9578
ConstVariable
Definition: SemaExpr.cpp:10965
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:16100
clang::DeclarationName::CXXOperatorName
Definition: DeclarationName.h:210
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:249
clang::UnqualifiedId::setIdentifier
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1023
clang::ASTContext::getObjCObjectPointerType
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Definition: ASTContext.cpp:4687
clang::Builtin::Context::hasCustomTypechecking
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:160
clang::Sema::BuildVectorLiteral
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:6399
clang::DeclRefExpr::getQualifier
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1141
clang::Decl::setAccess
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:457
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:2971
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:15972
clang::ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5071
clang::ASTContext::ObjCQualifiedIdTypesAreCompatible
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
Definition: ASTContext.cpp:7878
clang::Sema::getCurLambda
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1550
clang::Sema::BuildBinOp
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12738
clang::DeclaratorContext::BlockLiteralContext
clang::APValue::getInt
APSInt & getInt()
Definition: APValue.h:252
clang::ObjCIvarDecl::getAccessControl
AccessControl getAccessControl() const
Definition: DeclObjC.h:1984
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:324
clang::ASTContext::DoubleTy
CanQualType DoubleTy
Definition: ASTContext.h:1028
clang::LookupResult::getNameLoc
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:595
clang::Expr::MLV_ConstAddrSpace
Definition: Expr.h:279
clang::ASTContext::isObjCNSObjectType
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2050
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:49
clang::Type::isFunctionPointerType
bool isFunctionPointerType() const
Definition: Type.h:6320
clang::FieldDecl::Create
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3762
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:185
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:513
clang::ComparisonCategoryType
ComparisonCategoryType
An enumeration representing the different comparison categories types.
Definition: ComparisonCategories.h:44
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:339
clang::StandardConversionSequence::setToType
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:306
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:6350
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:6909
clang::FunctionDecl::getNumParams
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:649
clang::Qualifiers::removeAddressSpace
void removeAddressSpace()
Definition: Type.h:377
clang::BinaryOperator::isComparisonOp
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3377
clang::OpaquePtr< QualType >::getFromOpaquePtr
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
clang::VarDecl::hasInit
bool hasInit() const
Definition: Decl.cpp:2164
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:207
clang::Sema::AssignmentAction
AssignmentAction
Definition: Sema.h:2525
ColonLoc
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:108
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
clang::TypoCorrection::WillReplaceSpecifier
void WillReplaceSpecifier(bool ForceReplacement)
Definition: TypoCorrection.h:101
clang::sema::Capture::isBlockCapture
bool isBlockCapture() const
Definition: ScopeInfo.h:577
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
An implicit &#39;self&#39; parameter.
clang::ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:230
clang::Sema::LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:3127
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:12122
clang::ConstantArrayType
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2872
IsArithmeticOp
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:7295
clang::Sema::IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types...
Definition: Sema.h:9561
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:5650
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:969
clang::ObjCIvarRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:559
clang::FunctionType::ExtInfo
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3466
isImplicitlyDefinableConstexprFunction
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:14607
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:686
clang::Sema::ConditionResult
Definition: Sema.h:9887
clang::AvailabilitySpec
One specifier in an expression.
Definition: Availability.h:31
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1943
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:44
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:418
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:1861
CastType
CastType
Definition: SemaCast.cpp:46
clang::Sema::UsualArithmeticConversions
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign=false)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1244
clang::Token::startToken
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
clang::Sema::ActOnAddrLabel
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:13162
clang::NamedDecl::isExternallyVisible
bool isExternallyVisible() const
Definition: Decl.h:380
clang::UETT_OpenMPRequiredSimdAlign
Definition: TypeTraits.h:103
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:11727
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:98
clang::IdentifierInfo::isEditorPlaceholder
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
Definition: IdentifierTable.h:384
clang::TemplateIdAnnotation::Template
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Definition: ParsedTemplate.h:171
clang::ObjCMethodDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:367
diagnoseArithmeticOnNullPointer
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:8971
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:2819
clang::ASTContext::getIntTypeForBitwidth
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
Definition: ASTContext.cpp:10021
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:13650
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:145
clang::Sema::SemaDiagnosticBuilder
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1261
clang::VarDecl::ensureEvaluatedStmt
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form, which contains extra information on the evaluated value of the initializer.
Definition: Decl.cpp:2244
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560
OriginalExprKind
OriginalExprKind
Definition: SemaExpr.cpp:11095
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:3602
clang::ASTContext::getSizeType
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Definition: ASTContext.cpp:4958
clang::Type::STK_Integral
Definition: Type.h:2067
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1058
RecordModifiableNonNullParam
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:11943
clang::EvaluatedStmt
Structure used to store a statement, the constant value to which it was evaluated (if any)...
Definition: Decl.h:784
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:728
clang::Sema::getVariadicCallType
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:4781
clang::ObjCObjectPointerType::getPointeeType
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5810
clang::StandardConversionSequence
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:230
CheckRealImagOperand
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4135