1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54 
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58   // See if this is an auto-typed variable whose initializer we are parsing.
59   if (ParsingInitForAutoVars.count(D))
60     return false;
61 
62   // See if this is a deleted function.
63   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64     if (FD->isDeleted())
65       return false;
66 
67     // If the function has a deduced return type, and we can't deduce it,
68     // then we can't use it either.
69     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71       return false;
72 
73     // See if this is an aligned allocation/deallocation function that is
74     // unavailable.
75     if (TreatUnavailableAsInvalid &&
76         isUnavailableAlignedAllocationFunction(*FD))
77       return false;
78   }
79 
80   // See if this function is unavailable.
81   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83     return false;
84 
85   return true;
86 }
87 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89   // Warn if this is used but marked unused.
90   if (const auto *A = D->getAttr<UnusedAttr>()) {
91     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92     // should diagnose them.
93     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96       if (DC && !DC->hasAttr<UnusedAttr>())
97         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
98     }
99   }
100 }
101 
102 /// Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104   assert(Decl && Decl->isDeleted());
105 
106   if (Decl->isDefaulted()) {
107     // If the method was explicitly defaulted, point at that declaration.
108     if (!Decl->isImplicit())
109       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110 
111     // Try to diagnose why this special member function was implicitly
112     // deleted. This might fail, if that reason no longer applies.
113     DiagnoseDeletedDefaultedFunction(Decl);
114     return;
115   }
116 
117   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118   if (Ctor && Ctor->isInheritingConstructor())
119     return NoteDeletedInheritingConstructor(Ctor);
120 
121   Diag(Decl->getLocation(), diag::note_availability_specified_here)
122     << Decl << 1;
123 }
124 
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128   for (auto I : D->redecls()) {
129     if (I->getStorageClass() != SC_None)
130       return true;
131   }
132   return false;
133 }
134 
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144                                                       const NamedDecl *D,
145                                                       SourceLocation Loc) {
146   // This is disabled under C++; there are too many ways for this to fire in
147   // contexts where the warning is a false positive, or where it is technically
148   // correct but benign.
149   if (S.getLangOpts().CPlusPlus)
150     return;
151 
152   // Check if this is an inlined function or method.
153   FunctionDecl *Current = S.getCurFunctionDecl();
154   if (!Current)
155     return;
156   if (!Current->isInlined())
157     return;
158   if (!Current->isExternallyVisible())
159     return;
160 
161   // Check if the decl has internal linkage.
162   if (D->getFormalLinkage() != InternalLinkage)
163     return;
164 
165   // Downgrade from ExtWarn to Extension if
166   //  (1) the supposedly external inline function is in the main file,
167   //      and probably won't be included anywhere else.
168   //  (2) the thing we're referencing is a pure function.
169   //  (3) the thing we're referencing is another inline function.
170   // This last can give us false negatives, but it's better than warning on
171   // wrappers for simple C library functions.
172   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174   if (!DowngradeWarning && UsedFn)
175     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176 
177   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178                                : diag::ext_internal_in_extern_inline)
179     << /*IsVar=*/!UsedFn << D;
180 
181   S.MaybeSuggestAddingStaticToDecl(Current);
182 
183   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184       << D;
185 }
186 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188   const FunctionDecl *First = Cur->getFirstDecl();
189 
190   // Suggest "static" on the function, if possible.
191   if (!hasAnyExplicitStorageClass(First)) {
192     SourceLocation DeclBegin = First->getSourceRange().getBegin();
193     Diag(DeclBegin, diag::note_convert_inline_to_static)
194       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195   }
196 }
197 
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
DiagnoseUseOfDecl(NamedDecl * D,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess,bool AvoidPartialAvailabilityChecks,ObjCInterfaceDecl * ClassReceiver)210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211                              const ObjCInterfaceDecl *UnknownObjCClass,
212                              bool ObjCPropertyAccess,
213                              bool AvoidPartialAvailabilityChecks,
214                              ObjCInterfaceDecl *ClassReceiver) {
215   SourceLocation Loc = Locs.front();
216   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217     // If there were any diagnostics suppressed by template argument deduction,
218     // emit them now.
219     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220     if (Pos != SuppressedDiagnostics.end()) {
221       for (const PartialDiagnosticAt &Suppressed : Pos->second)
222         Diag(Suppressed.first, Suppressed.second);
223 
224       // Clear out the list of suppressed diagnostics, so that we don't emit
225       // them again for this specialization. However, we don't obsolete this
226       // entry from the table, because we want to avoid ever emitting these
227       // diagnostics again.
228       Pos->second.clear();
229     }
230 
231     // C++ [basic.start.main]p3:
232     //   The function 'main' shall not be used within a program.
233     if (cast<FunctionDecl>(D)->isMain())
234       Diag(Loc, diag::ext_main_used);
235 
236     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237   }
238 
239   // See if this is an auto-typed variable whose initializer we are parsing.
240   if (ParsingInitForAutoVars.count(D)) {
241     if (isa<BindingDecl>(D)) {
242       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243         << D->getDeclName();
244     } else {
245       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246         << D->getDeclName() << cast<VarDecl>(D)->getType();
247     }
248     return true;
249   }
250 
251   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252     // See if this is a deleted function.
253     if (FD->isDeleted()) {
254       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255       if (Ctor && Ctor->isInheritingConstructor())
256         Diag(Loc, diag::err_deleted_inherited_ctor_use)
257             << Ctor->getParent()
258             << Ctor->getInheritedConstructor().getConstructor()->getParent();
259       else
260         Diag(Loc, diag::err_deleted_function_use);
261       NoteDeletedFunction(FD);
262       return true;
263     }
264 
265     // [expr.prim.id]p4
266     //   A program that refers explicitly or implicitly to a function with a
267     //   trailing requires-clause whose constraint-expression is not satisfied,
268     //   other than to declare it, is ill-formed. [...]
269     //
270     // See if this is a function with constraints that need to be satisfied.
271     // Check this before deducing the return type, as it might instantiate the
272     // definition.
273     if (FD->getTrailingRequiresClause()) {
274       ConstraintSatisfaction Satisfaction;
275       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276         // A diagnostic will have already been generated (non-constant
277         // constraint expression, for example)
278         return true;
279       if (!Satisfaction.IsSatisfied) {
280         Diag(Loc,
281              diag::err_reference_to_function_with_unsatisfied_constraints)
282             << D;
283         DiagnoseUnsatisfiedConstraint(Satisfaction);
284         return true;
285       }
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293 
294     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295       return true;
296 
297     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298       return true;
299   }
300 
301   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302     // Lambdas are only default-constructible or assignable in C++2a onwards.
303     if (MD->getParent()->isLambda() &&
304         ((isa<CXXConstructorDecl>(MD) &&
305           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308         << !isa<CXXConstructorDecl>(MD);
309     }
310   }
311 
312   auto getReferencedObjCProp = [](const NamedDecl *D) ->
313                                       const ObjCPropertyDecl * {
314     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315       return MD->findPropertyDecl();
316     return nullptr;
317   };
318   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320       return true;
321   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322       return true;
323   }
324 
325   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326   // Only the variables omp_in and omp_out are allowed in the combiner.
327   // Only the variables omp_priv and omp_orig are allowed in the
328   // initializer-clause.
329   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331       isa<VarDecl>(D)) {
332     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333         << getCurFunction()->HasOMPDeclareReductionCombiner;
334     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335     return true;
336   }
337 
338   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339   //  List-items in map clauses on this construct may only refer to the declared
340   //  variable var and entities that could be referenced by a procedure defined
341   //  at the same location
342   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
344       isa<VarDecl>(D)) {
345     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346         << DMD->getVarName().getAsString();
347     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348     return true;
349   }
350 
351   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352                              AvoidPartialAvailabilityChecks, ClassReceiver);
353 
354   DiagnoseUnusedOfDecl(*this, D, Loc);
355 
356   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357 
358   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359     if (const auto *VD = dyn_cast<ValueDecl>(D))
360       checkDeviceDecl(VD, Loc);
361 
362     if (!Context.getTargetInfo().isTLSSupported())
363       if (const auto *VD = dyn_cast<VarDecl>(D))
364         if (VD->getTLSKind() != VarDecl::TLS_None)
365           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366   }
367 
368   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369       !isUnevaluatedContext()) {
370     // C++ [expr.prim.req.nested] p3
371     //   A local parameter shall only appear as an unevaluated operand
372     //   (Clause 8) within the constraint-expression.
373     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374         << D;
375     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376     return true;
377   }
378 
379   return false;
380 }
381 
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
385 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387                                  ArrayRef<Expr *> Args) {
388   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389   if (!attr)
390     return;
391 
392   // The number of formal parameters of the declaration.
393   unsigned numFormalParams;
394 
395   // The kind of declaration.  This is also an index into a %select in
396   // the diagnostic.
397   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398 
399   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400     numFormalParams = MD->param_size();
401     calleeType = CT_Method;
402   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403     numFormalParams = FD->param_size();
404     calleeType = CT_Function;
405   } else if (isa<VarDecl>(D)) {
406     QualType type = cast<ValueDecl>(D)->getType();
407     const FunctionType *fn = nullptr;
408     if (const PointerType *ptr = type->getAs<PointerType>()) {
409       fn = ptr->getPointeeType()->getAs<FunctionType>();
410       if (!fn) return;
411       calleeType = CT_Function;
412     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413       fn = ptr->getPointeeType()->castAs<FunctionType>();
414       calleeType = CT_Block;
415     } else {
416       return;
417     }
418 
419     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420       numFormalParams = proto->getNumParams();
421     } else {
422       numFormalParams = 0;
423     }
424   } else {
425     return;
426   }
427 
428   // "nullPos" is the number of formal parameters at the end which
429   // effectively count as part of the variadic arguments.  This is
430   // useful if you would prefer to not have *any* formal parameters,
431   // but the language forces you to have at least one.
432   unsigned nullPos = attr->getNullPos();
433   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435 
436   // The number of arguments which should follow the sentinel.
437   unsigned numArgsAfterSentinel = attr->getSentinel();
438 
439   // If there aren't enough arguments for all the formal parameters,
440   // the sentinel, and the args after the sentinel, complain.
441   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444     return;
445   }
446 
447   // Otherwise, find the sentinel expression.
448   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449   if (!sentinelExpr) return;
450   if (sentinelExpr->isValueDependent()) return;
451   if (Context.isSentinelNullExpr(sentinelExpr)) return;
452 
453   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
454   // or 'NULL' if those are actually defined in the context.  Only use
455   // 'nil' for ObjC methods, where it's much more likely that the
456   // variadic arguments form a list of object pointers.
457   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458   std::string NullValue;
459   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460     NullValue = "nil";
461   else if (getLangOpts().CPlusPlus11)
462     NullValue = "nullptr";
463   else if (PP.isMacroDefined("NULL"))
464     NullValue = "NULL";
465   else
466     NullValue = "(void*) 0";
467 
468   if (MissingNilLoc.isInvalid())
469     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470   else
471     Diag(MissingNilLoc, diag::warn_missing_sentinel)
472       << int(calleeType)
473       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475 }
476 
getExprRange(Expr * E) const477 SourceRange Sema::getExprRange(Expr *E) const {
478   return E ? E->getSourceRange() : SourceRange();
479 }
480 
481 //===----------------------------------------------------------------------===//
482 //  Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
484 
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487   // Handle any placeholder expressions which made it here.
488   if (E->getType()->isPlaceholderType()) {
489     ExprResult result = CheckPlaceholderExpr(E);
490     if (result.isInvalid()) return ExprError();
491     E = result.get();
492   }
493 
494   QualType Ty = E->getType();
495   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
496 
497   if (Ty->isFunctionType()) {
498     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501           return ExprError();
502 
503     E = ImpCastExprToType(E, Context.getPointerType(Ty),
504                           CK_FunctionToPointerDecay).get();
505   } else if (Ty->isArrayType()) {
506     // In C90 mode, arrays only promote to pointers if the array expression is
507     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508     // type 'array of type' is converted to an expression that has type 'pointer
509     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
510     // that has type 'array of type' ...".  The relevant change is "an lvalue"
511     // (C90) to "an expression" (C99).
512     //
513     // C++ 4.2p1:
514     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515     // T" can be converted to an rvalue of type "pointer to T".
516     //
517     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519                             CK_ArrayToPointerDecay).get();
520   }
521   return E;
522 }
523 
CheckForNullPointerDereference(Sema & S,Expr * E)524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525   // Check to see if we are dereferencing a null pointer.  If so,
526   // and if not volatile-qualified, this is undefined behavior that the
527   // optimizer will delete, so warn about it.  People sometimes try to use this
528   // to get a deterministic trap and are surprised by clang's behavior.  This
529   // only handles the pattern "*null", which is a very syntactic check.
530   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531   if (UO && UO->getOpcode() == UO_Deref &&
532       UO->getSubExpr()->getType()->isPointerType()) {
533     const LangAS AS =
534         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535     if ((!isTargetAddressSpace(AS) ||
536          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539         !UO->getType().isVolatileQualified()) {
540       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541                             S.PDiag(diag::warn_indirection_through_null)
542                                 << UO->getSubExpr()->getSourceRange());
543       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544                             S.PDiag(diag::note_indirection_through_null));
545     }
546   }
547 }
548 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550                                     SourceLocation AssignLoc,
551                                     const Expr* RHS) {
552   const ObjCIvarDecl *IV = OIRE->getDecl();
553   if (!IV)
554     return;
555 
556   DeclarationName MemberName = IV->getDeclName();
557   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558   if (!Member || !Member->isStr("isa"))
559     return;
560 
561   const Expr *Base = OIRE->getBase();
562   QualType BaseType = Base->getType();
563   if (OIRE->isArrow())
564     BaseType = BaseType->getPointeeType();
565   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567       ObjCInterfaceDecl *ClassDeclared = nullptr;
568       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569       if (!ClassDeclared->getSuperClass()
570           && (*ClassDeclared->ivar_begin()) == IV) {
571         if (RHS) {
572           NamedDecl *ObjectSetClass =
573             S.LookupSingleName(S.TUScope,
574                                &S.Context.Idents.get("object_setClass"),
575                                SourceLocation(), S.LookupOrdinaryName);
576           if (ObjectSetClass) {
577             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580                                               "object_setClass(")
581                 << FixItHint::CreateReplacement(
582                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584           }
585           else
586             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587         } else {
588           NamedDecl *ObjectGetClass =
589             S.LookupSingleName(S.TUScope,
590                                &S.Context.Idents.get("object_getClass"),
591                                SourceLocation(), S.LookupOrdinaryName);
592           if (ObjectGetClass)
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595                                               "object_getClass(")
596                 << FixItHint::CreateReplacement(
597                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598           else
599             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600         }
601         S.Diag(IV->getLocation(), diag::note_ivar_decl);
602       }
603     }
604 }
605 
DefaultLvalueConversion(Expr * E)606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607   if (E->getType().getQualifiers().hasOutput()) {
608     return ExprError(Diag(E->getExprLoc(), diag::err_typecheck_read_output)
609       << E->getSourceRange());
610   }
611 
612   // Handle any placeholder expressions which made it here.
613   if (E->getType()->isPlaceholderType()) {
614     ExprResult result = CheckPlaceholderExpr(E);
615     if (result.isInvalid()) return ExprError();
616     E = result.get();
617   }
618 
619   // C++ [conv.lval]p1:
620   //   A glvalue of a non-function, non-array type T can be
621   //   converted to a prvalue.
622   if (!E->isGLValue()) return E;
623 
624   QualType T = E->getType();
625   assert(!T.isNull() && "r-value conversion on typeless expression?");
626 
627   // lvalue-to-rvalue conversion cannot be applied to function or array types.
628   if (T->isFunctionType() || T->isArrayType())
629     return E;
630 
631   // We don't want to throw lvalue-to-rvalue casts on top of
632   // expressions of certain types in C++.
633   if (getLangOpts().CPlusPlus &&
634       (E->getType() == Context.OverloadTy ||
635        T->isDependentType() ||
636        T->isRecordType()))
637     return E;
638 
639   // The C standard is actually really unclear on this point, and
640   // DR106 tells us what the result should be but not why.  It's
641   // generally best to say that void types just doesn't undergo
642   // lvalue-to-rvalue at all.  Note that expressions of unqualified
643   // 'void' type are never l-values, but qualified void can be.
644   if (T->isVoidType())
645     return E;
646 
647   // OpenCL usually rejects direct accesses to values of 'half' type.
648   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
649       T->isHalfType()) {
650     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
651       << 0 << T;
652     return ExprError();
653   }
654 
655   CheckForNullPointerDereference(*this, E);
656   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
657     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
658                                      &Context.Idents.get("object_getClass"),
659                                      SourceLocation(), LookupOrdinaryName);
660     if (ObjectGetClass)
661       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
662           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
663           << FixItHint::CreateReplacement(
664                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
665     else
666       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
667   }
668   else if (const ObjCIvarRefExpr *OIRE =
669             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
670     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
671 
672   // C++ [conv.lval]p1:
673   //   [...] If T is a non-class type, the type of the prvalue is the
674   //   cv-unqualified version of T. Otherwise, the type of the
675   //   rvalue is T.
676   //
677   // C99 6.3.2.1p2:
678   //   If the lvalue has qualified type, the value has the unqualified
679   //   version of the type of the lvalue; otherwise, the value has the
680   //   type of the lvalue.
681   if (T.hasQualifiers())
682     T = T.getUnqualifiedType();
683 
684   // Under the MS ABI, lock down the inheritance model now.
685   if (T->isMemberPointerType() &&
686       Context.getTargetInfo().getCXXABI().isMicrosoft())
687     (void)isCompleteType(E->getExprLoc(), T);
688 
689   ExprResult Res = CheckLValueToRValueConversionOperand(E);
690   if (Res.isInvalid())
691     return Res;
692   E = Res.get();
693 
694   // Loading a __weak object implicitly retains the value, so we need a cleanup to
695   // balance that.
696   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
697     Cleanup.setExprNeedsCleanups(true);
698 
699   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
700     Cleanup.setExprNeedsCleanups(true);
701 
702   // C++ [conv.lval]p3:
703   //   If T is cv std::nullptr_t, the result is a null pointer constant.
704   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
705   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
706 
707   // C11 6.3.2.1p2:
708   //   ... if the lvalue has atomic type, the value has the non-atomic version
709   //   of the type of the lvalue ...
710   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
711     T = Atomic->getValueType().getUnqualifiedType();
712     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
713                                    nullptr, VK_RValue);
714   }
715 
716   return Res;
717 }
718 
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)719 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
720   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
721   if (Res.isInvalid())
722     return ExprError();
723   Res = DefaultLvalueConversion(Res.get());
724   if (Res.isInvalid())
725     return ExprError();
726   return Res;
727 }
728 
729 /// CallExprUnaryConversions - a special case of an unary conversion
730 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)731 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
732   QualType Ty = E->getType();
733   ExprResult Res = E;
734   // Only do implicit cast for a function type, but not for a pointer
735   // to function type.
736   if (Ty->isFunctionType()) {
737     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
738                             CK_FunctionToPointerDecay);
739     if (Res.isInvalid())
740       return ExprError();
741   }
742   Res = DefaultLvalueConversion(Res.get());
743   if (Res.isInvalid())
744     return ExprError();
745   return Res.get();
746 }
747 
748 /// UsualUnaryConversions - Performs various conversions that are common to most
749 /// operators (C99 6.3). The conversions of array and function types are
750 /// sometimes suppressed. For example, the array->pointer conversion doesn't
751 /// apply if the array is an argument to the sizeof or address (&) operators.
752 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)753 ExprResult Sema::UsualUnaryConversions(Expr *E) {
754   // First, convert to an r-value.
755   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
756   if (Res.isInvalid())
757     return ExprError();
758   E = Res.get();
759 
760   QualType Ty = E->getType();
761   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
762 
763   // Half FP have to be promoted to float unless it is natively supported
764   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
765     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
766 
767   // Try to perform integral promotions if the object has a theoretically
768   // promotable type.
769   if (Ty->isIntegralOrUnscopedEnumerationType()) {
770     // C99 6.3.1.1p2:
771     //
772     //   The following may be used in an expression wherever an int or
773     //   unsigned int may be used:
774     //     - an object or expression with an integer type whose integer
775     //       conversion rank is less than or equal to the rank of int
776     //       and unsigned int.
777     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
778     //
779     //   If an int can represent all values of the original type, the
780     //   value is converted to an int; otherwise, it is converted to an
781     //   unsigned int. These are called the integer promotions. All
782     //   other types are unchanged by the integer promotions.
783 
784     QualType PTy = Context.isPromotableBitField(E);
785     if (!PTy.isNull()) {
786       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
787       return E;
788     }
789     if (Ty->isPromotableIntegerType()) {
790       QualType PT = Context.getPromotedIntegerType(Ty);
791       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
792       return E;
793     }
794   }
795   return E;
796 }
797 
798 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
799 /// do not have a prototype. Arguments that have type float or __fp16
800 /// are promoted to double. All other argument types are converted by
801 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)802 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
803   QualType Ty = E->getType();
804   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
805 
806   ExprResult Res = UsualUnaryConversions(E);
807   if (Res.isInvalid())
808     return ExprError();
809   E = Res.get();
810 
811   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
812   // promote to double.
813   // Note that default argument promotion applies only to float (and
814   // half/fp16); it does not apply to _Float16.
815   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
816   if (BTy && (BTy->getKind() == BuiltinType::Half ||
817               BTy->getKind() == BuiltinType::Float)) {
818     if (getLangOpts().OpenCL &&
819         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
820         if (BTy->getKind() == BuiltinType::Half) {
821             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
822         }
823     } else {
824       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
825     }
826   }
827 
828   // C++ performs lvalue-to-rvalue conversion as a default argument
829   // promotion, even on class types, but note:
830   //   C++11 [conv.lval]p2:
831   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
832   //     operand or a subexpression thereof the value contained in the
833   //     referenced object is not accessed. Otherwise, if the glvalue
834   //     has a class type, the conversion copy-initializes a temporary
835   //     of type T from the glvalue and the result of the conversion
836   //     is a prvalue for the temporary.
837   // FIXME: add some way to gate this entire thing for correctness in
838   // potentially potentially evaluated contexts.
839   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
840     ExprResult Temp = PerformCopyInitialization(
841                        InitializedEntity::InitializeTemporary(E->getType()),
842                                                 E->getExprLoc(), E);
843     if (Temp.isInvalid())
844       return ExprError();
845     E = Temp.get();
846   }
847 
848   return E;
849 }
850 
851 /// Determine the degree of POD-ness for an expression.
852 /// Incomplete types are considered POD, since this check can be performed
853 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)854 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
855   if (Ty->isIncompleteType()) {
856     // C++11 [expr.call]p7:
857     //   After these conversions, if the argument does not have arithmetic,
858     //   enumeration, pointer, pointer to member, or class type, the program
859     //   is ill-formed.
860     //
861     // Since we've already performed array-to-pointer and function-to-pointer
862     // decay, the only such type in C++ is cv void. This also handles
863     // initializer lists as variadic arguments.
864     if (Ty->isVoidType())
865       return VAK_Invalid;
866 
867     if (Ty->isObjCObjectType())
868       return VAK_Invalid;
869     return VAK_Valid;
870   }
871 
872   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
873     return VAK_Invalid;
874 
875   if (Ty.isCXX98PODType(Context))
876     return VAK_Valid;
877 
878   // C++11 [expr.call]p7:
879   //   Passing a potentially-evaluated argument of class type (Clause 9)
880   //   having a non-trivial copy constructor, a non-trivial move constructor,
881   //   or a non-trivial destructor, with no corresponding parameter,
882   //   is conditionally-supported with implementation-defined semantics.
883   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
884     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
885       if (!Record->hasNonTrivialCopyConstructor() &&
886           !Record->hasNonTrivialMoveConstructor() &&
887           !Record->hasNonTrivialDestructor())
888         return VAK_ValidInCXX11;
889 
890   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891     return VAK_Valid;
892 
893   if (Ty->isObjCObjectType())
894     return VAK_Invalid;
895 
896   if (getLangOpts().MSVCCompat)
897     return VAK_MSVCUndefined;
898 
899   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900   // permitted to reject them. We should consider doing so.
901   return VAK_Undefined;
902 }
903 
checkVariadicArgument(const Expr * E,VariadicCallType CT)904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
905   // Don't allow one to pass an Objective-C interface to a vararg.
906   const QualType &Ty = E->getType();
907   VarArgKind VAK = isValidVarArgType(Ty);
908 
909   // Complain about passing non-POD types through varargs.
910   switch (VAK) {
911   case VAK_ValidInCXX11:
912     DiagRuntimeBehavior(
913         E->getBeginLoc(), nullptr,
914         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
915     LLVM_FALLTHROUGH;
916   case VAK_Valid:
917     if (Ty->isRecordType()) {
918       // This is unlikely to be what the user intended. If the class has a
919       // 'c_str' member function, the user probably meant to call that.
920       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
921                           PDiag(diag::warn_pass_class_arg_to_vararg)
922                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
923     }
924     break;
925 
926   case VAK_Undefined:
927   case VAK_MSVCUndefined:
928     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
929                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
930                             << getLangOpts().CPlusPlus11 << Ty << CT);
931     break;
932 
933   case VAK_Invalid:
934     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
935       Diag(E->getBeginLoc(),
936            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
937           << Ty << CT;
938     else if (Ty->isObjCObjectType())
939       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
940                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
941                               << Ty << CT);
942     else
943       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
944           << isa<InitListExpr>(E) << Ty << CT;
945     break;
946   }
947 }
948 
949 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
950 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)951 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
952                                                   FunctionDecl *FDecl) {
953   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
954     // Strip the unbridged-cast placeholder expression off, if applicable.
955     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
956         (CT == VariadicMethod ||
957          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
958       E = stripARCUnbridgedCast(E);
959 
960     // Otherwise, do normal placeholder checking.
961     } else {
962       ExprResult ExprRes = CheckPlaceholderExpr(E);
963       if (ExprRes.isInvalid())
964         return ExprError();
965       E = ExprRes.get();
966     }
967   }
968 
969   ExprResult ExprRes = DefaultArgumentPromotion(E);
970   if (ExprRes.isInvalid())
971     return ExprError();
972 
973   // Copy blocks to the heap.
974   if (ExprRes.get()->getType()->isBlockPointerType())
975     maybeExtendBlockObject(ExprRes);
976 
977   E = ExprRes.get();
978 
979   // Diagnostics regarding non-POD argument types are
980   // emitted along with format string checking in Sema::CheckFunctionCall().
981   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
982     // Turn this into a trap.
983     CXXScopeSpec SS;
984     SourceLocation TemplateKWLoc;
985     UnqualifiedId Name;
986     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
987                        E->getBeginLoc());
988     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
989                                           /*HasTrailingLParen=*/true,
990                                           /*IsAddressOfOperand=*/false);
991     if (TrapFn.isInvalid())
992       return ExprError();
993 
994     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
995                                     None, E->getEndLoc());
996     if (Call.isInvalid())
997       return ExprError();
998 
999     ExprResult Comma =
1000         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1001     if (Comma.isInvalid())
1002       return ExprError();
1003     return Comma.get();
1004   }
1005 
1006   if (!getLangOpts().CPlusPlus &&
1007       RequireCompleteType(E->getExprLoc(), E->getType(),
1008                           diag::err_call_incomplete_argument))
1009     return ExprError();
1010 
1011   return E;
1012 }
1013 
1014 /// Converts an integer to complex float type.  Helper function of
1015 /// UsualArithmeticConversions()
1016 ///
1017 /// \return false if the integer expression is an integer type and is
1018 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1020                                                   ExprResult &ComplexExpr,
1021                                                   QualType IntTy,
1022                                                   QualType ComplexTy,
1023                                                   bool SkipCast) {
1024   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1025   if (SkipCast) return false;
1026   if (IntTy->isIntegerType()) {
1027     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1029     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030                                   CK_FloatingRealToComplex);
1031   } else {
1032     assert(IntTy->isComplexIntegerType());
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1034                                   CK_IntegralComplexToFloatingComplex);
1035   }
1036   return false;
1037 }
1038 
1039 /// Handle arithmetic conversion with complex types.  Helper function of
1040 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1042                                              ExprResult &RHS, QualType LHSType,
1043                                              QualType RHSType,
1044                                              bool IsCompAssign) {
1045   // if we have an integer operand, the result is the complex type.
1046   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1047                                              /*skipCast*/false))
1048     return LHSType;
1049   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1050                                              /*skipCast*/IsCompAssign))
1051     return RHSType;
1052 
1053   // This handles complex/complex, complex/float, or float/complex.
1054   // When both operands are complex, the shorter operand is converted to the
1055   // type of the longer, and that is the type of the result. This corresponds
1056   // to what is done when combining two real floating-point operands.
1057   // The fun begins when size promotion occur across type domains.
1058   // From H&S 6.3.4: When one operand is complex and the other is a real
1059   // floating-point type, the less precise type is converted, within it's
1060   // real or complex domain, to the precision of the other type. For example,
1061   // when combining a "long double" with a "double _Complex", the
1062   // "double _Complex" is promoted to "long double _Complex".
1063 
1064   // Compute the rank of the two types, regardless of whether they are complex.
1065   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1066 
1067   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1068   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1069   QualType LHSElementType =
1070       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1071   QualType RHSElementType =
1072       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1073 
1074   QualType ResultType = S.Context.getComplexType(LHSElementType);
1075   if (Order < 0) {
1076     // Promote the precision of the LHS if not an assignment.
1077     ResultType = S.Context.getComplexType(RHSElementType);
1078     if (!IsCompAssign) {
1079       if (LHSComplexType)
1080         LHS =
1081             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1082       else
1083         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1084     }
1085   } else if (Order > 0) {
1086     // Promote the precision of the RHS.
1087     if (RHSComplexType)
1088       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1089     else
1090       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1091   }
1092   return ResultType;
1093 }
1094 
1095 /// Handle arithmetic conversion from integer to float.  Helper function
1096 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1098                                            ExprResult &IntExpr,
1099                                            QualType FloatTy, QualType IntTy,
1100                                            bool ConvertFloat, bool ConvertInt) {
1101   if (IntTy->isIntegerType()) {
1102     if (ConvertInt)
1103       // Convert intExpr to the lhs floating point type.
1104       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1105                                     CK_IntegralToFloating);
1106     return FloatTy;
1107   }
1108 
1109   // Convert both sides to the appropriate complex float.
1110   assert(IntTy->isComplexIntegerType());
1111   QualType result = S.Context.getComplexType(FloatTy);
1112 
1113   // _Complex int -> _Complex float
1114   if (ConvertInt)
1115     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1116                                   CK_IntegralComplexToFloatingComplex);
1117 
1118   // float -> _Complex float
1119   if (ConvertFloat)
1120     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1121                                     CK_FloatingRealToComplex);
1122 
1123   return result;
1124 }
1125 
1126 /// Handle arithmethic conversion with floating point types.  Helper
1127 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1129                                       ExprResult &RHS, QualType LHSType,
1130                                       QualType RHSType, bool IsCompAssign) {
1131   bool LHSFloat = LHSType->isRealFloatingType();
1132   bool RHSFloat = RHSType->isRealFloatingType();
1133 
1134   // If we have two real floating types, convert the smaller operand
1135   // to the bigger result.
1136   if (LHSFloat && RHSFloat) {
1137     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1138     if (order > 0) {
1139       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1140       return LHSType;
1141     }
1142 
1143     assert(order < 0 && "illegal float comparison");
1144     if (!IsCompAssign)
1145       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1146     return RHSType;
1147   }
1148 
1149   if (LHSFloat) {
1150     // Half FP has to be promoted to float unless it is natively supported
1151     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1152       LHSType = S.Context.FloatTy;
1153 
1154     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1155                                       /*ConvertFloat=*/!IsCompAssign,
1156                                       /*ConvertInt=*/ true);
1157   }
1158   assert(RHSFloat);
1159   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160                                     /*convertInt=*/ true,
1161                                     /*convertFloat=*/!IsCompAssign);
1162 }
1163 
1164 /// Diagnose attempts to convert between __float128 and long double if
1165 /// there is no support for such conversion. Helper function of
1166 /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1168                                       QualType RHSType) {
1169   /*  No issue converting if at least one of the types is not a floating point
1170       type or the two types have the same rank.
1171   */
1172   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1173       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1174     return false;
1175 
1176   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1177          "The remaining types must be floating point types.");
1178 
1179   auto *LHSComplex = LHSType->getAs<ComplexType>();
1180   auto *RHSComplex = RHSType->getAs<ComplexType>();
1181 
1182   QualType LHSElemType = LHSComplex ?
1183     LHSComplex->getElementType() : LHSType;
1184   QualType RHSElemType = RHSComplex ?
1185     RHSComplex->getElementType() : RHSType;
1186 
1187   // No issue if the two types have the same representation
1188   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1189       &S.Context.getFloatTypeSemantics(RHSElemType))
1190     return false;
1191 
1192   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1193                                 RHSElemType == S.Context.LongDoubleTy);
1194   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1195                             RHSElemType == S.Context.Float128Ty);
1196 
1197   // We've handled the situation where __float128 and long double have the same
1198   // representation. We allow all conversions for all possible long double types
1199   // except PPC's double double.
1200   return Float128AndLongDouble &&
1201     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1202      &llvm::APFloat::PPCDoubleDouble());
1203 }
1204 
1205 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1206 
1207 namespace {
1208 /// These helper callbacks are placed in an anonymous namespace to
1209 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1210 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1211   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1212 }
1213 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1214 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1215   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1216                              CK_IntegralComplexCast);
1217 }
1218 }
1219 
1220 /// Handle integer arithmetic conversions.  Helper function of
1221 /// UsualArithmeticConversions()
1222 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1223 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1224                                         ExprResult &RHS, QualType LHSType,
1225                                         QualType RHSType, bool IsCompAssign) {
1226   // The rules for this case are in C99 6.3.1.8
1227   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1228   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1229   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1230   if (LHSSigned == RHSSigned) {
1231     // Same signedness; use the higher-ranked type
1232     if (order >= 0) {
1233       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1234       return LHSType;
1235     } else if (!IsCompAssign)
1236       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1237     return RHSType;
1238   } else if (order != (LHSSigned ? 1 : -1)) {
1239     // The unsigned type has greater than or equal rank to the
1240     // signed type, so use the unsigned type
1241     if (RHSSigned) {
1242       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1243       return LHSType;
1244     } else if (!IsCompAssign)
1245       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1246     return RHSType;
1247   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1248     // The two types are different widths; if we are here, that
1249     // means the signed type is larger than the unsigned type, so
1250     // use the signed type.
1251     if (LHSSigned) {
1252       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1253       return LHSType;
1254     } else if (!IsCompAssign)
1255       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1256     return RHSType;
1257   } else {
1258     // The signed type is higher-ranked than the unsigned type,
1259     // but isn't actually any bigger (like unsigned int and long
1260     // on most 32-bit systems).  Use the unsigned type corresponding
1261     // to the signed type.
1262     QualType result =
1263       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1264     RHS = (*doRHSCast)(S, RHS.get(), result);
1265     if (!IsCompAssign)
1266       LHS = (*doLHSCast)(S, LHS.get(), result);
1267     return result;
1268   }
1269 }
1270 
1271 /// Handle conversions with GCC complex int extension.  Helper function
1272 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1273 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1274                                            ExprResult &RHS, QualType LHSType,
1275                                            QualType RHSType,
1276                                            bool IsCompAssign) {
1277   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1278   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1279 
1280   if (LHSComplexInt && RHSComplexInt) {
1281     QualType LHSEltType = LHSComplexInt->getElementType();
1282     QualType RHSEltType = RHSComplexInt->getElementType();
1283     QualType ScalarType =
1284       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1285         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1286 
1287     return S.Context.getComplexType(ScalarType);
1288   }
1289 
1290   if (LHSComplexInt) {
1291     QualType LHSEltType = LHSComplexInt->getElementType();
1292     QualType ScalarType =
1293       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1294         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1295     QualType ComplexType = S.Context.getComplexType(ScalarType);
1296     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1297                               CK_IntegralRealToComplex);
1298 
1299     return ComplexType;
1300   }
1301 
1302   assert(RHSComplexInt);
1303 
1304   QualType RHSEltType = RHSComplexInt->getElementType();
1305   QualType ScalarType =
1306     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1307       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1308   QualType ComplexType = S.Context.getComplexType(ScalarType);
1309 
1310   if (!IsCompAssign)
1311     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1312                               CK_IntegralRealToComplex);
1313   return ComplexType;
1314 }
1315 
1316 /// Return the rank of a given fixed point or integer type. The value itself
1317 /// doesn't matter, but the values must be increasing with proper increasing
1318 /// rank as described in N1169 4.1.1.
GetFixedPointRank(QualType Ty)1319 static unsigned GetFixedPointRank(QualType Ty) {
1320   const auto *BTy = Ty->getAs<BuiltinType>();
1321   assert(BTy && "Expected a builtin type.");
1322 
1323   switch (BTy->getKind()) {
1324   case BuiltinType::ShortFract:
1325   case BuiltinType::UShortFract:
1326   case BuiltinType::SatShortFract:
1327   case BuiltinType::SatUShortFract:
1328     return 1;
1329   case BuiltinType::Fract:
1330   case BuiltinType::UFract:
1331   case BuiltinType::SatFract:
1332   case BuiltinType::SatUFract:
1333     return 2;
1334   case BuiltinType::LongFract:
1335   case BuiltinType::ULongFract:
1336   case BuiltinType::SatLongFract:
1337   case BuiltinType::SatULongFract:
1338     return 3;
1339   case BuiltinType::ShortAccum:
1340   case BuiltinType::UShortAccum:
1341   case BuiltinType::SatShortAccum:
1342   case BuiltinType::SatUShortAccum:
1343     return 4;
1344   case BuiltinType::Accum:
1345   case BuiltinType::UAccum:
1346   case BuiltinType::SatAccum:
1347   case BuiltinType::SatUAccum:
1348     return 5;
1349   case BuiltinType::LongAccum:
1350   case BuiltinType::ULongAccum:
1351   case BuiltinType::SatLongAccum:
1352   case BuiltinType::SatULongAccum:
1353     return 6;
1354   default:
1355     if (BTy->isInteger())
1356       return 0;
1357     llvm_unreachable("Unexpected fixed point or integer type");
1358   }
1359 }
1360 
1361 /// handleFixedPointConversion - Fixed point operations between fixed
1362 /// point types and integers or other fixed point types do not fall under
1363 /// usual arithmetic conversion since these conversions could result in loss
1364 /// of precsision (N1169 4.1.4). These operations should be calculated with
1365 /// the full precision of their result type (N1169 4.1.6.2.1).
handleFixedPointConversion(Sema & S,QualType LHSTy,QualType RHSTy)1366 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1367                                            QualType RHSTy) {
1368   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1369          "Expected at least one of the operands to be a fixed point type");
1370   assert((LHSTy->isFixedPointOrIntegerType() ||
1371           RHSTy->isFixedPointOrIntegerType()) &&
1372          "Special fixed point arithmetic operation conversions are only "
1373          "applied to ints or other fixed point types");
1374 
1375   // If one operand has signed fixed-point type and the other operand has
1376   // unsigned fixed-point type, then the unsigned fixed-point operand is
1377   // converted to its corresponding signed fixed-point type and the resulting
1378   // type is the type of the converted operand.
1379   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1380     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1381   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1382     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1383 
1384   // The result type is the type with the highest rank, whereby a fixed-point
1385   // conversion rank is always greater than an integer conversion rank; if the
1386   // type of either of the operands is a saturating fixedpoint type, the result
1387   // type shall be the saturating fixed-point type corresponding to the type
1388   // with the highest rank; the resulting value is converted (taking into
1389   // account rounding and overflow) to the precision of the resulting type.
1390   // Same ranks between signed and unsigned types are resolved earlier, so both
1391   // types are either signed or both unsigned at this point.
1392   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1393   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1394 
1395   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1396 
1397   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1398     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1399 
1400   return ResultTy;
1401 }
1402 
1403 /// Check that the usual arithmetic conversions can be performed on this pair of
1404 /// expressions that might be of enumeration type.
checkEnumArithmeticConversions(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc,Sema::ArithConvKind ACK)1405 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1406                                            SourceLocation Loc,
1407                                            Sema::ArithConvKind ACK) {
1408   // C++2a [expr.arith.conv]p1:
1409   //   If one operand is of enumeration type and the other operand is of a
1410   //   different enumeration type or a floating-point type, this behavior is
1411   //   deprecated ([depr.arith.conv.enum]).
1412   //
1413   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1414   // Eventually we will presumably reject these cases (in C++23 onwards?).
1415   QualType L = LHS->getType(), R = RHS->getType();
1416   bool LEnum = L->isUnscopedEnumerationType(),
1417        REnum = R->isUnscopedEnumerationType();
1418   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1419   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1420       (REnum && L->isFloatingType())) {
1421     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1422                     ? diag::warn_arith_conv_enum_float_cxx20
1423                     : diag::warn_arith_conv_enum_float)
1424         << LHS->getSourceRange() << RHS->getSourceRange()
1425         << (int)ACK << LEnum << L << R;
1426   } else if (!IsCompAssign && LEnum && REnum &&
1427              !S.Context.hasSameUnqualifiedType(L, R)) {
1428     unsigned DiagID;
1429     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1430         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1431       // If either enumeration type is unnamed, it's less likely that the
1432       // user cares about this, but this situation is still deprecated in
1433       // C++2a. Use a different warning group.
1434       DiagID = S.getLangOpts().CPlusPlus20
1435                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1436                     : diag::warn_arith_conv_mixed_anon_enum_types;
1437     } else if (ACK == Sema::ACK_Conditional) {
1438       // Conditional expressions are separated out because they have
1439       // historically had a different warning flag.
1440       DiagID = S.getLangOpts().CPlusPlus20
1441                    ? diag::warn_conditional_mixed_enum_types_cxx20
1442                    : diag::warn_conditional_mixed_enum_types;
1443     } else if (ACK == Sema::ACK_Comparison) {
1444       // Comparison expressions are separated out because they have
1445       // historically had a different warning flag.
1446       DiagID = S.getLangOpts().CPlusPlus20
1447                    ? diag::warn_comparison_mixed_enum_types_cxx20
1448                    : diag::warn_comparison_mixed_enum_types;
1449     } else {
1450       DiagID = S.getLangOpts().CPlusPlus20
1451                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1452                    : diag::warn_arith_conv_mixed_enum_types;
1453     }
1454     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1455                         << (int)ACK << L << R;
1456   }
1457 }
1458 
1459 /// UsualArithmeticConversions - Performs various conversions that are common to
1460 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1461 /// routine returns the first non-arithmetic type found. The client is
1462 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,ArithConvKind ACK)1463 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1464                                           SourceLocation Loc,
1465                                           ArithConvKind ACK) {
1466   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1467 
1468   if (ACK != ACK_CompAssign) {
1469     LHS = UsualUnaryConversions(LHS.get());
1470     if (LHS.isInvalid())
1471       return QualType();
1472   }
1473 
1474   RHS = UsualUnaryConversions(RHS.get());
1475   if (RHS.isInvalid())
1476     return QualType();
1477 
1478   // For conversion purposes, we ignore any qualifiers.
1479   // For example, "const float" and "float" are equivalent.
1480   QualType LHSType =
1481     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1482   QualType RHSType =
1483     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1484 
1485   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1486   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1487     LHSType = AtomicLHS->getValueType();
1488 
1489   // If both types are identical, no conversion is needed.
1490   if (LHSType == RHSType)
1491     return LHSType;
1492 
1493   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1494   // The caller can deal with this (e.g. pointer + int).
1495   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1496     return QualType();
1497 
1498   // Apply unary and bitfield promotions to the LHS's type.
1499   QualType LHSUnpromotedType = LHSType;
1500   if (LHSType->isPromotableIntegerType())
1501     LHSType = Context.getPromotedIntegerType(LHSType);
1502   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1503   if (!LHSBitfieldPromoteTy.isNull())
1504     LHSType = LHSBitfieldPromoteTy;
1505   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1506     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1507 
1508   // If both types are identical, no conversion is needed.
1509   if (LHSType == RHSType)
1510     return LHSType;
1511 
1512   // ExtInt types aren't subject to conversions between them or normal integers,
1513   // so this fails.
1514   if(LHSType->isExtIntType() || RHSType->isExtIntType())
1515     return QualType();
1516 
1517   // At this point, we have two different arithmetic types.
1518 
1519   // Diagnose attempts to convert between __float128 and long double where
1520   // such conversions currently can't be handled.
1521   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1522     return QualType();
1523 
1524   // Handle complex types first (C99 6.3.1.8p1).
1525   if (LHSType->isComplexType() || RHSType->isComplexType())
1526     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527                                         ACK == ACK_CompAssign);
1528 
1529   // Now handle "real" floating types (i.e. float, double, long double).
1530   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1531     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1532                                  ACK == ACK_CompAssign);
1533 
1534   // Handle GCC complex int extension.
1535   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1536     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1537                                       ACK == ACK_CompAssign);
1538 
1539   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1540     return handleFixedPointConversion(*this, LHSType, RHSType);
1541 
1542   // Finally, we have two differing integer types.
1543   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1544            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1545 }
1546 
1547 //===----------------------------------------------------------------------===//
1548 //  Semantic Analysis for various Expression Types
1549 //===----------------------------------------------------------------------===//
1550 
1551 
1552 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1553 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1554                                 SourceLocation DefaultLoc,
1555                                 SourceLocation RParenLoc,
1556                                 Expr *ControllingExpr,
1557                                 ArrayRef<ParsedType> ArgTypes,
1558                                 ArrayRef<Expr *> ArgExprs) {
1559   unsigned NumAssocs = ArgTypes.size();
1560   assert(NumAssocs == ArgExprs.size());
1561 
1562   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1563   for (unsigned i = 0; i < NumAssocs; ++i) {
1564     if (ArgTypes[i])
1565       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1566     else
1567       Types[i] = nullptr;
1568   }
1569 
1570   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1571                                              ControllingExpr,
1572                                              llvm::makeArrayRef(Types, NumAssocs),
1573                                              ArgExprs);
1574   delete [] Types;
1575   return ER;
1576 }
1577 
1578 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1579 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1580                                  SourceLocation DefaultLoc,
1581                                  SourceLocation RParenLoc,
1582                                  Expr *ControllingExpr,
1583                                  ArrayRef<TypeSourceInfo *> Types,
1584                                  ArrayRef<Expr *> Exprs) {
1585   unsigned NumAssocs = Types.size();
1586   assert(NumAssocs == Exprs.size());
1587 
1588   // Decay and strip qualifiers for the controlling expression type, and handle
1589   // placeholder type replacement. See committee discussion from WG14 DR423.
1590   {
1591     EnterExpressionEvaluationContext Unevaluated(
1592         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1593     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1594     if (R.isInvalid())
1595       return ExprError();
1596     ControllingExpr = R.get();
1597   }
1598 
1599   // The controlling expression is an unevaluated operand, so side effects are
1600   // likely unintended.
1601   if (!inTemplateInstantiation() &&
1602       ControllingExpr->HasSideEffects(Context, false))
1603     Diag(ControllingExpr->getExprLoc(),
1604          diag::warn_side_effects_unevaluated_context);
1605 
1606   bool TypeErrorFound = false,
1607        IsResultDependent = ControllingExpr->isTypeDependent(),
1608        ContainsUnexpandedParameterPack
1609          = ControllingExpr->containsUnexpandedParameterPack();
1610 
1611   for (unsigned i = 0; i < NumAssocs; ++i) {
1612     if (Exprs[i]->containsUnexpandedParameterPack())
1613       ContainsUnexpandedParameterPack = true;
1614 
1615     if (Types[i]) {
1616       if (Types[i]->getType()->containsUnexpandedParameterPack())
1617         ContainsUnexpandedParameterPack = true;
1618 
1619       if (Types[i]->getType()->isDependentType()) {
1620         IsResultDependent = true;
1621       } else {
1622         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1623         // complete object type other than a variably modified type."
1624         unsigned D = 0;
1625         if (Types[i]->getType()->isIncompleteType())
1626           D = diag::err_assoc_type_incomplete;
1627         else if (!Types[i]->getType()->isObjectType())
1628           D = diag::err_assoc_type_nonobject;
1629         else if (Types[i]->getType()->isVariablyModifiedType())
1630           D = diag::err_assoc_type_variably_modified;
1631 
1632         if (D != 0) {
1633           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1634             << Types[i]->getTypeLoc().getSourceRange()
1635             << Types[i]->getType();
1636           TypeErrorFound = true;
1637         }
1638 
1639         // C11 6.5.1.1p2 "No two generic associations in the same generic
1640         // selection shall specify compatible types."
1641         for (unsigned j = i+1; j < NumAssocs; ++j)
1642           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1643               Context.typesAreCompatible(Types[i]->getType(),
1644                                          Types[j]->getType())) {
1645             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1646                  diag::err_assoc_compatible_types)
1647               << Types[j]->getTypeLoc().getSourceRange()
1648               << Types[j]->getType()
1649               << Types[i]->getType();
1650             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1651                  diag::note_compat_assoc)
1652               << Types[i]->getTypeLoc().getSourceRange()
1653               << Types[i]->getType();
1654             TypeErrorFound = true;
1655           }
1656       }
1657     }
1658   }
1659   if (TypeErrorFound)
1660     return ExprError();
1661 
1662   // If we determined that the generic selection is result-dependent, don't
1663   // try to compute the result expression.
1664   if (IsResultDependent)
1665     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1666                                         Exprs, DefaultLoc, RParenLoc,
1667                                         ContainsUnexpandedParameterPack);
1668 
1669   SmallVector<unsigned, 1> CompatIndices;
1670   unsigned DefaultIndex = -1U;
1671   for (unsigned i = 0; i < NumAssocs; ++i) {
1672     if (!Types[i])
1673       DefaultIndex = i;
1674     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1675                                         Types[i]->getType()))
1676       CompatIndices.push_back(i);
1677   }
1678 
1679   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1680   // type compatible with at most one of the types named in its generic
1681   // association list."
1682   if (CompatIndices.size() > 1) {
1683     // We strip parens here because the controlling expression is typically
1684     // parenthesized in macro definitions.
1685     ControllingExpr = ControllingExpr->IgnoreParens();
1686     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1687         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1688         << (unsigned)CompatIndices.size();
1689     for (unsigned I : CompatIndices) {
1690       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1691            diag::note_compat_assoc)
1692         << Types[I]->getTypeLoc().getSourceRange()
1693         << Types[I]->getType();
1694     }
1695     return ExprError();
1696   }
1697 
1698   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1699   // its controlling expression shall have type compatible with exactly one of
1700   // the types named in its generic association list."
1701   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1702     // We strip parens here because the controlling expression is typically
1703     // parenthesized in macro definitions.
1704     ControllingExpr = ControllingExpr->IgnoreParens();
1705     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1706         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1707     return ExprError();
1708   }
1709 
1710   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1711   // type name that is compatible with the type of the controlling expression,
1712   // then the result expression of the generic selection is the expression
1713   // in that generic association. Otherwise, the result expression of the
1714   // generic selection is the expression in the default generic association."
1715   unsigned ResultIndex =
1716     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1717 
1718   return GenericSelectionExpr::Create(
1719       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1720       ContainsUnexpandedParameterPack, ResultIndex);
1721 }
1722 
1723 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1724 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1725 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1726                                      unsigned Offset) {
1727   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1728                                         S.getLangOpts());
1729 }
1730 
1731 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1732 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
BuildCookedLiteralOperatorCall(Sema & S,Scope * Scope,IdentifierInfo * UDSuffix,SourceLocation UDSuffixLoc,ArrayRef<Expr * > Args,SourceLocation LitEndLoc)1733 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1734                                                  IdentifierInfo *UDSuffix,
1735                                                  SourceLocation UDSuffixLoc,
1736                                                  ArrayRef<Expr*> Args,
1737                                                  SourceLocation LitEndLoc) {
1738   assert(Args.size() <= 2 && "too many arguments for literal operator");
1739 
1740   QualType ArgTy[2];
1741   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1742     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1743     if (ArgTy[ArgIdx]->isArrayType())
1744       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1745   }
1746 
1747   DeclarationName OpName =
1748     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1749   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1750   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1751 
1752   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1753   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1754                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1755                               /*AllowStringTemplate*/ false,
1756                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1757     return ExprError();
1758 
1759   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1760 }
1761 
1762 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1763 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1764 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1765 /// multiple tokens.  However, the common case is that StringToks points to one
1766 /// string.
1767 ///
1768 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1769 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1770   assert(!StringToks.empty() && "Must have at least one string!");
1771 
1772   StringLiteralParser Literal(StringToks, PP);
1773   if (Literal.hadError)
1774     return ExprError();
1775 
1776   SmallVector<SourceLocation, 4> StringTokLocs;
1777   for (const Token &Tok : StringToks)
1778     StringTokLocs.push_back(Tok.getLocation());
1779 
1780   QualType CharTy = Context.CharTy;
1781   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1782   if (Literal.isWide()) {
1783     CharTy = Context.getWideCharType();
1784     Kind = StringLiteral::Wide;
1785   } else if (Literal.isUTF8()) {
1786     if (getLangOpts().Char8)
1787       CharTy = Context.Char8Ty;
1788     Kind = StringLiteral::UTF8;
1789   } else if (Literal.isUTF16()) {
1790     CharTy = Context.Char16Ty;
1791     Kind = StringLiteral::UTF16;
1792   } else if (Literal.isUTF32()) {
1793     CharTy = Context.Char32Ty;
1794     Kind = StringLiteral::UTF32;
1795   } else if (Literal.isPascal()) {
1796     CharTy = Context.UnsignedCharTy;
1797   }
1798 
1799   // Warn on initializing an array of char from a u8 string literal; this
1800   // becomes ill-formed in C++2a.
1801   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1802       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1803     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1804 
1805     // Create removals for all 'u8' prefixes in the string literal(s). This
1806     // ensures C++2a compatibility (but may change the program behavior when
1807     // built by non-Clang compilers for which the execution character set is
1808     // not always UTF-8).
1809     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1810     SourceLocation RemovalDiagLoc;
1811     for (const Token &Tok : StringToks) {
1812       if (Tok.getKind() == tok::utf8_string_literal) {
1813         if (RemovalDiagLoc.isInvalid())
1814           RemovalDiagLoc = Tok.getLocation();
1815         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1816             Tok.getLocation(),
1817             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1818                                            getSourceManager(), getLangOpts())));
1819       }
1820     }
1821     Diag(RemovalDiagLoc, RemovalDiag);
1822   }
1823 
1824   QualType StrTy =
1825       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1826 
1827   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1828   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1829                                              Kind, Literal.Pascal, StrTy,
1830                                              &StringTokLocs[0],
1831                                              StringTokLocs.size());
1832   if (Literal.getUDSuffix().empty())
1833     return Lit;
1834 
1835   // We're building a user-defined literal.
1836   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1837   SourceLocation UDSuffixLoc =
1838     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1839                    Literal.getUDSuffixOffset());
1840 
1841   // Make sure we're allowed user-defined literals here.
1842   if (!UDLScope)
1843     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1844 
1845   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1846   //   operator "" X (str, len)
1847   QualType SizeType = Context.getSizeType();
1848 
1849   DeclarationName OpName =
1850     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1851   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1852   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1853 
1854   QualType ArgTy[] = {
1855     Context.getArrayDecayedType(StrTy), SizeType
1856   };
1857 
1858   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1859   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1860                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1861                                 /*AllowStringTemplate*/ true,
1862                                 /*DiagnoseMissing*/ true)) {
1863 
1864   case LOLR_Cooked: {
1865     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1866     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1867                                                     StringTokLocs[0]);
1868     Expr *Args[] = { Lit, LenArg };
1869 
1870     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1871   }
1872 
1873   case LOLR_StringTemplate: {
1874     TemplateArgumentListInfo ExplicitArgs;
1875 
1876     unsigned CharBits = Context.getIntWidth(CharTy);
1877     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1878     llvm::APSInt Value(CharBits, CharIsUnsigned);
1879 
1880     TemplateArgument TypeArg(CharTy);
1881     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1882     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1883 
1884     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1885       Value = Lit->getCodeUnit(I);
1886       TemplateArgument Arg(Context, Value, CharTy);
1887       TemplateArgumentLocInfo ArgInfo;
1888       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1889     }
1890     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1891                                     &ExplicitArgs);
1892   }
1893   case LOLR_Raw:
1894   case LOLR_Template:
1895   case LOLR_ErrorNoDiagnostic:
1896     llvm_unreachable("unexpected literal operator lookup result");
1897   case LOLR_Error:
1898     return ExprError();
1899   }
1900   llvm_unreachable("unexpected literal operator lookup result");
1901 }
1902 
1903 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1904 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1905                        SourceLocation Loc,
1906                        const CXXScopeSpec *SS) {
1907   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1908   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1909 }
1910 
1911 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1912 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1913                        const DeclarationNameInfo &NameInfo,
1914                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1915                        SourceLocation TemplateKWLoc,
1916                        const TemplateArgumentListInfo *TemplateArgs) {
1917   NestedNameSpecifierLoc NNS =
1918       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1919   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1920                           TemplateArgs);
1921 }
1922 
getNonOdrUseReasonInCurrentContext(ValueDecl * D)1923 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1924   // A declaration named in an unevaluated operand never constitutes an odr-use.
1925   if (isUnevaluatedContext())
1926     return NOUR_Unevaluated;
1927 
1928   // C++2a [basic.def.odr]p4:
1929   //   A variable x whose name appears as a potentially-evaluated expression e
1930   //   is odr-used by e unless [...] x is a reference that is usable in
1931   //   constant expressions.
1932   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1933     if (VD->getType()->isReferenceType() &&
1934         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1935         VD->isUsableInConstantExpressions(Context))
1936       return NOUR_Constant;
1937   }
1938 
1939   // All remaining non-variable cases constitute an odr-use. For variables, we
1940   // need to wait and see how the expression is used.
1941   return NOUR_None;
1942 }
1943 
1944 /// BuildDeclRefExpr - Build an expression that references a
1945 /// declaration that does not require a closure capture.
1946 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,NestedNameSpecifierLoc NNS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1947 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1948                        const DeclarationNameInfo &NameInfo,
1949                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1950                        SourceLocation TemplateKWLoc,
1951                        const TemplateArgumentListInfo *TemplateArgs) {
1952   bool RefersToCapturedVariable =
1953       isa<VarDecl>(D) &&
1954       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1955 
1956   DeclRefExpr *E = DeclRefExpr::Create(
1957       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1958       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1959   MarkDeclRefReferenced(E);
1960 
1961   // C++ [except.spec]p17:
1962   //   An exception-specification is considered to be needed when:
1963   //   - in an expression, the function is the unique lookup result or
1964   //     the selected member of a set of overloaded functions.
1965   //
1966   // We delay doing this until after we've built the function reference and
1967   // marked it as used so that:
1968   //  a) if the function is defaulted, we get errors from defining it before /
1969   //     instead of errors from computing its exception specification, and
1970   //  b) if the function is a defaulted comparison, we can use the body we
1971   //     build when defining it as input to the exception specification
1972   //     computation rather than computing a new body.
1973   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1974     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1975       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1976         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1977     }
1978   }
1979 
1980   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1981       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1982       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1983     getCurFunction()->recordUseOfWeak(E);
1984 
1985   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1986   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1987     FD = IFD->getAnonField();
1988   if (FD) {
1989     UnusedPrivateFields.remove(FD);
1990     // Just in case we're building an illegal pointer-to-member.
1991     if (FD->isBitField())
1992       E->setObjectKind(OK_BitField);
1993   }
1994 
1995   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1996   // designates a bit-field.
1997   if (auto *BD = dyn_cast<BindingDecl>(D))
1998     if (auto *BE = BD->getBinding())
1999       E->setObjectKind(BE->getObjectKind());
2000 
2001   return E;
2002 }
2003 
2004 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2005 /// possibly a list of template arguments.
2006 ///
2007 /// If this produces template arguments, it is permitted to call
2008 /// DecomposeTemplateName.
2009 ///
2010 /// This actually loses a lot of source location information for
2011 /// non-standard name kinds; we should consider preserving that in
2012 /// some way.
2013 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)2014 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2015                              TemplateArgumentListInfo &Buffer,
2016                              DeclarationNameInfo &NameInfo,
2017                              const TemplateArgumentListInfo *&TemplateArgs) {
2018   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2019     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2020     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2021 
2022     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2023                                        Id.TemplateId->NumArgs);
2024     translateTemplateArguments(TemplateArgsPtr, Buffer);
2025 
2026     TemplateName TName = Id.TemplateId->Template.get();
2027     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2028     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2029     TemplateArgs = &Buffer;
2030   } else {
2031     NameInfo = GetNameFromUnqualifiedId(Id);
2032     TemplateArgs = nullptr;
2033   }
2034 }
2035 
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)2036 static void emitEmptyLookupTypoDiagnostic(
2037     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2038     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2039     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2040   DeclContext *Ctx =
2041       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2042   if (!TC) {
2043     // Emit a special diagnostic for failed member lookups.
2044     // FIXME: computing the declaration context might fail here (?)
2045     if (Ctx)
2046       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2047                                                  << SS.getRange();
2048     else
2049       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2050     return;
2051   }
2052 
2053   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2054   bool DroppedSpecifier =
2055       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2056   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2057                         ? diag::note_implicit_param_decl
2058                         : diag::note_previous_decl;
2059   if (!Ctx)
2060     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2061                          SemaRef.PDiag(NoteID));
2062   else
2063     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2064                                  << Typo << Ctx << DroppedSpecifier
2065                                  << SS.getRange(),
2066                          SemaRef.PDiag(NoteID));
2067 }
2068 
2069 /// Diagnose an empty lookup.
2070 ///
2071 /// \return false if new lookup candidates were found
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,CorrectionCandidateCallback & CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)2072 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2073                                CorrectionCandidateCallback &CCC,
2074                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2075                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2076   DeclarationName Name = R.getLookupName();
2077 
2078   unsigned diagnostic = diag::err_undeclared_var_use;
2079   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2080   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2081       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2082       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2083     diagnostic = diag::err_undeclared_use;
2084     diagnostic_suggest = diag::err_undeclared_use_suggest;
2085   }
2086 
2087   // If the original lookup was an unqualified lookup, fake an
2088   // unqualified lookup.  This is useful when (for example) the
2089   // original lookup would not have found something because it was a
2090   // dependent name.
2091   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2092   while (DC) {
2093     if (isa<CXXRecordDecl>(DC)) {
2094       LookupQualifiedName(R, DC);
2095 
2096       if (!R.empty()) {
2097         // Don't give errors about ambiguities in this lookup.
2098         R.suppressDiagnostics();
2099 
2100         // During a default argument instantiation the CurContext points
2101         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2102         // function parameter list, hence add an explicit check.
2103         bool isDefaultArgument =
2104             !CodeSynthesisContexts.empty() &&
2105             CodeSynthesisContexts.back().Kind ==
2106                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2107         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2108         bool isInstance = CurMethod &&
2109                           CurMethod->isInstance() &&
2110                           DC == CurMethod->getParent() && !isDefaultArgument;
2111 
2112         // Give a code modification hint to insert 'this->'.
2113         // TODO: fixit for inserting 'Base<T>::' in the other cases.
2114         // Actually quite difficult!
2115         if (getLangOpts().MSVCCompat)
2116           diagnostic = diag::ext_found_via_dependent_bases_lookup;
2117         if (isInstance) {
2118           Diag(R.getNameLoc(), diagnostic) << Name
2119             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2120           CheckCXXThisCapture(R.getNameLoc());
2121         } else {
2122           Diag(R.getNameLoc(), diagnostic) << Name;
2123         }
2124 
2125         // Do we really want to note all of these?
2126         for (NamedDecl *D : R)
2127           Diag(D->getLocation(), diag::note_dependent_var_use);
2128 
2129         // Return true if we are inside a default argument instantiation
2130         // and the found name refers to an instance member function, otherwise
2131         // the function calling DiagnoseEmptyLookup will try to create an
2132         // implicit member call and this is wrong for default argument.
2133         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2134           Diag(R.getNameLoc(), diag::err_member_call_without_object);
2135           return true;
2136         }
2137 
2138         // Tell the callee to try to recover.
2139         return false;
2140       }
2141 
2142       R.clear();
2143     }
2144 
2145     DC = DC->getLookupParent();
2146   }
2147 
2148   // We didn't find anything, so try to correct for a typo.
2149   TypoCorrection Corrected;
2150   if (S && Out) {
2151     SourceLocation TypoLoc = R.getNameLoc();
2152     assert(!ExplicitTemplateArgs &&
2153            "Diagnosing an empty lookup with explicit template args!");
2154     *Out = CorrectTypoDelayed(
2155         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2156         [=](const TypoCorrection &TC) {
2157           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2158                                         diagnostic, diagnostic_suggest);
2159         },
2160         nullptr, CTK_ErrorRecovery);
2161     if (*Out)
2162       return true;
2163   } else if (S &&
2164              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2165                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2166     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2167     bool DroppedSpecifier =
2168         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2169     R.setLookupName(Corrected.getCorrection());
2170 
2171     bool AcceptableWithRecovery = false;
2172     bool AcceptableWithoutRecovery = false;
2173     NamedDecl *ND = Corrected.getFoundDecl();
2174     if (ND) {
2175       if (Corrected.isOverloaded()) {
2176         OverloadCandidateSet OCS(R.getNameLoc(),
2177                                  OverloadCandidateSet::CSK_Normal);
2178         OverloadCandidateSet::iterator Best;
2179         for (NamedDecl *CD : Corrected) {
2180           if (FunctionTemplateDecl *FTD =
2181                    dyn_cast<FunctionTemplateDecl>(CD))
2182             AddTemplateOverloadCandidate(
2183                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2184                 Args, OCS);
2185           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2186             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2187               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2188                                    Args, OCS);
2189         }
2190         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2191         case OR_Success:
2192           ND = Best->FoundDecl;
2193           Corrected.setCorrectionDecl(ND);
2194           break;
2195         default:
2196           // FIXME: Arbitrarily pick the first declaration for the note.
2197           Corrected.setCorrectionDecl(ND);
2198           break;
2199         }
2200       }
2201       R.addDecl(ND);
2202       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2203         CXXRecordDecl *Record = nullptr;
2204         if (Corrected.getCorrectionSpecifier()) {
2205           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2206           Record = Ty->getAsCXXRecordDecl();
2207         }
2208         if (!Record)
2209           Record = cast<CXXRecordDecl>(
2210               ND->getDeclContext()->getRedeclContext());
2211         R.setNamingClass(Record);
2212       }
2213 
2214       auto *UnderlyingND = ND->getUnderlyingDecl();
2215       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2216                                isa<FunctionTemplateDecl>(UnderlyingND);
2217       // FIXME: If we ended up with a typo for a type name or
2218       // Objective-C class name, we're in trouble because the parser
2219       // is in the wrong place to recover. Suggest the typo
2220       // correction, but don't make it a fix-it since we're not going
2221       // to recover well anyway.
2222       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2223                                   getAsTypeTemplateDecl(UnderlyingND) ||
2224                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2225     } else {
2226       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2227       // because we aren't able to recover.
2228       AcceptableWithoutRecovery = true;
2229     }
2230 
2231     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2232       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2233                             ? diag::note_implicit_param_decl
2234                             : diag::note_previous_decl;
2235       if (SS.isEmpty())
2236         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2237                      PDiag(NoteID), AcceptableWithRecovery);
2238       else
2239         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2240                                   << Name << computeDeclContext(SS, false)
2241                                   << DroppedSpecifier << SS.getRange(),
2242                      PDiag(NoteID), AcceptableWithRecovery);
2243 
2244       // Tell the callee whether to try to recover.
2245       return !AcceptableWithRecovery;
2246     }
2247   }
2248   R.clear();
2249 
2250   // Emit a special diagnostic for failed member lookups.
2251   // FIXME: computing the declaration context might fail here (?)
2252   if (!SS.isEmpty()) {
2253     Diag(R.getNameLoc(), diag::err_no_member)
2254       << Name << computeDeclContext(SS, false)
2255       << SS.getRange();
2256     return true;
2257   }
2258 
2259   // Give up, we can't recover.
2260   Diag(R.getNameLoc(), diagnostic) << Name;
2261   return true;
2262 }
2263 
2264 /// In Microsoft mode, if we are inside a template class whose parent class has
2265 /// dependent base classes, and we can't resolve an unqualified identifier, then
2266 /// assume the identifier is a member of a dependent base class.  We can only
2267 /// recover successfully in static methods, instance methods, and other contexts
2268 /// where 'this' is available.  This doesn't precisely match MSVC's
2269 /// instantiation model, but it's close enough.
2270 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2271 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2272                                DeclarationNameInfo &NameInfo,
2273                                SourceLocation TemplateKWLoc,
2274                                const TemplateArgumentListInfo *TemplateArgs) {
2275   // Only try to recover from lookup into dependent bases in static methods or
2276   // contexts where 'this' is available.
2277   QualType ThisType = S.getCurrentThisType();
2278   const CXXRecordDecl *RD = nullptr;
2279   if (!ThisType.isNull())
2280     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2281   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2282     RD = MD->getParent();
2283   if (!RD || !RD->hasAnyDependentBases())
2284     return nullptr;
2285 
2286   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2287   // is available, suggest inserting 'this->' as a fixit.
2288   SourceLocation Loc = NameInfo.getLoc();
2289   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2290   DB << NameInfo.getName() << RD;
2291 
2292   if (!ThisType.isNull()) {
2293     DB << FixItHint::CreateInsertion(Loc, "this->");
2294     return CXXDependentScopeMemberExpr::Create(
2295         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2296         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2297         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2298   }
2299 
2300   // Synthesize a fake NNS that points to the derived class.  This will
2301   // perform name lookup during template instantiation.
2302   CXXScopeSpec SS;
2303   auto *NNS =
2304       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2305   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2306   return DependentScopeDeclRefExpr::Create(
2307       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2308       TemplateArgs);
2309 }
2310 
2311 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2312 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2313                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2314                         bool HasTrailingLParen, bool IsAddressOfOperand,
2315                         CorrectionCandidateCallback *CCC,
2316                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2317   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2318          "cannot be direct & operand and have a trailing lparen");
2319   if (SS.isInvalid())
2320     return ExprError();
2321 
2322   TemplateArgumentListInfo TemplateArgsBuffer;
2323 
2324   // Decompose the UnqualifiedId into the following data.
2325   DeclarationNameInfo NameInfo;
2326   const TemplateArgumentListInfo *TemplateArgs;
2327   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2328 
2329   DeclarationName Name = NameInfo.getName();
2330   IdentifierInfo *II = Name.getAsIdentifierInfo();
2331   SourceLocation NameLoc = NameInfo.getLoc();
2332 
2333   if (II && II->isEditorPlaceholder()) {
2334     // FIXME: When typed placeholders are supported we can create a typed
2335     // placeholder expression node.
2336     return ExprError();
2337   }
2338 
2339   // C++ [temp.dep.expr]p3:
2340   //   An id-expression is type-dependent if it contains:
2341   //     -- an identifier that was declared with a dependent type,
2342   //        (note: handled after lookup)
2343   //     -- a template-id that is dependent,
2344   //        (note: handled in BuildTemplateIdExpr)
2345   //     -- a conversion-function-id that specifies a dependent type,
2346   //     -- a nested-name-specifier that contains a class-name that
2347   //        names a dependent type.
2348   // Determine whether this is a member of an unknown specialization;
2349   // we need to handle these differently.
2350   bool DependentID = false;
2351   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2352       Name.getCXXNameType()->isDependentType()) {
2353     DependentID = true;
2354   } else if (SS.isSet()) {
2355     if (DeclContext *DC = computeDeclContext(SS, false)) {
2356       if (RequireCompleteDeclContext(SS, DC))
2357         return ExprError();
2358     } else {
2359       DependentID = true;
2360     }
2361   }
2362 
2363   if (DependentID)
2364     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2365                                       IsAddressOfOperand, TemplateArgs);
2366 
2367   // Perform the required lookup.
2368   LookupResult R(*this, NameInfo,
2369                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2370                      ? LookupObjCImplicitSelfParam
2371                      : LookupOrdinaryName);
2372   if (TemplateKWLoc.isValid() || TemplateArgs) {
2373     // Lookup the template name again to correctly establish the context in
2374     // which it was found. This is really unfortunate as we already did the
2375     // lookup to determine that it was a template name in the first place. If
2376     // this becomes a performance hit, we can work harder to preserve those
2377     // results until we get here but it's likely not worth it.
2378     bool MemberOfUnknownSpecialization;
2379     AssumedTemplateKind AssumedTemplate;
2380     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2381                            MemberOfUnknownSpecialization, TemplateKWLoc,
2382                            &AssumedTemplate))
2383       return ExprError();
2384 
2385     if (MemberOfUnknownSpecialization ||
2386         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2387       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2388                                         IsAddressOfOperand, TemplateArgs);
2389   } else {
2390     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2391     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2392 
2393     // If the result might be in a dependent base class, this is a dependent
2394     // id-expression.
2395     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2396       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2397                                         IsAddressOfOperand, TemplateArgs);
2398 
2399     // If this reference is in an Objective-C method, then we need to do
2400     // some special Objective-C lookup, too.
2401     if (IvarLookupFollowUp) {
2402       ExprResult E(LookupInObjCMethod(R, S, II, true));
2403       if (E.isInvalid())
2404         return ExprError();
2405 
2406       if (Expr *Ex = E.getAs<Expr>())
2407         return Ex;
2408     }
2409   }
2410 
2411   if (R.isAmbiguous())
2412     return ExprError();
2413 
2414   // This could be an implicitly declared function reference (legal in C90,
2415   // extension in C99, forbidden in C++).
2416   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2417     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2418     if (D) R.addDecl(D);
2419   }
2420 
2421   // Determine whether this name might be a candidate for
2422   // argument-dependent lookup.
2423   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2424 
2425   if (R.empty() && !ADL) {
2426     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2427       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2428                                                    TemplateKWLoc, TemplateArgs))
2429         return E;
2430     }
2431 
2432     // Don't diagnose an empty lookup for inline assembly.
2433     if (IsInlineAsmIdentifier)
2434       return ExprError();
2435 
2436     // If this name wasn't predeclared and if this is not a function
2437     // call, diagnose the problem.
2438     TypoExpr *TE = nullptr;
2439     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2440                                                        : nullptr);
2441     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2442     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2443            "Typo correction callback misconfigured");
2444     if (CCC) {
2445       // Make sure the callback knows what the typo being diagnosed is.
2446       CCC->setTypoName(II);
2447       if (SS.isValid())
2448         CCC->setTypoNNS(SS.getScopeRep());
2449     }
2450     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2451     // a template name, but we happen to have always already looked up the name
2452     // before we get here if it must be a template name.
2453     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2454                             None, &TE)) {
2455       if (TE && KeywordReplacement) {
2456         auto &State = getTypoExprState(TE);
2457         auto BestTC = State.Consumer->getNextCorrection();
2458         if (BestTC.isKeyword()) {
2459           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2460           if (State.DiagHandler)
2461             State.DiagHandler(BestTC);
2462           KeywordReplacement->startToken();
2463           KeywordReplacement->setKind(II->getTokenID());
2464           KeywordReplacement->setIdentifierInfo(II);
2465           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2466           // Clean up the state associated with the TypoExpr, since it has
2467           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2468           clearDelayedTypo(TE);
2469           // Signal that a correction to a keyword was performed by returning a
2470           // valid-but-null ExprResult.
2471           return (Expr*)nullptr;
2472         }
2473         State.Consumer->resetCorrectionStream();
2474       }
2475       return TE ? TE : ExprError();
2476     }
2477 
2478     assert(!R.empty() &&
2479            "DiagnoseEmptyLookup returned false but added no results");
2480 
2481     // If we found an Objective-C instance variable, let
2482     // LookupInObjCMethod build the appropriate expression to
2483     // reference the ivar.
2484     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2485       R.clear();
2486       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2487       // In a hopelessly buggy code, Objective-C instance variable
2488       // lookup fails and no expression will be built to reference it.
2489       if (!E.isInvalid() && !E.get())
2490         return ExprError();
2491       return E;
2492     }
2493   }
2494 
2495   // This is guaranteed from this point on.
2496   assert(!R.empty() || ADL);
2497 
2498   // Check whether this might be a C++ implicit instance member access.
2499   // C++ [class.mfct.non-static]p3:
2500   //   When an id-expression that is not part of a class member access
2501   //   syntax and not used to form a pointer to member is used in the
2502   //   body of a non-static member function of class X, if name lookup
2503   //   resolves the name in the id-expression to a non-static non-type
2504   //   member of some class C, the id-expression is transformed into a
2505   //   class member access expression using (*this) as the
2506   //   postfix-expression to the left of the . operator.
2507   //
2508   // But we don't actually need to do this for '&' operands if R
2509   // resolved to a function or overloaded function set, because the
2510   // expression is ill-formed if it actually works out to be a
2511   // non-static member function:
2512   //
2513   // C++ [expr.ref]p4:
2514   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2515   //   [t]he expression can be used only as the left-hand operand of a
2516   //   member function call.
2517   //
2518   // There are other safeguards against such uses, but it's important
2519   // to get this right here so that we don't end up making a
2520   // spuriously dependent expression if we're inside a dependent
2521   // instance method.
2522   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2523     bool MightBeImplicitMember;
2524     if (!IsAddressOfOperand)
2525       MightBeImplicitMember = true;
2526     else if (!SS.isEmpty())
2527       MightBeImplicitMember = false;
2528     else if (R.isOverloadedResult())
2529       MightBeImplicitMember = false;
2530     else if (R.isUnresolvableResult())
2531       MightBeImplicitMember = true;
2532     else
2533       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2534                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2535                               isa<MSPropertyDecl>(R.getFoundDecl());
2536 
2537     if (MightBeImplicitMember)
2538       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2539                                              R, TemplateArgs, S);
2540   }
2541 
2542   if (TemplateArgs || TemplateKWLoc.isValid()) {
2543 
2544     // In C++1y, if this is a variable template id, then check it
2545     // in BuildTemplateIdExpr().
2546     // The single lookup result must be a variable template declaration.
2547     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2548         Id.TemplateId->Kind == TNK_Var_template) {
2549       assert(R.getAsSingle<VarTemplateDecl>() &&
2550              "There should only be one declaration found.");
2551     }
2552 
2553     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2554   }
2555 
2556   return BuildDeclarationNameExpr(SS, R, ADL);
2557 }
2558 
2559 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2560 /// declaration name, generally during template instantiation.
2561 /// There's a large number of things which don't need to be done along
2562 /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2563 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2564     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2565     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2566   DeclContext *DC = computeDeclContext(SS, false);
2567   if (!DC)
2568     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2569                                      NameInfo, /*TemplateArgs=*/nullptr);
2570 
2571   if (RequireCompleteDeclContext(SS, DC))
2572     return ExprError();
2573 
2574   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2575   LookupQualifiedName(R, DC);
2576 
2577   if (R.isAmbiguous())
2578     return ExprError();
2579 
2580   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2581     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2582                                      NameInfo, /*TemplateArgs=*/nullptr);
2583 
2584   if (R.empty()) {
2585     Diag(NameInfo.getLoc(), diag::err_no_member)
2586       << NameInfo.getName() << DC << SS.getRange();
2587     return ExprError();
2588   }
2589 
2590   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2591     // Diagnose a missing typename if this resolved unambiguously to a type in
2592     // a dependent context.  If we can recover with a type, downgrade this to
2593     // a warning in Microsoft compatibility mode.
2594     unsigned DiagID = diag::err_typename_missing;
2595     if (RecoveryTSI && getLangOpts().MSVCCompat)
2596       DiagID = diag::ext_typename_missing;
2597     SourceLocation Loc = SS.getBeginLoc();
2598     auto D = Diag(Loc, DiagID);
2599     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2600       << SourceRange(Loc, NameInfo.getEndLoc());
2601 
2602     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2603     // context.
2604     if (!RecoveryTSI)
2605       return ExprError();
2606 
2607     // Only issue the fixit if we're prepared to recover.
2608     D << FixItHint::CreateInsertion(Loc, "typename ");
2609 
2610     // Recover by pretending this was an elaborated type.
2611     QualType Ty = Context.getTypeDeclType(TD);
2612     TypeLocBuilder TLB;
2613     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2614 
2615     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2616     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2617     QTL.setElaboratedKeywordLoc(SourceLocation());
2618     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2619 
2620     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2621 
2622     return ExprEmpty();
2623   }
2624 
2625   // Defend against this resolving to an implicit member access. We usually
2626   // won't get here if this might be a legitimate a class member (we end up in
2627   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2628   // a pointer-to-member or in an unevaluated context in C++11.
2629   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2630     return BuildPossibleImplicitMemberExpr(SS,
2631                                            /*TemplateKWLoc=*/SourceLocation(),
2632                                            R, /*TemplateArgs=*/nullptr, S);
2633 
2634   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2635 }
2636 
2637 /// The parser has read a name in, and Sema has detected that we're currently
2638 /// inside an ObjC method. Perform some additional checks and determine if we
2639 /// should form a reference to an ivar.
2640 ///
2641 /// Ideally, most of this would be done by lookup, but there's
2642 /// actually quite a lot of extra work involved.
LookupIvarInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II)2643 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2644                                         IdentifierInfo *II) {
2645   SourceLocation Loc = Lookup.getNameLoc();
2646   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2647 
2648   // Check for error condition which is already reported.
2649   if (!CurMethod)
2650     return DeclResult(true);
2651 
2652   // There are two cases to handle here.  1) scoped lookup could have failed,
2653   // in which case we should look for an ivar.  2) scoped lookup could have
2654   // found a decl, but that decl is outside the current instance method (i.e.
2655   // a global variable).  In these two cases, we do a lookup for an ivar with
2656   // this name, if the lookup sucedes, we replace it our current decl.
2657 
2658   // If we're in a class method, we don't normally want to look for
2659   // ivars.  But if we don't find anything else, and there's an
2660   // ivar, that's an error.
2661   bool IsClassMethod = CurMethod->isClassMethod();
2662 
2663   bool LookForIvars;
2664   if (Lookup.empty())
2665     LookForIvars = true;
2666   else if (IsClassMethod)
2667     LookForIvars = false;
2668   else
2669     LookForIvars = (Lookup.isSingleResult() &&
2670                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2671   ObjCInterfaceDecl *IFace = nullptr;
2672   if (LookForIvars) {
2673     IFace = CurMethod->getClassInterface();
2674     ObjCInterfaceDecl *ClassDeclared;
2675     ObjCIvarDecl *IV = nullptr;
2676     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2677       // Diagnose using an ivar in a class method.
2678       if (IsClassMethod) {
2679         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2680         return DeclResult(true);
2681       }
2682 
2683       // Diagnose the use of an ivar outside of the declaring class.
2684       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2685           !declaresSameEntity(ClassDeclared, IFace) &&
2686           !getLangOpts().DebuggerSupport)
2687         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2688 
2689       // Success.
2690       return IV;
2691     }
2692   } else if (CurMethod->isInstanceMethod()) {
2693     // We should warn if a local variable hides an ivar.
2694     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2695       ObjCInterfaceDecl *ClassDeclared;
2696       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2697         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2698             declaresSameEntity(IFace, ClassDeclared))
2699           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2700       }
2701     }
2702   } else if (Lookup.isSingleResult() &&
2703              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2704     // If accessing a stand-alone ivar in a class method, this is an error.
2705     if (const ObjCIvarDecl *IV =
2706             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2707       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2708       return DeclResult(true);
2709     }
2710   }
2711 
2712   // Didn't encounter an error, didn't find an ivar.
2713   return DeclResult(false);
2714 }
2715 
BuildIvarRefExpr(Scope * S,SourceLocation Loc,ObjCIvarDecl * IV)2716 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2717                                   ObjCIvarDecl *IV) {
2718   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2719   assert(CurMethod && CurMethod->isInstanceMethod() &&
2720          "should not reference ivar from this context");
2721 
2722   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2723   assert(IFace && "should not reference ivar from this context");
2724 
2725   // If we're referencing an invalid decl, just return this as a silent
2726   // error node.  The error diagnostic was already emitted on the decl.
2727   if (IV->isInvalidDecl())
2728     return ExprError();
2729 
2730   // Check if referencing a field with __attribute__((deprecated)).
2731   if (DiagnoseUseOfDecl(IV, Loc))
2732     return ExprError();
2733 
2734   // FIXME: This should use a new expr for a direct reference, don't
2735   // turn this into Self->ivar, just return a BareIVarExpr or something.
2736   IdentifierInfo &II = Context.Idents.get("self");
2737   UnqualifiedId SelfName;
2738   SelfName.setIdentifier(&II, SourceLocation());
2739   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2740   CXXScopeSpec SelfScopeSpec;
2741   SourceLocation TemplateKWLoc;
2742   ExprResult SelfExpr =
2743       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2744                         /*HasTrailingLParen=*/false,
2745                         /*IsAddressOfOperand=*/false);
2746   if (SelfExpr.isInvalid())
2747     return ExprError();
2748 
2749   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2750   if (SelfExpr.isInvalid())
2751     return ExprError();
2752 
2753   MarkAnyDeclReferenced(Loc, IV, true);
2754 
2755   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2756   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2757       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2758     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2759 
2760   ObjCIvarRefExpr *Result = new (Context)
2761       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2762                       IV->getLocation(), SelfExpr.get(), true, true);
2763 
2764   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2765     if (!isUnevaluatedContext() &&
2766         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2767       getCurFunction()->recordUseOfWeak(Result);
2768   }
2769   if (getLangOpts().ObjCAutoRefCount)
2770     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2771       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2772 
2773   return Result;
2774 }
2775 
2776 /// The parser has read a name in, and Sema has detected that we're currently
2777 /// inside an ObjC method. Perform some additional checks and determine if we
2778 /// should form a reference to an ivar. If so, build an expression referencing
2779 /// that ivar.
2780 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2781 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2782                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2783   // FIXME: Integrate this lookup step into LookupParsedName.
2784   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2785   if (Ivar.isInvalid())
2786     return ExprError();
2787   if (Ivar.isUsable())
2788     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2789                             cast<ObjCIvarDecl>(Ivar.get()));
2790 
2791   if (Lookup.empty() && II && AllowBuiltinCreation)
2792     LookupBuiltin(Lookup);
2793 
2794   // Sentinel value saying that we didn't do anything special.
2795   return ExprResult(false);
2796 }
2797 
2798 /// Cast a base object to a member's actual type.
2799 ///
2800 /// Logically this happens in three phases:
2801 ///
2802 /// * First we cast from the base type to the naming class.
2803 ///   The naming class is the class into which we were looking
2804 ///   when we found the member;  it's the qualifier type if a
2805 ///   qualifier was provided, and otherwise it's the base type.
2806 ///
2807 /// * Next we cast from the naming class to the declaring class.
2808 ///   If the member we found was brought into a class's scope by
2809 ///   a using declaration, this is that class;  otherwise it's
2810 ///   the class declaring the member.
2811 ///
2812 /// * Finally we cast from the declaring class to the "true"
2813 ///   declaring class of the member.  This conversion does not
2814 ///   obey access control.
2815 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2816 Sema::PerformObjectMemberConversion(Expr *From,
2817                                     NestedNameSpecifier *Qualifier,
2818                                     NamedDecl *FoundDecl,
2819                                     NamedDecl *Member) {
2820   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2821   if (!RD)
2822     return From;
2823 
2824   QualType DestRecordType;
2825   QualType DestType;
2826   QualType FromRecordType;
2827   QualType FromType = From->getType();
2828   bool PointerConversions = false;
2829   if (isa<FieldDecl>(Member)) {
2830     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2831     auto FromPtrType = FromType->getAs<PointerType>();
2832     DestRecordType = Context.getAddrSpaceQualType(
2833         DestRecordType, FromPtrType
2834                             ? FromType->getPointeeType().getAddressSpace()
2835                             : FromType.getAddressSpace());
2836 
2837     if (FromPtrType) {
2838       DestType = Context.getPointerType(DestRecordType,
2839                                         FromPtrType->getPointerInterpretation());
2840       FromRecordType = FromPtrType->getPointeeType();
2841       PointerConversions = true;
2842     } else {
2843       DestType = DestRecordType;
2844       FromRecordType = FromType;
2845     }
2846   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2847     if (Method->isStatic())
2848       return From;
2849 
2850     DestType = Method->getThisType();
2851     DestRecordType = DestType->getPointeeType();
2852 
2853     if (FromType->getAs<PointerType>()) {
2854       FromRecordType = FromType->getPointeeType();
2855       PointerConversions = true;
2856     } else {
2857       FromRecordType = FromType;
2858       DestType = DestRecordType;
2859     }
2860 
2861     LangAS FromAS = FromRecordType.getAddressSpace();
2862     LangAS DestAS = DestRecordType.getAddressSpace();
2863     if (FromAS != DestAS) {
2864       QualType FromRecordTypeWithoutAS =
2865           Context.removeAddrSpaceQualType(FromRecordType);
2866       QualType FromTypeWithDestAS =
2867           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2868       if (PointerConversions)
2869         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2870       From = ImpCastExprToType(From, FromTypeWithDestAS,
2871                                CK_AddressSpaceConversion, From->getValueKind())
2872                  .get();
2873     }
2874   } else {
2875     // No conversion necessary.
2876     return From;
2877   }
2878 
2879   if (DestType->isDependentType() || FromType->isDependentType())
2880     return From;
2881 
2882   // If the unqualified types are the same, no conversion is necessary.
2883   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2884     return From;
2885 
2886   SourceRange FromRange = From->getSourceRange();
2887   SourceLocation FromLoc = FromRange.getBegin();
2888 
2889   ExprValueKind VK = From->getValueKind();
2890 
2891   // C++ [class.member.lookup]p8:
2892   //   [...] Ambiguities can often be resolved by qualifying a name with its
2893   //   class name.
2894   //
2895   // If the member was a qualified name and the qualified referred to a
2896   // specific base subobject type, we'll cast to that intermediate type
2897   // first and then to the object in which the member is declared. That allows
2898   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2899   //
2900   //   class Base { public: int x; };
2901   //   class Derived1 : public Base { };
2902   //   class Derived2 : public Base { };
2903   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2904   //
2905   //   void VeryDerived::f() {
2906   //     x = 17; // error: ambiguous base subobjects
2907   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2908   //   }
2909   if (Qualifier && Qualifier->getAsType()) {
2910     QualType QType = QualType(Qualifier->getAsType(), 0);
2911     assert(QType->isRecordType() && "lookup done with non-record type");
2912 
2913     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2914 
2915     // In C++98, the qualifier type doesn't actually have to be a base
2916     // type of the object type, in which case we just ignore it.
2917     // Otherwise build the appropriate casts.
2918     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2919       CXXCastPath BasePath;
2920       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2921                                        FromLoc, FromRange, &BasePath))
2922         return ExprError();
2923 
2924       if (PointerConversions)
2925         QType = Context.getPointerType(QType,
2926                                        FromType->isCHERICapabilityType(Context)
2927                                            ? PIK_Capability : PIK_Integer);
2928       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2929                                VK, &BasePath).get();
2930 
2931       FromType = QType;
2932       FromRecordType = QRecordType;
2933 
2934       // If the qualifier type was the same as the destination type,
2935       // we're done.
2936       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2937         return From;
2938     }
2939   }
2940 
2941   bool IgnoreAccess = false;
2942 
2943   // If we actually found the member through a using declaration, cast
2944   // down to the using declaration's type.
2945   //
2946   // Pointer equality is fine here because only one declaration of a
2947   // class ever has member declarations.
2948   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2949     assert(isa<UsingShadowDecl>(FoundDecl));
2950     QualType URecordType = Context.getTypeDeclType(
2951                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2952 
2953     // We only need to do this if the naming-class to declaring-class
2954     // conversion is non-trivial.
2955     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2956       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2957       CXXCastPath BasePath;
2958       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2959                                        FromLoc, FromRange, &BasePath))
2960         return ExprError();
2961 
2962       QualType UType = URecordType;
2963       if (PointerConversions)
2964         UType = Context.getPointerType(UType,
2965                                        FromType->isCHERICapabilityType(Context)
2966                                            ? PIK_Capability : PIK_Integer);
2967       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2968                                VK, &BasePath).get();
2969       FromType = UType;
2970       FromRecordType = URecordType;
2971     }
2972 
2973     // We don't do access control for the conversion from the
2974     // declaring class to the true declaring class.
2975     IgnoreAccess = true;
2976   }
2977 
2978   CXXCastPath BasePath;
2979   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2980                                    FromLoc, FromRange, &BasePath,
2981                                    IgnoreAccess))
2982     return ExprError();
2983 
2984   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2985                            VK, &BasePath);
2986 }
2987 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2988 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2989                                       const LookupResult &R,
2990                                       bool HasTrailingLParen) {
2991   // Only when used directly as the postfix-expression of a call.
2992   if (!HasTrailingLParen)
2993     return false;
2994 
2995   // Never if a scope specifier was provided.
2996   if (SS.isSet())
2997     return false;
2998 
2999   // Only in C++ or ObjC++.
3000   if (!getLangOpts().CPlusPlus)
3001     return false;
3002 
3003   // Turn off ADL when we find certain kinds of declarations during
3004   // normal lookup:
3005   for (NamedDecl *D : R) {
3006     // C++0x [basic.lookup.argdep]p3:
3007     //     -- a declaration of a class member
3008     // Since using decls preserve this property, we check this on the
3009     // original decl.
3010     if (D->isCXXClassMember())
3011       return false;
3012 
3013     // C++0x [basic.lookup.argdep]p3:
3014     //     -- a block-scope function declaration that is not a
3015     //        using-declaration
3016     // NOTE: we also trigger this for function templates (in fact, we
3017     // don't check the decl type at all, since all other decl types
3018     // turn off ADL anyway).
3019     if (isa<UsingShadowDecl>(D))
3020       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3021     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3022       return false;
3023 
3024     // C++0x [basic.lookup.argdep]p3:
3025     //     -- a declaration that is neither a function or a function
3026     //        template
3027     // And also for builtin functions.
3028     if (isa<FunctionDecl>(D)) {
3029       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3030 
3031       // But also builtin functions.
3032       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3033         return false;
3034     } else if (!isa<FunctionTemplateDecl>(D))
3035       return false;
3036   }
3037 
3038   return true;
3039 }
3040 
3041 
3042 /// Diagnoses obvious problems with the use of the given declaration
3043 /// as an expression.  This is only actually called for lookups that
3044 /// were not overloaded, and it doesn't promise that the declaration
3045 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)3046 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3047   if (D->isInvalidDecl())
3048     return true;
3049 
3050   if (isa<TypedefNameDecl>(D)) {
3051     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3052     return true;
3053   }
3054 
3055   if (isa<ObjCInterfaceDecl>(D)) {
3056     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3057     return true;
3058   }
3059 
3060   if (isa<NamespaceDecl>(D)) {
3061     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3062     return true;
3063   }
3064 
3065   return false;
3066 }
3067 
3068 // Certain multiversion types should be treated as overloaded even when there is
3069 // only one result.
ShouldLookupResultBeMultiVersionOverload(const LookupResult & R)3070 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3071   assert(R.isSingleResult() && "Expected only a single result");
3072   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3073   return FD &&
3074          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3075 }
3076 
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)3077 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3078                                           LookupResult &R, bool NeedsADL,
3079                                           bool AcceptInvalidDecl) {
3080   // If this is a single, fully-resolved result and we don't need ADL,
3081   // just build an ordinary singleton decl ref.
3082   if (!NeedsADL && R.isSingleResult() &&
3083       !R.getAsSingle<FunctionTemplateDecl>() &&
3084       !ShouldLookupResultBeMultiVersionOverload(R))
3085     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3086                                     R.getRepresentativeDecl(), nullptr,
3087                                     AcceptInvalidDecl);
3088 
3089   // We only need to check the declaration if there's exactly one
3090   // result, because in the overloaded case the results can only be
3091   // functions and function templates.
3092   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3093       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3094     return ExprError();
3095 
3096   // Otherwise, just build an unresolved lookup expression.  Suppress
3097   // any lookup-related diagnostics; we'll hash these out later, when
3098   // we've picked a target.
3099   R.suppressDiagnostics();
3100 
3101   UnresolvedLookupExpr *ULE
3102     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3103                                    SS.getWithLocInContext(Context),
3104                                    R.getLookupNameInfo(),
3105                                    NeedsADL, R.isOverloadedResult(),
3106                                    R.begin(), R.end());
3107 
3108   return ULE;
3109 }
3110 
3111 static void
3112 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3113                                    ValueDecl *var, DeclContext *DC);
3114 
3115 /// Complete semantic analysis for a reference to the given declaration.
BuildDeclarationNameExpr(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,NamedDecl * D,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,bool AcceptInvalidDecl)3116 ExprResult Sema::BuildDeclarationNameExpr(
3117     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3118     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3119     bool AcceptInvalidDecl) {
3120   assert(D && "Cannot refer to a NULL declaration");
3121   assert(!isa<FunctionTemplateDecl>(D) &&
3122          "Cannot refer unambiguously to a function template");
3123 
3124   SourceLocation Loc = NameInfo.getLoc();
3125   if (CheckDeclInExpr(*this, Loc, D))
3126     return ExprError();
3127 
3128   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3129     // Specifically diagnose references to class templates that are missing
3130     // a template argument list.
3131     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3132     return ExprError();
3133   }
3134 
3135   // Make sure that we're referring to a value.
3136   ValueDecl *VD = dyn_cast<ValueDecl>(D);
3137   if (!VD) {
3138     Diag(Loc, diag::err_ref_non_value)
3139       << D << SS.getRange();
3140     Diag(D->getLocation(), diag::note_declared_at);
3141     return ExprError();
3142   }
3143 
3144   // Check whether this declaration can be used. Note that we suppress
3145   // this check when we're going to perform argument-dependent lookup
3146   // on this function name, because this might not be the function
3147   // that overload resolution actually selects.
3148   if (DiagnoseUseOfDecl(VD, Loc))
3149     return ExprError();
3150 
3151   // Only create DeclRefExpr's for valid Decl's.
3152   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3153     return ExprError();
3154 
3155   // Handle members of anonymous structs and unions.  If we got here,
3156   // and the reference is to a class member indirect field, then this
3157   // must be the subject of a pointer-to-member expression.
3158   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3159     if (!indirectField->isCXXClassMember())
3160       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3161                                                       indirectField);
3162 
3163   {
3164     QualType type = VD->getType();
3165     if (type.isNull())
3166       return ExprError();
3167     ExprValueKind valueKind = VK_RValue;
3168 
3169     // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3170     // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3171     // is expanded by some outer '...' in the context of the use.
3172     type = type.getNonPackExpansionType();
3173 
3174     switch (D->getKind()) {
3175     // Ignore all the non-ValueDecl kinds.
3176 #define ABSTRACT_DECL(kind)
3177 #define VALUE(type, base)
3178 #define DECL(type, base) \
3179     case Decl::type:
3180 #include "clang/AST/DeclNodes.inc"
3181       llvm_unreachable("invalid value decl kind");
3182 
3183     // These shouldn't make it here.
3184     case Decl::ObjCAtDefsField:
3185       llvm_unreachable("forming non-member reference to ivar?");
3186 
3187     // Enum constants are always r-values and never references.
3188     // Unresolved using declarations are dependent.
3189     case Decl::EnumConstant:
3190     case Decl::UnresolvedUsingValue:
3191     case Decl::OMPDeclareReduction:
3192     case Decl::OMPDeclareMapper:
3193       valueKind = VK_RValue;
3194       break;
3195 
3196     // Fields and indirect fields that got here must be for
3197     // pointer-to-member expressions; we just call them l-values for
3198     // internal consistency, because this subexpression doesn't really
3199     // exist in the high-level semantics.
3200     case Decl::Field:
3201     case Decl::IndirectField:
3202     case Decl::ObjCIvar:
3203       assert(getLangOpts().CPlusPlus &&
3204              "building reference to field in C?");
3205 
3206       // These can't have reference type in well-formed programs, but
3207       // for internal consistency we do this anyway.
3208       type = type.getNonReferenceType();
3209       valueKind = VK_LValue;
3210       break;
3211 
3212     // Non-type template parameters are either l-values or r-values
3213     // depending on the type.
3214     case Decl::NonTypeTemplateParm: {
3215       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3216         type = reftype->getPointeeType();
3217         valueKind = VK_LValue; // even if the parameter is an r-value reference
3218         break;
3219       }
3220 
3221       // For non-references, we need to strip qualifiers just in case
3222       // the template parameter was declared as 'const int' or whatever.
3223       valueKind = VK_RValue;
3224       type = type.getUnqualifiedType();
3225       break;
3226     }
3227 
3228     case Decl::Var:
3229     case Decl::VarTemplateSpecialization:
3230     case Decl::VarTemplatePartialSpecialization:
3231     case Decl::Decomposition:
3232     case Decl::OMPCapturedExpr:
3233       // In C, "extern void blah;" is valid and is an r-value.
3234       if (!getLangOpts().CPlusPlus &&
3235           !type.hasQualifiers() &&
3236           type->isVoidType()) {
3237         valueKind = VK_RValue;
3238         break;
3239       }
3240       LLVM_FALLTHROUGH;
3241 
3242     case Decl::ImplicitParam:
3243     case Decl::ParmVar: {
3244       // These are always l-values.
3245       valueKind = VK_LValue;
3246       type = type.getNonReferenceType();
3247 
3248       // FIXME: Does the addition of const really only apply in
3249       // potentially-evaluated contexts? Since the variable isn't actually
3250       // captured in an unevaluated context, it seems that the answer is no.
3251       if (!isUnevaluatedContext()) {
3252         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3253         if (!CapturedType.isNull())
3254           type = CapturedType;
3255       }
3256 
3257       break;
3258     }
3259 
3260     case Decl::Binding: {
3261       // These are always lvalues.
3262       valueKind = VK_LValue;
3263       type = type.getNonReferenceType();
3264       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3265       // decides how that's supposed to work.
3266       auto *BD = cast<BindingDecl>(VD);
3267       if (BD->getDeclContext() != CurContext) {
3268         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3269         if (DD && DD->hasLocalStorage())
3270           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3271       }
3272       break;
3273     }
3274 
3275     case Decl::Function: {
3276       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3277         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3278           type = Context.BuiltinFnTy;
3279           valueKind = VK_RValue;
3280           break;
3281         }
3282       }
3283 
3284       const FunctionType *fty = type->castAs<FunctionType>();
3285 
3286       // If we're referring to a function with an __unknown_anytype
3287       // result type, make the entire expression __unknown_anytype.
3288       if (fty->getReturnType() == Context.UnknownAnyTy) {
3289         type = Context.UnknownAnyTy;
3290         valueKind = VK_RValue;
3291         break;
3292       }
3293 
3294       // Functions are l-values in C++.
3295       if (getLangOpts().CPlusPlus) {
3296         valueKind = VK_LValue;
3297         break;
3298       }
3299 
3300       // C99 DR 316 says that, if a function type comes from a
3301       // function definition (without a prototype), that type is only
3302       // used for checking compatibility. Therefore, when referencing
3303       // the function, we pretend that we don't have the full function
3304       // type.
3305       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3306           isa<FunctionProtoType>(fty))
3307         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3308                                               fty->getExtInfo());
3309 
3310       // Functions are r-values in C.
3311       valueKind = VK_RValue;
3312       break;
3313     }
3314 
3315     case Decl::CXXDeductionGuide:
3316       llvm_unreachable("building reference to deduction guide");
3317 
3318     case Decl::MSProperty:
3319     case Decl::MSGuid:
3320       // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3321       // or duplicated between host and device?
3322       valueKind = VK_LValue;
3323       break;
3324 
3325     case Decl::CXXMethod:
3326       // If we're referring to a method with an __unknown_anytype
3327       // result type, make the entire expression __unknown_anytype.
3328       // This should only be possible with a type written directly.
3329       if (const FunctionProtoType *proto
3330             = dyn_cast<FunctionProtoType>(VD->getType()))
3331         if (proto->getReturnType() == Context.UnknownAnyTy) {
3332           type = Context.UnknownAnyTy;
3333           valueKind = VK_RValue;
3334           break;
3335         }
3336 
3337       // C++ methods are l-values if static, r-values if non-static.
3338       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3339         valueKind = VK_LValue;
3340         break;
3341       }
3342       LLVM_FALLTHROUGH;
3343 
3344     case Decl::CXXConversion:
3345     case Decl::CXXDestructor:
3346     case Decl::CXXConstructor:
3347       valueKind = VK_RValue;
3348       break;
3349     }
3350 
3351     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3352                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3353                             TemplateArgs);
3354   }
3355 }
3356 
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3357 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3358                                     SmallString<32> &Target) {
3359   Target.resize(CharByteWidth * (Source.size() + 1));
3360   char *ResultPtr = &Target[0];
3361   const llvm::UTF8 *ErrorPtr;
3362   bool success =
3363       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3364   (void)success;
3365   assert(success);
3366   Target.resize(ResultPtr - &Target[0]);
3367 }
3368 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentKind IK)3369 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3370                                      PredefinedExpr::IdentKind IK) {
3371   // Pick the current block, lambda, captured statement or function.
3372   Decl *currentDecl = nullptr;
3373   if (const BlockScopeInfo *BSI = getCurBlock())
3374     currentDecl = BSI->TheDecl;
3375   else if (const LambdaScopeInfo *LSI = getCurLambda())
3376     currentDecl = LSI->CallOperator;
3377   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3378     currentDecl = CSI->TheCapturedDecl;
3379   else
3380     currentDecl = getCurFunctionOrMethodDecl();
3381 
3382   if (!currentDecl) {
3383     Diag(Loc, diag::ext_predef_outside_function);
3384     currentDecl = Context.getTranslationUnitDecl();
3385   }
3386 
3387   QualType ResTy;
3388   StringLiteral *SL = nullptr;
3389   if (cast<DeclContext>(currentDecl)->isDependentContext())
3390     ResTy = Context.DependentTy;
3391   else {
3392     // Pre-defined identifiers are of type char[x], where x is the length of
3393     // the string.
3394     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3395     unsigned Length = Str.length();
3396 
3397     llvm::APInt LengthI(32, Length + 1);
3398     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3399       ResTy =
3400           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3401       SmallString<32> RawChars;
3402       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3403                               Str, RawChars);
3404       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3405                                            ArrayType::Normal,
3406                                            /*IndexTypeQuals*/ 0);
3407       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3408                                  /*Pascal*/ false, ResTy, Loc);
3409     } else {
3410       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3411       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3412                                            ArrayType::Normal,
3413                                            /*IndexTypeQuals*/ 0);
3414       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3415                                  /*Pascal*/ false, ResTy, Loc);
3416     }
3417   }
3418 
3419   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3420 }
3421 
3422 static std::pair<QualType, StringLiteral *>
GetUniqueStableNameInfo(ASTContext & Context,QualType OpType,SourceLocation OpLoc,PredefinedExpr::IdentKind K)3423 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3424                         SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3425   std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3426 
3427   if (OpType->isDependentType()) {
3428       Result.first = Context.DependentTy;
3429       return Result;
3430   }
3431 
3432   std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3433   llvm::APInt Length(32, Str.length() + 1);
3434   Result.first =
3435       Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3436   Result.first = Context.getConstantArrayType(
3437       Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3438   Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3439                                         /*Pascal*/ false, Result.first, OpLoc);
3440   return Result;
3441 }
3442 
BuildUniqueStableName(SourceLocation OpLoc,TypeSourceInfo * Operand)3443 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3444                                        TypeSourceInfo *Operand) {
3445   QualType ResultTy;
3446   StringLiteral *SL;
3447   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3448       Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3449 
3450   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3451                                 PredefinedExpr::UniqueStableNameType, SL,
3452                                 Operand);
3453 }
3454 
BuildUniqueStableName(SourceLocation OpLoc,Expr * E)3455 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3456                                        Expr *E) {
3457   QualType ResultTy;
3458   StringLiteral *SL;
3459   std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3460       Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3461 
3462   return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3463                                 PredefinedExpr::UniqueStableNameExpr, SL, E);
3464 }
3465 
ActOnUniqueStableNameExpr(SourceLocation OpLoc,SourceLocation L,SourceLocation R,ParsedType Ty)3466 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3467                                            SourceLocation L, SourceLocation R,
3468                                            ParsedType Ty) {
3469   TypeSourceInfo *TInfo = nullptr;
3470   QualType T = GetTypeFromParser(Ty, &TInfo);
3471 
3472   if (T.isNull())
3473     return ExprError();
3474   if (!TInfo)
3475     TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3476 
3477   return BuildUniqueStableName(OpLoc, TInfo);
3478 }
3479 
ActOnUniqueStableNameExpr(SourceLocation OpLoc,SourceLocation L,SourceLocation R,Expr * E)3480 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3481                                            SourceLocation L, SourceLocation R,
3482                                            Expr *E) {
3483   return BuildUniqueStableName(OpLoc, E);
3484 }
3485 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3486 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3487   PredefinedExpr::IdentKind IK;
3488 
3489   switch (Kind) {
3490   default: llvm_unreachable("Unknown simple primary expr!");
3491   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3492   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3493   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3494   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3495   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3496   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3497   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3498   }
3499 
3500   return BuildPredefinedExpr(Loc, IK);
3501 }
3502 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3503 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3504   SmallString<16> CharBuffer;
3505   bool Invalid = false;
3506   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3507   if (Invalid)
3508     return ExprError();
3509 
3510   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3511                             PP, Tok.getKind());
3512   if (Literal.hadError())
3513     return ExprError();
3514 
3515   QualType Ty;
3516   if (Literal.isWide())
3517     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3518   else if (Literal.isUTF8() && getLangOpts().Char8)
3519     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3520   else if (Literal.isUTF16())
3521     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3522   else if (Literal.isUTF32())
3523     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3524   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3525     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3526   else
3527     Ty = Context.CharTy;  // 'x' -> char in C++
3528 
3529   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3530   if (Literal.isWide())
3531     Kind = CharacterLiteral::Wide;
3532   else if (Literal.isUTF16())
3533     Kind = CharacterLiteral::UTF16;
3534   else if (Literal.isUTF32())
3535     Kind = CharacterLiteral::UTF32;
3536   else if (Literal.isUTF8())
3537     Kind = CharacterLiteral::UTF8;
3538 
3539   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3540                                              Tok.getLocation());
3541 
3542   if (Literal.getUDSuffix().empty())
3543     return Lit;
3544 
3545   // We're building a user-defined literal.
3546   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3547   SourceLocation UDSuffixLoc =
3548     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3549 
3550   // Make sure we're allowed user-defined literals here.
3551   if (!UDLScope)
3552     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3553 
3554   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3555   //   operator "" X (ch)
3556   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3557                                         Lit, Tok.getLocation());
3558 }
3559 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3560 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3561   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3562   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3563                                 Context.IntTy, Loc);
3564 }
3565 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3566 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3567                                   QualType Ty, SourceLocation Loc) {
3568   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3569 
3570   using llvm::APFloat;
3571   APFloat Val(Format);
3572 
3573   APFloat::opStatus result = Literal.GetFloatValue(Val);
3574 
3575   // Overflow is always an error, but underflow is only an error if
3576   // we underflowed to zero (APFloat reports denormals as underflow).
3577   if ((result & APFloat::opOverflow) ||
3578       ((result & APFloat::opUnderflow) && Val.isZero())) {
3579     unsigned diagnostic;
3580     SmallString<20> buffer;
3581     if (result & APFloat::opOverflow) {
3582       diagnostic = diag::warn_float_overflow;
3583       APFloat::getLargest(Format).toString(buffer);
3584     } else {
3585       diagnostic = diag::warn_float_underflow;
3586       APFloat::getSmallest(Format).toString(buffer);
3587     }
3588 
3589     S.Diag(Loc, diagnostic)
3590       << Ty
3591       << StringRef(buffer.data(), buffer.size());
3592   }
3593 
3594   bool isExact = (result == APFloat::opOK);
3595   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3596 }
3597 
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3598 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3599   assert(E && "Invalid expression");
3600 
3601   if (E->isValueDependent())
3602     return false;
3603 
3604   QualType QT = E->getType();
3605   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3606     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3607     return true;
3608   }
3609 
3610   llvm::APSInt ValueAPS;
3611   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3612 
3613   if (R.isInvalid())
3614     return true;
3615 
3616   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3617   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3618     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3619         << ValueAPS.toString(10) << ValueIsPositive;
3620     return true;
3621   }
3622 
3623   return false;
3624 }
3625 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3626 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3627   // Fast path for a single digit (which is quite common).  A single digit
3628   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3629   if (Tok.getLength() == 1) {
3630     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3631     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3632   }
3633 
3634   SmallString<128> SpellingBuffer;
3635   // NumericLiteralParser wants to overread by one character.  Add padding to
3636   // the buffer in case the token is copied to the buffer.  If getSpelling()
3637   // returns a StringRef to the memory buffer, it should have a null char at
3638   // the EOF, so it is also safe.
3639   SpellingBuffer.resize(Tok.getLength() + 1);
3640 
3641   // Get the spelling of the token, which eliminates trigraphs, etc.
3642   bool Invalid = false;
3643   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3644   if (Invalid)
3645     return ExprError();
3646 
3647   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3648                                PP.getSourceManager(), PP.getLangOpts(),
3649                                PP.getTargetInfo(), PP.getDiagnostics());
3650   if (Literal.hadError)
3651     return ExprError();
3652 
3653   if (Literal.hasUDSuffix()) {
3654     // We're building a user-defined literal.
3655     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3656     SourceLocation UDSuffixLoc =
3657       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3658 
3659     // Make sure we're allowed user-defined literals here.
3660     if (!UDLScope)
3661       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3662 
3663     QualType CookedTy;
3664     if (Literal.isFloatingLiteral()) {
3665       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3666       // long double, the literal is treated as a call of the form
3667       //   operator "" X (f L)
3668       CookedTy = Context.LongDoubleTy;
3669     } else {
3670       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3671       // unsigned long long, the literal is treated as a call of the form
3672       //   operator "" X (n ULL)
3673       CookedTy = Context.UnsignedLongLongTy;
3674     }
3675 
3676     DeclarationName OpName =
3677       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3678     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3679     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3680 
3681     SourceLocation TokLoc = Tok.getLocation();
3682 
3683     // Perform literal operator lookup to determine if we're building a raw
3684     // literal or a cooked one.
3685     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3686     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3687                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3688                                   /*AllowStringTemplate*/ false,
3689                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3690     case LOLR_ErrorNoDiagnostic:
3691       // Lookup failure for imaginary constants isn't fatal, there's still the
3692       // GNU extension producing _Complex types.
3693       break;
3694     case LOLR_Error:
3695       return ExprError();
3696     case LOLR_Cooked: {
3697       Expr *Lit;
3698       if (Literal.isFloatingLiteral()) {
3699         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3700       } else {
3701         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3702         if (Literal.GetIntegerValue(ResultVal))
3703           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3704               << /* Unsigned */ 1;
3705         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3706                                      Tok.getLocation());
3707       }
3708       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3709     }
3710 
3711     case LOLR_Raw: {
3712       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3713       // literal is treated as a call of the form
3714       //   operator "" X ("n")
3715       unsigned Length = Literal.getUDSuffixOffset();
3716       QualType StrTy = Context.getConstantArrayType(
3717           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3718           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3719       Expr *Lit = StringLiteral::Create(
3720           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3721           /*Pascal*/false, StrTy, &TokLoc, 1);
3722       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3723     }
3724 
3725     case LOLR_Template: {
3726       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3727       // template), L is treated as a call fo the form
3728       //   operator "" X <'c1', 'c2', ... 'ck'>()
3729       // where n is the source character sequence c1 c2 ... ck.
3730       TemplateArgumentListInfo ExplicitArgs;
3731       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3732       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3733       llvm::APSInt Value(CharBits, CharIsUnsigned);
3734       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3735         Value = TokSpelling[I];
3736         TemplateArgument Arg(Context, Value, Context.CharTy);
3737         TemplateArgumentLocInfo ArgInfo;
3738         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3739       }
3740       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3741                                       &ExplicitArgs);
3742     }
3743     case LOLR_StringTemplate:
3744       llvm_unreachable("unexpected literal operator lookup result");
3745     }
3746   }
3747 
3748   Expr *Res;
3749 
3750   if (Literal.isFixedPointLiteral()) {
3751     QualType Ty;
3752 
3753     if (Literal.isAccum) {
3754       if (Literal.isHalf) {
3755         Ty = Context.ShortAccumTy;
3756       } else if (Literal.isLong) {
3757         Ty = Context.LongAccumTy;
3758       } else {
3759         Ty = Context.AccumTy;
3760       }
3761     } else if (Literal.isFract) {
3762       if (Literal.isHalf) {
3763         Ty = Context.ShortFractTy;
3764       } else if (Literal.isLong) {
3765         Ty = Context.LongFractTy;
3766       } else {
3767         Ty = Context.FractTy;
3768       }
3769     }
3770 
3771     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3772 
3773     bool isSigned = !Literal.isUnsigned;
3774     unsigned scale = Context.getFixedPointScale(Ty);
3775     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3776 
3777     llvm::APInt Val(bit_width, 0, isSigned);
3778     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3779     bool ValIsZero = Val.isNullValue() && !Overflowed;
3780 
3781     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3782     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3783       // Clause 6.4.4 - The value of a constant shall be in the range of
3784       // representable values for its type, with exception for constants of a
3785       // fract type with a value of exactly 1; such a constant shall denote
3786       // the maximal value for the type.
3787       --Val;
3788     else if (Val.ugt(MaxVal) || Overflowed)
3789       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3790 
3791     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3792                                               Tok.getLocation(), scale);
3793   } else if (Literal.isFloatingLiteral()) {
3794     QualType Ty;
3795     if (Literal.isHalf){
3796       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3797         Ty = Context.HalfTy;
3798       else {
3799         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3800         return ExprError();
3801       }
3802     } else if (Literal.isFloat)
3803       Ty = Context.FloatTy;
3804     else if (Literal.isLong)
3805       Ty = Context.LongDoubleTy;
3806     else if (Literal.isFloat16)
3807       Ty = Context.Float16Ty;
3808     else if (Literal.isFloat128)
3809       Ty = Context.Float128Ty;
3810     else
3811       Ty = Context.DoubleTy;
3812 
3813     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3814 
3815     if (Ty == Context.DoubleTy) {
3816       if (getLangOpts().SinglePrecisionConstants) {
3817         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3818         if (BTy->getKind() != BuiltinType::Float) {
3819           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3820         }
3821       } else if (getLangOpts().OpenCL &&
3822                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3823         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3824         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3825         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3826       }
3827     }
3828   } else if (!Literal.isIntegerLiteral()) {
3829     return ExprError();
3830   } else {
3831     QualType Ty;
3832 
3833     // 'long long' is a C99 or C++11 feature.
3834     if (!getLangOpts().C99 && Literal.isLongLong) {
3835       if (getLangOpts().CPlusPlus)
3836         Diag(Tok.getLocation(),
3837              getLangOpts().CPlusPlus11 ?
3838              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3839       else
3840         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3841     }
3842 
3843     // Get the value in the widest-possible width.
3844     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3845     llvm::APInt ResultVal(MaxWidth, 0);
3846 
3847     if (Literal.GetIntegerValue(ResultVal)) {
3848       // If this value didn't fit into uintmax_t, error and force to ull.
3849       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3850           << /* Unsigned */ 1;
3851       Ty = Context.UnsignedLongLongTy;
3852       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3853              "long long is not intmax_t?");
3854     } else {
3855       // If this value fits into a ULL, try to figure out what else it fits into
3856       // according to the rules of C99 6.4.4.1p5.
3857 
3858       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3859       // be an unsigned int.
3860       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3861 
3862       // Check from smallest to largest, picking the smallest type we can.
3863       unsigned Width = 0;
3864 
3865       // Microsoft specific integer suffixes are explicitly sized.
3866       if (Literal.MicrosoftInteger) {
3867         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3868           Width = 8;
3869           Ty = Context.CharTy;
3870         } else {
3871           Width = Literal.MicrosoftInteger;
3872           Ty = Context.getIntTypeForBitwidth(Width,
3873                                              /*Signed=*/!Literal.isUnsigned);
3874         }
3875       }
3876 
3877       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3878         // Are int/unsigned possibilities?
3879         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3880 
3881         // Does it fit in a unsigned int?
3882         if (ResultVal.isIntN(IntSize)) {
3883           // Does it fit in a signed int?
3884           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3885             Ty = Context.IntTy;
3886           else if (AllowUnsigned)
3887             Ty = Context.UnsignedIntTy;
3888           Width = IntSize;
3889         }
3890       }
3891 
3892       // Are long/unsigned long possibilities?
3893       if (Ty.isNull() && !Literal.isLongLong) {
3894         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3895 
3896         // Does it fit in a unsigned long?
3897         if (ResultVal.isIntN(LongSize)) {
3898           // Does it fit in a signed long?
3899           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3900             Ty = Context.LongTy;
3901           else if (AllowUnsigned)
3902             Ty = Context.UnsignedLongTy;
3903           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3904           // is compatible.
3905           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3906             const unsigned LongLongSize =
3907                 Context.getTargetInfo().getLongLongWidth();
3908             Diag(Tok.getLocation(),
3909                  getLangOpts().CPlusPlus
3910                      ? Literal.isLong
3911                            ? diag::warn_old_implicitly_unsigned_long_cxx
3912                            : /*C++98 UB*/ diag::
3913                                  ext_old_implicitly_unsigned_long_cxx
3914                      : diag::warn_old_implicitly_unsigned_long)
3915                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3916                                             : /*will be ill-formed*/ 1);
3917             Ty = Context.UnsignedLongTy;
3918           }
3919           Width = LongSize;
3920         }
3921       }
3922 
3923       // Check long long if needed.
3924       if (Ty.isNull()) {
3925         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3926 
3927         // Does it fit in a unsigned long long?
3928         if (ResultVal.isIntN(LongLongSize)) {
3929           // Does it fit in a signed long long?
3930           // To be compatible with MSVC, hex integer literals ending with the
3931           // LL or i64 suffix are always signed in Microsoft mode.
3932           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3933               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3934             Ty = Context.LongLongTy;
3935           else if (AllowUnsigned)
3936             Ty = Context.UnsignedLongLongTy;
3937           Width = LongLongSize;
3938         }
3939       }
3940 
3941       // If we still couldn't decide a type, we probably have something that
3942       // does not fit in a signed long long, but has no U suffix.
3943       if (Ty.isNull()) {
3944         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3945         Ty = Context.UnsignedLongLongTy;
3946         Width = Context.getTargetInfo().getLongLongWidth();
3947       }
3948 
3949       if (ResultVal.getBitWidth() != Width)
3950         ResultVal = ResultVal.trunc(Width);
3951     }
3952     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3953   }
3954 
3955   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3956   if (Literal.isImaginary) {
3957     Res = new (Context) ImaginaryLiteral(Res,
3958                                         Context.getComplexType(Res->getType()));
3959 
3960     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3961   }
3962   return Res;
3963 }
3964 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3965 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3966   assert(E && "ActOnParenExpr() missing expr");
3967   return new (Context) ParenExpr(L, R, E);
3968 }
3969 
ActOnNoChangeBoundsExpr(SourceLocation L,SourceLocation R,Expr * E)3970 ExprResult Sema::ActOnNoChangeBoundsExpr(SourceLocation L, SourceLocation R,
3971                                          Expr *E) {
3972   assert(E && "ActOnNoChangeBoundsExpr() missing expr");
3973   return NoChangeBoundsExpr::Create(Context, L, R, E);
3974 }
3975 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3976 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3977                                          SourceLocation Loc,
3978                                          SourceRange ArgRange) {
3979   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3980   // scalar or vector data type argument..."
3981   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3982   // type (C99 6.2.5p18) or void.
3983   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3984     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3985       << T << ArgRange;
3986     return true;
3987   }
3988 
3989   assert((T->isVoidType() || !T->isIncompleteType()) &&
3990          "Scalar types should always be complete");
3991   return false;
3992 }
3993 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3994 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3995                                            SourceLocation Loc,
3996                                            SourceRange ArgRange,
3997                                            UnaryExprOrTypeTrait TraitKind) {
3998   // Invalid types must be hard errors for SFINAE in C++.
3999   if (S.LangOpts.CPlusPlus)
4000     return true;
4001 
4002   // C99 6.5.3.4p1:
4003   if (T->isFunctionType() &&
4004       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4005        TraitKind == UETT_PreferredAlignOf)) {
4006     // sizeof(function)/alignof(function) is allowed as an extension.
4007     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4008         << getTraitSpelling(TraitKind) << ArgRange;
4009     return false;
4010   }
4011 
4012   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4013   // this is an error (OpenCL v1.1 s6.3.k)
4014   if (T->isVoidType()) {
4015     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4016                                         : diag::ext_sizeof_alignof_void_type;
4017     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4018     return false;
4019   }
4020 
4021   return true;
4022 }
4023 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4024 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4025                                              SourceLocation Loc,
4026                                              SourceRange ArgRange,
4027                                              UnaryExprOrTypeTrait TraitKind) {
4028   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4029   // runtime doesn't allow it.
4030   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4031     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4032       << T << (TraitKind == UETT_SizeOf)
4033       << ArgRange;
4034     return true;
4035   }
4036 
4037   return false;
4038 }
4039 
4040 /// Check whether E is a pointer from a decayed array type (the decayed
4041 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)4042 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4043                                      Expr *E) {
4044   // Don't warn if the operation changed the type.
4045   if (T != E->getType())
4046     return;
4047 
4048   // Now look for array decays.
4049   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4050   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4051     return;
4052 
4053   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4054                                              << ICE->getType()
4055                                              << ICE->getSubExpr()->getType();
4056 }
4057 
4058 /// Check the constraints on expression operands to unary type expression
4059 /// and type traits.
4060 ///
4061 /// Completes any types necessary and validates the constraints on the operand
4062 /// expression. The logic mostly mirrors the type-based overload, but may modify
4063 /// the expression as it completes the type for that expression through template
4064 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)4065 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4066                                             UnaryExprOrTypeTrait ExprKind) {
4067   QualType ExprTy = E->getType();
4068   assert(!ExprTy->isReferenceType());
4069 
4070   bool IsUnevaluatedOperand =
4071       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4072        ExprKind == UETT_PreferredAlignOf);
4073   if (IsUnevaluatedOperand) {
4074     ExprResult Result = CheckUnevaluatedOperand(E);
4075     if (Result.isInvalid())
4076       return true;
4077     E = Result.get();
4078   }
4079 
4080   if (ExprKind == UETT_VecStep)
4081     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4082                                         E->getSourceRange());
4083 
4084   // Explicitly list some types as extensions.
4085   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4086                                       E->getSourceRange(), ExprKind))
4087     return false;
4088 
4089   // 'alignof' applied to an expression only requires the base element type of
4090   // the expression to be complete. 'sizeof' requires the expression's type to
4091   // be complete (and will attempt to complete it if it's an array of unknown
4092   // bound).
4093   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4094     if (RequireCompleteSizedType(
4095             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4096             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4097             getTraitSpelling(ExprKind), E->getSourceRange()))
4098       return true;
4099   } else {
4100     if (RequireCompleteSizedExprType(
4101             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4102             getTraitSpelling(ExprKind), E->getSourceRange()))
4103       return true;
4104   }
4105 
4106   // Completing the expression's type may have changed it.
4107   ExprTy = E->getType();
4108   assert(!ExprTy->isReferenceType());
4109 
4110   if (ExprTy->isFunctionType()) {
4111     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4112         << getTraitSpelling(ExprKind) << E->getSourceRange();
4113     return true;
4114   }
4115 
4116   // The operand for sizeof and alignof is in an unevaluated expression context,
4117   // so side effects could result in unintended consequences.
4118   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4119       E->HasSideEffects(Context, false))
4120     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4121 
4122   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4123                                        E->getSourceRange(), ExprKind))
4124     return true;
4125 
4126   if (ExprKind == UETT_SizeOf) {
4127     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4128       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4129         QualType OType = PVD->getOriginalType();
4130         QualType Type = PVD->getType();
4131         if (Type->isPointerType() && OType->isArrayType()) {
4132           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4133             << Type << OType;
4134           Diag(PVD->getLocation(), diag::note_declared_at);
4135         }
4136       }
4137     }
4138 
4139     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4140     // decays into a pointer and returns an unintended result. This is most
4141     // likely a typo for "sizeof(array) op x".
4142     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4143       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4144                                BO->getLHS());
4145       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4146                                BO->getRHS());
4147     }
4148   }
4149 
4150   return false;
4151 }
4152 
4153 /// Check the constraints on operands to unary expression and type
4154 /// traits.
4155 ///
4156 /// This will complete any types necessary, and validate the various constraints
4157 /// on those operands.
4158 ///
4159 /// The UsualUnaryConversions() function is *not* called by this routine.
4160 /// C99 6.3.2.1p[2-4] all state:
4161 ///   Except when it is the operand of the sizeof operator ...
4162 ///
4163 /// C++ [expr.sizeof]p4
4164 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4165 ///   standard conversions are not applied to the operand of sizeof.
4166 ///
4167 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)4168 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4169                                             SourceLocation OpLoc,
4170                                             SourceRange ExprRange,
4171                                             UnaryExprOrTypeTrait ExprKind) {
4172   if (ExprType->isDependentType())
4173     return false;
4174 
4175   // C++ [expr.sizeof]p2:
4176   //     When applied to a reference or a reference type, the result
4177   //     is the size of the referenced type.
4178   // C++11 [expr.alignof]p3:
4179   //     When alignof is applied to a reference type, the result
4180   //     shall be the alignment of the referenced type.
4181   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4182     ExprType = Ref->getPointeeType();
4183 
4184   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4185   //   When alignof or _Alignof is applied to an array type, the result
4186   //   is the alignment of the element type.
4187   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4188       ExprKind == UETT_OpenMPRequiredSimdAlign)
4189     ExprType = Context.getBaseElementType(ExprType);
4190 
4191   if (ExprKind == UETT_VecStep)
4192     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4193 
4194   // Explicitly list some types as extensions.
4195   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4196                                       ExprKind))
4197     return false;
4198 
4199   if (RequireCompleteSizedType(
4200           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4201           getTraitSpelling(ExprKind), ExprRange))
4202     return true;
4203 
4204   if (ExprType->isFunctionType()) {
4205     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4206         << getTraitSpelling(ExprKind) << ExprRange;
4207     return true;
4208   }
4209 
4210   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4211                                        ExprKind))
4212     return true;
4213 
4214   return false;
4215 }
4216 
CheckAlignOfExpr(Sema & S,Expr * E,UnaryExprOrTypeTrait ExprKind)4217 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4218   // Cannot know anything else if the expression is dependent.
4219   if (E->isTypeDependent())
4220     return false;
4221 
4222   if (E->getObjectKind() == OK_BitField) {
4223     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4224        << 1 << E->getSourceRange();
4225     return true;
4226   }
4227 
4228   ValueDecl *D = nullptr;
4229   Expr *Inner = E->IgnoreParens();
4230   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4231     D = DRE->getDecl();
4232   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4233     D = ME->getMemberDecl();
4234   }
4235 
4236   // If it's a field, require the containing struct to have a
4237   // complete definition so that we can compute the layout.
4238   //
4239   // This can happen in C++11 onwards, either by naming the member
4240   // in a way that is not transformed into a member access expression
4241   // (in an unevaluated operand, for instance), or by naming the member
4242   // in a trailing-return-type.
4243   //
4244   // For the record, since __alignof__ on expressions is a GCC
4245   // extension, GCC seems to permit this but always gives the
4246   // nonsensical answer 0.
4247   //
4248   // We don't really need the layout here --- we could instead just
4249   // directly check for all the appropriate alignment-lowing
4250   // attributes --- but that would require duplicating a lot of
4251   // logic that just isn't worth duplicating for such a marginal
4252   // use-case.
4253   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4254     // Fast path this check, since we at least know the record has a
4255     // definition if we can find a member of it.
4256     if (!FD->getParent()->isCompleteDefinition()) {
4257       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4258         << E->getSourceRange();
4259       return true;
4260     }
4261 
4262     // Otherwise, if it's a field, and the field doesn't have
4263     // reference type, then it must have a complete type (or be a
4264     // flexible array member, which we explicitly want to
4265     // white-list anyway), which makes the following checks trivial.
4266     if (!FD->getType()->isReferenceType())
4267       return false;
4268   }
4269 
4270   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4271 }
4272 
CheckVecStepExpr(Expr * E)4273 bool Sema::CheckVecStepExpr(Expr *E) {
4274   E = E->IgnoreParens();
4275 
4276   // Cannot know anything else if the expression is dependent.
4277   if (E->isTypeDependent())
4278     return false;
4279 
4280   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4281 }
4282 
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)4283 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4284                                         CapturingScopeInfo *CSI) {
4285   assert(T->isVariablyModifiedType());
4286   assert(CSI != nullptr);
4287 
4288   // We're going to walk down into the type and look for VLA expressions.
4289   do {
4290     const Type *Ty = T.getTypePtr();
4291     switch (Ty->getTypeClass()) {
4292 #define TYPE(Class, Base)
4293 #define ABSTRACT_TYPE(Class, Base)
4294 #define NON_CANONICAL_TYPE(Class, Base)
4295 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4296 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4297 #include "clang/AST/TypeNodes.inc"
4298       T = QualType();
4299       break;
4300     // These types are never variably-modified.
4301     case Type::Builtin:
4302     case Type::Complex:
4303     case Type::Vector:
4304     case Type::ExtVector:
4305     case Type::ConstantMatrix:
4306     case Type::Record:
4307     case Type::Enum:
4308     case Type::Elaborated:
4309     case Type::TemplateSpecialization:
4310     case Type::ObjCObject:
4311     case Type::ObjCInterface:
4312     case Type::ObjCObjectPointer:
4313     case Type::ObjCTypeParam:
4314     case Type::Pipe:
4315     case Type::ExtInt:
4316       llvm_unreachable("type class is never variably-modified!");
4317     case Type::Adjusted:
4318       T = cast<AdjustedType>(Ty)->getOriginalType();
4319       break;
4320     case Type::Decayed:
4321       T = cast<DecayedType>(Ty)->getPointeeType();
4322       break;
4323     case Type::Pointer:
4324       T = cast<PointerType>(Ty)->getPointeeType();
4325       break;
4326     case Type::BlockPointer:
4327       T = cast<BlockPointerType>(Ty)->getPointeeType();
4328       break;
4329     case Type::LValueReference:
4330     case Type::RValueReference:
4331       T = cast<ReferenceType>(Ty)->getPointeeType();
4332       break;
4333     case Type::MemberPointer:
4334       T = cast<MemberPointerType>(Ty)->getPointeeType();
4335       break;
4336     case Type::ConstantArray:
4337     case Type::IncompleteArray:
4338       // Losing element qualification here is fine.
4339       T = cast<ArrayType>(Ty)->getElementType();
4340       break;
4341     case Type::VariableArray: {
4342       // Losing element qualification here is fine.
4343       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4344 
4345       // Unknown size indication requires no size computation.
4346       // Otherwise, evaluate and record it.
4347       auto Size = VAT->getSizeExpr();
4348       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4349           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4350         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4351 
4352       T = VAT->getElementType();
4353       break;
4354     }
4355     case Type::FunctionProto:
4356     case Type::FunctionNoProto:
4357       T = cast<FunctionType>(Ty)->getReturnType();
4358       break;
4359     case Type::Paren:
4360     case Type::TypeOf:
4361     case Type::UnaryTransform:
4362     case Type::Attributed:
4363     case Type::SubstTemplateTypeParm:
4364     case Type::PackExpansion:
4365     case Type::MacroQualified:
4366       // Keep walking after single level desugaring.
4367       T = T.getSingleStepDesugaredType(Context);
4368       break;
4369     case Type::Typedef:
4370       T = cast<TypedefType>(Ty)->desugar();
4371       break;
4372     case Type::Decltype:
4373       T = cast<DecltypeType>(Ty)->desugar();
4374       break;
4375     case Type::Auto:
4376     case Type::DeducedTemplateSpecialization:
4377       T = cast<DeducedType>(Ty)->getDeducedType();
4378       break;
4379     case Type::TypeOfExpr:
4380       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4381       break;
4382     case Type::Atomic:
4383       T = cast<AtomicType>(Ty)->getValueType();
4384       break;
4385     }
4386   } while (!T.isNull() && T->isVariablyModifiedType());
4387 }
4388 
4389 /// Build a sizeof or alignof expression given a type operand.
4390 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)4391 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4392                                      SourceLocation OpLoc,
4393                                      UnaryExprOrTypeTrait ExprKind,
4394                                      SourceRange R) {
4395   if (!TInfo)
4396     return ExprError();
4397 
4398   QualType T = TInfo->getType();
4399 
4400   if (!T->isDependentType() &&
4401       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4402     return ExprError();
4403 
4404   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4405     if (auto *TT = T->getAs<TypedefType>()) {
4406       for (auto I = FunctionScopes.rbegin(),
4407                 E = std::prev(FunctionScopes.rend());
4408            I != E; ++I) {
4409         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4410         if (CSI == nullptr)
4411           break;
4412         DeclContext *DC = nullptr;
4413         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4414           DC = LSI->CallOperator;
4415         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4416           DC = CRSI->TheCapturedDecl;
4417         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4418           DC = BSI->TheDecl;
4419         if (DC) {
4420           if (DC->containsDecl(TT->getDecl()))
4421             break;
4422           captureVariablyModifiedType(Context, T, CSI);
4423         }
4424       }
4425     }
4426   }
4427 
4428   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4429   return new (Context) UnaryExprOrTypeTraitExpr(
4430       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4431 }
4432 
4433 /// Build a sizeof or alignof expression given an expression
4434 /// operand.
4435 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)4436 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4437                                      UnaryExprOrTypeTrait ExprKind) {
4438   ExprResult PE = CheckPlaceholderExpr(E);
4439   if (PE.isInvalid())
4440     return ExprError();
4441 
4442   E = PE.get();
4443 
4444   // Verify that the operand is valid.
4445   bool isInvalid = false;
4446   if (E->isTypeDependent()) {
4447     // Delay type-checking for type-dependent expressions.
4448   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4449     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4450   } else if (ExprKind == UETT_VecStep) {
4451     isInvalid = CheckVecStepExpr(E);
4452   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4453       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4454       isInvalid = true;
4455   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4456     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4457     isInvalid = true;
4458   } else {
4459     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4460   }
4461 
4462   if (isInvalid)
4463     return ExprError();
4464 
4465   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4466     PE = TransformToPotentiallyEvaluated(E);
4467     if (PE.isInvalid()) return ExprError();
4468     E = PE.get();
4469   }
4470 
4471   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4472   return new (Context) UnaryExprOrTypeTraitExpr(
4473       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4474 }
4475 
4476 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4477 /// expr and the same for @c alignof and @c __alignof
4478 /// Note that the ArgRange is invalid if isType is false.
4479 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4480 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4481                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4482                                     void *TyOrEx, SourceRange ArgRange) {
4483   // If error parsing type, ignore.
4484   if (!TyOrEx) return ExprError();
4485 
4486   if (IsType) {
4487     TypeSourceInfo *TInfo;
4488     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4489     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4490   }
4491 
4492   Expr *ArgEx = (Expr *)TyOrEx;
4493   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4494   return Result;
4495 }
4496 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4497 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4498                                      bool IsReal) {
4499   if (V.get()->isTypeDependent())
4500     return S.Context.DependentTy;
4501 
4502   // _Real and _Imag are only l-values for normal l-values.
4503   if (V.get()->getObjectKind() != OK_Ordinary) {
4504     V = S.DefaultLvalueConversion(V.get());
4505     if (V.isInvalid())
4506       return QualType();
4507   }
4508 
4509   // These operators return the element type of a complex type.
4510   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4511     return CT->getElementType();
4512 
4513   // Otherwise they pass through real integer and floating point types here.
4514   if (V.get()->getType()->isArithmeticType())
4515     return V.get()->getType();
4516 
4517   // Test for placeholders.
4518   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4519   if (PR.isInvalid()) return QualType();
4520   if (PR.get() != V.get()) {
4521     V = PR;
4522     return CheckRealImagOperand(S, V, Loc, IsReal);
4523   }
4524 
4525   // Reject anything else.
4526   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4527     << (IsReal ? "__real" : "__imag");
4528   return QualType();
4529 }
4530 
4531 
4532 
4533 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4534 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4535                           tok::TokenKind Kind, Expr *Input) {
4536   UnaryOperatorKind Opc;
4537   switch (Kind) {
4538   default: llvm_unreachable("Unknown unary op!");
4539   case tok::plusplus:   Opc = UO_PostInc; break;
4540   case tok::minusminus: Opc = UO_PostDec; break;
4541   }
4542 
4543   // Since this might is a postfix expression, get rid of ParenListExprs.
4544   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4545   if (Result.isInvalid()) return ExprError();
4546   Input = Result.get();
4547 
4548   return BuildUnaryOp(S, OpLoc, Opc, Input);
4549 }
4550 
4551 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4552 ///
4553 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4554 static bool checkArithmeticOnObjCPointer(Sema &S,
4555                                          SourceLocation opLoc,
4556                                          Expr *op) {
4557   assert(op->getType()->isObjCObjectPointerType());
4558   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4559       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4560     return false;
4561 
4562   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4563     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4564     << op->getSourceRange();
4565   return true;
4566 }
4567 
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4568 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4569   auto *BaseNoParens = Base->IgnoreParens();
4570   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4571     return MSProp->getPropertyDecl()->getType()->isArrayType();
4572   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4573 }
4574 
4575 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4576 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4577                               Expr *idx, SourceLocation rbLoc) {
4578   if (base && !base->getType().isNull() &&
4579       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4580     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4581                                     SourceLocation(), /*Length*/ nullptr,
4582                                     /*Stride=*/nullptr, rbLoc);
4583 
4584   // Since this might be a postfix expression, get rid of ParenListExprs.
4585   if (isa<ParenListExpr>(base)) {
4586     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4587     if (result.isInvalid()) return ExprError();
4588     base = result.get();
4589   }
4590 
4591   // Check if base and idx form a MatrixSubscriptExpr.
4592   //
4593   // Helper to check for comma expressions, which are not allowed as indices for
4594   // matrix subscript expressions.
4595   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4596     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4597       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4598           << SourceRange(base->getBeginLoc(), rbLoc);
4599       return true;
4600     }
4601     return false;
4602   };
4603   // The matrix subscript operator ([][])is considered a single operator.
4604   // Separating the index expressions by parenthesis is not allowed.
4605   if (base->getType()->isSpecificPlaceholderType(
4606           BuiltinType::IncompleteMatrixIdx) &&
4607       !isa<MatrixSubscriptExpr>(base)) {
4608     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4609         << SourceRange(base->getBeginLoc(), rbLoc);
4610     return ExprError();
4611   }
4612   // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4613   // a new MatrixSubscriptExpr.
4614   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4615   if (matSubscriptE) {
4616     if (CheckAndReportCommaError(idx))
4617       return ExprError();
4618 
4619     assert(matSubscriptE->isIncomplete() &&
4620            "base has to be an incomplete matrix subscript");
4621     return CreateBuiltinMatrixSubscriptExpr(
4622         matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4623   }
4624   Expr *matrixBase = base;
4625   bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4626   if (!IsMSPropertySubscript) {
4627     ExprResult result = CheckPlaceholderExpr(base);
4628     if (!result.isInvalid())
4629       matrixBase = result.get();
4630   }
4631   if (matrixBase->getType()->isMatrixType()) {
4632     if (CheckAndReportCommaError(idx))
4633       return ExprError();
4634 
4635     return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4636   }
4637 
4638   // A comma-expression as the index is deprecated in C++2a onwards.
4639   if (getLangOpts().CPlusPlus20 &&
4640       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4641        (isa<CXXOperatorCallExpr>(idx) &&
4642         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4643     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4644       << SourceRange(base->getBeginLoc(), rbLoc);
4645   }
4646 
4647   // Handle any non-overload placeholder types in the base and index
4648   // expressions.  We can't handle overloads here because the other
4649   // operand might be an overloadable type, in which case the overload
4650   // resolution for the operator overload should get the first crack
4651   // at the overload.
4652   if (base->getType()->isNonOverloadPlaceholderType()) {
4653     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4654     if (!IsMSPropertySubscript) {
4655       ExprResult result = CheckPlaceholderExpr(base);
4656       if (result.isInvalid())
4657         return ExprError();
4658       base = result.get();
4659     }
4660   }
4661   if (idx->getType()->isNonOverloadPlaceholderType()) {
4662     ExprResult result = CheckPlaceholderExpr(idx);
4663     if (result.isInvalid()) return ExprError();
4664     idx = result.get();
4665   }
4666 
4667   // Build an unanalyzed expression if either operand is type-dependent.
4668   if (getLangOpts().CPlusPlus &&
4669       (base->isTypeDependent() || idx->isTypeDependent())) {
4670     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4671                                             VK_LValue, OK_Ordinary, rbLoc);
4672   }
4673 
4674   // MSDN, property (C++)
4675   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4676   // This attribute can also be used in the declaration of an empty array in a
4677   // class or structure definition. For example:
4678   // __declspec(property(get=GetX, put=PutX)) int x[];
4679   // The above statement indicates that x[] can be used with one or more array
4680   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4681   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4682   if (IsMSPropertySubscript) {
4683     // Build MS property subscript expression if base is MS property reference
4684     // or MS property subscript.
4685     return new (Context) MSPropertySubscriptExpr(
4686         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4687   }
4688 
4689   // Use C++ overloaded-operator rules if either operand has record
4690   // type.  The spec says to do this if either type is *overloadable*,
4691   // but enum types can't declare subscript operators or conversion
4692   // operators, so there's nothing interesting for overload resolution
4693   // to do if there aren't any record types involved.
4694   //
4695   // ObjC pointers have their own subscripting logic that is not tied
4696   // to overload resolution and so should not take this path.
4697   if (getLangOpts().CPlusPlus &&
4698       (base->getType()->isRecordType() ||
4699        (!base->getType()->isObjCObjectPointerType() &&
4700         idx->getType()->isRecordType()))) {
4701     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4702   }
4703 
4704   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4705 
4706   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4707     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4708 
4709   return Res;
4710 }
4711 
tryConvertExprToType(Expr * E,QualType Ty)4712 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4713   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4714   InitializationKind Kind =
4715       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4716   InitializationSequence InitSeq(*this, Entity, Kind, E);
4717   return InitSeq.Perform(*this, Entity, Kind, E);
4718 }
4719 
CreateBuiltinMatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,SourceLocation RBLoc)4720 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4721                                                   Expr *ColumnIdx,
4722                                                   SourceLocation RBLoc) {
4723   ExprResult BaseR = CheckPlaceholderExpr(Base);
4724   if (BaseR.isInvalid())
4725     return BaseR;
4726   Base = BaseR.get();
4727 
4728   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4729   if (RowR.isInvalid())
4730     return RowR;
4731   RowIdx = RowR.get();
4732 
4733   if (!ColumnIdx)
4734     return new (Context) MatrixSubscriptExpr(
4735         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4736 
4737   // Build an unanalyzed expression if any of the operands is type-dependent.
4738   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4739       ColumnIdx->isTypeDependent())
4740     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4741                                              Context.DependentTy, RBLoc);
4742 
4743   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4744   if (ColumnR.isInvalid())
4745     return ColumnR;
4746   ColumnIdx = ColumnR.get();
4747 
4748   // Check that IndexExpr is an integer expression. If it is a constant
4749   // expression, check that it is less than Dim (= the number of elements in the
4750   // corresponding dimension).
4751   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4752                           bool IsColumnIdx) -> Expr * {
4753     if (!IndexExpr->getType()->isIntegerType() &&
4754         !IndexExpr->isTypeDependent()) {
4755       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4756           << IsColumnIdx;
4757       return nullptr;
4758     }
4759 
4760     llvm::APSInt Idx;
4761     if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4762         (Idx < 0 || Idx >= Dim)) {
4763       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4764           << IsColumnIdx << Dim;
4765       return nullptr;
4766     }
4767 
4768     ExprResult ConvExpr =
4769         tryConvertExprToType(IndexExpr, Context.getSizeType());
4770     assert(!ConvExpr.isInvalid() &&
4771            "should be able to convert any integer type to size type");
4772     return ConvExpr.get();
4773   };
4774 
4775   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4776   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4777   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4778   if (!RowIdx || !ColumnIdx)
4779     return ExprError();
4780 
4781   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4782                                            MTy->getElementType(), RBLoc);
4783 }
4784 
CheckAddressOfNoDeref(const Expr * E)4785 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4786   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4787   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4788 
4789   // For expressions like `&(*s).b`, the base is recorded and what should be
4790   // checked.
4791   const MemberExpr *Member = nullptr;
4792   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4793     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4794 
4795   LastRecord.PossibleDerefs.erase(StrippedExpr);
4796 }
4797 
CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr * E)4798 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4799   QualType ResultTy = E->getType();
4800   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4801 
4802   // Bail if the element is an array since it is not memory access.
4803   if (isa<ArrayType>(ResultTy))
4804     return;
4805 
4806   if (ResultTy->hasAttr(attr::NoDeref)) {
4807     LastRecord.PossibleDerefs.insert(E);
4808     return;
4809   }
4810 
4811   // Check if the base type is a pointer to a member access of a struct
4812   // marked with noderef.
4813   const Expr *Base = E->getBase();
4814   QualType BaseTy = Base->getType();
4815   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4816     // Not a pointer access
4817     return;
4818 
4819   const MemberExpr *Member = nullptr;
4820   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4821          Member->isArrow())
4822     Base = Member->getBase();
4823 
4824   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4825     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4826       LastRecord.PossibleDerefs.insert(E);
4827   }
4828 }
4829 
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLocFirst,SourceLocation ColonLocSecond,Expr * Length,Expr * Stride,SourceLocation RBLoc)4830 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4831                                           Expr *LowerBound,
4832                                           SourceLocation ColonLocFirst,
4833                                           SourceLocation ColonLocSecond,
4834                                           Expr *Length, Expr *Stride,
4835                                           SourceLocation RBLoc) {
4836   if (Base->getType()->isPlaceholderType() &&
4837       !Base->getType()->isSpecificPlaceholderType(
4838           BuiltinType::OMPArraySection)) {
4839     ExprResult Result = CheckPlaceholderExpr(Base);
4840     if (Result.isInvalid())
4841       return ExprError();
4842     Base = Result.get();
4843   }
4844   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4845     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4846     if (Result.isInvalid())
4847       return ExprError();
4848     Result = DefaultLvalueConversion(Result.get());
4849     if (Result.isInvalid())
4850       return ExprError();
4851     LowerBound = Result.get();
4852   }
4853   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4854     ExprResult Result = CheckPlaceholderExpr(Length);
4855     if (Result.isInvalid())
4856       return ExprError();
4857     Result = DefaultLvalueConversion(Result.get());
4858     if (Result.isInvalid())
4859       return ExprError();
4860     Length = Result.get();
4861   }
4862   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4863     ExprResult Result = CheckPlaceholderExpr(Stride);
4864     if (Result.isInvalid())
4865       return ExprError();
4866     Result = DefaultLvalueConversion(Result.get());
4867     if (Result.isInvalid())
4868       return ExprError();
4869     Stride = Result.get();
4870   }
4871 
4872   // Build an unanalyzed expression if either operand is type-dependent.
4873   if (Base->isTypeDependent() ||
4874       (LowerBound &&
4875        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4876       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4877       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4878     return new (Context) OMPArraySectionExpr(
4879         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4880         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4881   }
4882 
4883   // Perform default conversions.
4884   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4885   QualType ResultTy;
4886   if (OriginalTy->isAnyPointerType()) {
4887     ResultTy = OriginalTy->getPointeeType();
4888   } else if (OriginalTy->isArrayType()) {
4889     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4890   } else {
4891     return ExprError(
4892         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4893         << Base->getSourceRange());
4894   }
4895   // C99 6.5.2.1p1
4896   if (LowerBound) {
4897     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4898                                                       LowerBound);
4899     if (Res.isInvalid())
4900       return ExprError(Diag(LowerBound->getExprLoc(),
4901                             diag::err_omp_typecheck_section_not_integer)
4902                        << 0 << LowerBound->getSourceRange());
4903     LowerBound = Res.get();
4904 
4905     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4906         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4907       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4908           << 0 << LowerBound->getSourceRange();
4909   }
4910   if (Length) {
4911     auto Res =
4912         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4913     if (Res.isInvalid())
4914       return ExprError(Diag(Length->getExprLoc(),
4915                             diag::err_omp_typecheck_section_not_integer)
4916                        << 1 << Length->getSourceRange());
4917     Length = Res.get();
4918 
4919     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4920         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4921       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4922           << 1 << Length->getSourceRange();
4923   }
4924   if (Stride) {
4925     ExprResult Res =
4926         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4927     if (Res.isInvalid())
4928       return ExprError(Diag(Stride->getExprLoc(),
4929                             diag::err_omp_typecheck_section_not_integer)
4930                        << 1 << Stride->getSourceRange());
4931     Stride = Res.get();
4932 
4933     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4934         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4935       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4936           << 1 << Stride->getSourceRange();
4937   }
4938 
4939   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4940   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4941   // type. Note that functions are not objects, and that (in C99 parlance)
4942   // incomplete types are not object types.
4943   if (ResultTy->isFunctionType()) {
4944     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4945         << ResultTy << Base->getSourceRange();
4946     return ExprError();
4947   }
4948 
4949   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4950                           diag::err_omp_section_incomplete_type, Base))
4951     return ExprError();
4952 
4953   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4954     Expr::EvalResult Result;
4955     if (LowerBound->EvaluateAsInt(Result, Context)) {
4956       // OpenMP 5.0, [2.1.5 Array Sections]
4957       // The array section must be a subset of the original array.
4958       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4959       if (LowerBoundValue.isNegative()) {
4960         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4961             << LowerBound->getSourceRange();
4962         return ExprError();
4963       }
4964     }
4965   }
4966 
4967   if (Length) {
4968     Expr::EvalResult Result;
4969     if (Length->EvaluateAsInt(Result, Context)) {
4970       // OpenMP 5.0, [2.1.5 Array Sections]
4971       // The length must evaluate to non-negative integers.
4972       llvm::APSInt LengthValue = Result.Val.getInt();
4973       if (LengthValue.isNegative()) {
4974         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4975             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4976             << Length->getSourceRange();
4977         return ExprError();
4978       }
4979     }
4980   } else if (ColonLocFirst.isValid() &&
4981              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4982                                       !OriginalTy->isVariableArrayType()))) {
4983     // OpenMP 5.0, [2.1.5 Array Sections]
4984     // When the size of the array dimension is not known, the length must be
4985     // specified explicitly.
4986     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4987         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4988     return ExprError();
4989   }
4990 
4991   if (Stride) {
4992     Expr::EvalResult Result;
4993     if (Stride->EvaluateAsInt(Result, Context)) {
4994       // OpenMP 5.0, [2.1.5 Array Sections]
4995       // The stride must evaluate to a positive integer.
4996       llvm::APSInt StrideValue = Result.Val.getInt();
4997       if (!StrideValue.isStrictlyPositive()) {
4998         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4999             << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5000             << Stride->getSourceRange();
5001         return ExprError();
5002       }
5003     }
5004   }
5005 
5006   if (!Base->getType()->isSpecificPlaceholderType(
5007           BuiltinType::OMPArraySection)) {
5008     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5009     if (Result.isInvalid())
5010       return ExprError();
5011     Base = Result.get();
5012   }
5013   return new (Context) OMPArraySectionExpr(
5014       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5015       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5016 }
5017 
ActOnOMPArrayShapingExpr(Expr * Base,SourceLocation LParenLoc,SourceLocation RParenLoc,ArrayRef<Expr * > Dims,ArrayRef<SourceRange> Brackets)5018 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5019                                           SourceLocation RParenLoc,
5020                                           ArrayRef<Expr *> Dims,
5021                                           ArrayRef<SourceRange> Brackets) {
5022   if (Base->getType()->isPlaceholderType()) {
5023     ExprResult Result = CheckPlaceholderExpr(Base);
5024     if (Result.isInvalid())
5025       return ExprError();
5026     Result = DefaultLvalueConversion(Result.get());
5027     if (Result.isInvalid())
5028       return ExprError();
5029     Base = Result.get();
5030   }
5031   QualType BaseTy = Base->getType();
5032   // Delay analysis of the types/expressions if instantiation/specialization is
5033   // required.
5034   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5035     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5036                                        LParenLoc, RParenLoc, Dims, Brackets);
5037   if (!BaseTy->isPointerType() ||
5038       (!Base->isTypeDependent() &&
5039        BaseTy->getPointeeType()->isIncompleteType()))
5040     return ExprError(Diag(Base->getExprLoc(),
5041                           diag::err_omp_non_pointer_type_array_shaping_base)
5042                      << Base->getSourceRange());
5043 
5044   SmallVector<Expr *, 4> NewDims;
5045   bool ErrorFound = false;
5046   for (Expr *Dim : Dims) {
5047     if (Dim->getType()->isPlaceholderType()) {
5048       ExprResult Result = CheckPlaceholderExpr(Dim);
5049       if (Result.isInvalid()) {
5050         ErrorFound = true;
5051         continue;
5052       }
5053       Result = DefaultLvalueConversion(Result.get());
5054       if (Result.isInvalid()) {
5055         ErrorFound = true;
5056         continue;
5057       }
5058       Dim = Result.get();
5059     }
5060     if (!Dim->isTypeDependent()) {
5061       ExprResult Result =
5062           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5063       if (Result.isInvalid()) {
5064         ErrorFound = true;
5065         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5066             << Dim->getSourceRange();
5067         continue;
5068       }
5069       Dim = Result.get();
5070       Expr::EvalResult EvResult;
5071       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5072         // OpenMP 5.0, [2.1.4 Array Shaping]
5073         // Each si is an integral type expression that must evaluate to a
5074         // positive integer.
5075         llvm::APSInt Value = EvResult.Val.getInt();
5076         if (!Value.isStrictlyPositive()) {
5077           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5078               << Value.toString(/*Radix=*/10, /*Signed=*/true)
5079               << Dim->getSourceRange();
5080           ErrorFound = true;
5081           continue;
5082         }
5083       }
5084     }
5085     NewDims.push_back(Dim);
5086   }
5087   if (ErrorFound)
5088     return ExprError();
5089   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5090                                      LParenLoc, RParenLoc, NewDims, Brackets);
5091 }
5092 
ActOnOMPIteratorExpr(Scope * S,SourceLocation IteratorKwLoc,SourceLocation LLoc,SourceLocation RLoc,ArrayRef<OMPIteratorData> Data)5093 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5094                                       SourceLocation LLoc, SourceLocation RLoc,
5095                                       ArrayRef<OMPIteratorData> Data) {
5096   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5097   bool IsCorrect = true;
5098   for (const OMPIteratorData &D : Data) {
5099     TypeSourceInfo *TInfo = nullptr;
5100     SourceLocation StartLoc;
5101     QualType DeclTy;
5102     if (!D.Type.getAsOpaquePtr()) {
5103       // OpenMP 5.0, 2.1.6 Iterators
5104       // In an iterator-specifier, if the iterator-type is not specified then
5105       // the type of that iterator is of int type.
5106       DeclTy = Context.IntTy;
5107       StartLoc = D.DeclIdentLoc;
5108     } else {
5109       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5110       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5111     }
5112 
5113     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5114                              DeclTy->containsUnexpandedParameterPack() ||
5115                              DeclTy->isInstantiationDependentType();
5116     if (!IsDeclTyDependent) {
5117       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5118         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5119         // The iterator-type must be an integral or pointer type.
5120         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5121             << DeclTy;
5122         IsCorrect = false;
5123         continue;
5124       }
5125       if (DeclTy.isConstant(Context)) {
5126         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5127         // The iterator-type must not be const qualified.
5128         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5129             << DeclTy;
5130         IsCorrect = false;
5131         continue;
5132       }
5133     }
5134 
5135     // Iterator declaration.
5136     assert(D.DeclIdent && "Identifier expected.");
5137     // Always try to create iterator declarator to avoid extra error messages
5138     // about unknown declarations use.
5139     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5140                                D.DeclIdent, DeclTy, TInfo, SC_None);
5141     VD->setImplicit();
5142     if (S) {
5143       // Check for conflicting previous declaration.
5144       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5145       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5146                             ForVisibleRedeclaration);
5147       Previous.suppressDiagnostics();
5148       LookupName(Previous, S);
5149 
5150       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5151                            /*AllowInlineNamespace=*/false);
5152       if (!Previous.empty()) {
5153         NamedDecl *Old = Previous.getRepresentativeDecl();
5154         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5155         Diag(Old->getLocation(), diag::note_previous_definition);
5156       } else {
5157         PushOnScopeChains(VD, S);
5158       }
5159     } else {
5160       CurContext->addDecl(VD);
5161     }
5162     Expr *Begin = D.Range.Begin;
5163     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5164       ExprResult BeginRes =
5165           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5166       Begin = BeginRes.get();
5167     }
5168     Expr *End = D.Range.End;
5169     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5170       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5171       End = EndRes.get();
5172     }
5173     Expr *Step = D.Range.Step;
5174     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5175       if (!Step->getType()->isIntegralType(Context)) {
5176         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5177             << Step << Step->getSourceRange();
5178         IsCorrect = false;
5179         continue;
5180       }
5181       llvm::APSInt Result;
5182       bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5183       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5184       // If the step expression of a range-specification equals zero, the
5185       // behavior is unspecified.
5186       if (IsConstant && Result.isNullValue()) {
5187         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5188             << Step << Step->getSourceRange();
5189         IsCorrect = false;
5190         continue;
5191       }
5192     }
5193     if (!Begin || !End || !IsCorrect) {
5194       IsCorrect = false;
5195       continue;
5196     }
5197     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5198     IDElem.IteratorDecl = VD;
5199     IDElem.AssignmentLoc = D.AssignLoc;
5200     IDElem.Range.Begin = Begin;
5201     IDElem.Range.End = End;
5202     IDElem.Range.Step = Step;
5203     IDElem.ColonLoc = D.ColonLoc;
5204     IDElem.SecondColonLoc = D.SecColonLoc;
5205   }
5206   if (!IsCorrect) {
5207     // Invalidate all created iterator declarations if error is found.
5208     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5209       if (Decl *ID = D.IteratorDecl)
5210         ID->setInvalidDecl();
5211     }
5212     return ExprError();
5213   }
5214   SmallVector<OMPIteratorHelperData, 4> Helpers;
5215   if (!CurContext->isDependentContext()) {
5216     // Build number of ityeration for each iteration range.
5217     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5218     // ((Begini-Stepi-1-Endi) / -Stepi);
5219     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5220       // (Endi - Begini)
5221       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5222                                           D.Range.Begin);
5223       if(!Res.isUsable()) {
5224         IsCorrect = false;
5225         continue;
5226       }
5227       ExprResult St, St1;
5228       if (D.Range.Step) {
5229         St = D.Range.Step;
5230         // (Endi - Begini) + Stepi
5231         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5232         if (!Res.isUsable()) {
5233           IsCorrect = false;
5234           continue;
5235         }
5236         // (Endi - Begini) + Stepi - 1
5237         Res =
5238             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5239                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5240         if (!Res.isUsable()) {
5241           IsCorrect = false;
5242           continue;
5243         }
5244         // ((Endi - Begini) + Stepi - 1) / Stepi
5245         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5246         if (!Res.isUsable()) {
5247           IsCorrect = false;
5248           continue;
5249         }
5250         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5251         // (Begini - Endi)
5252         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5253                                              D.Range.Begin, D.Range.End);
5254         if (!Res1.isUsable()) {
5255           IsCorrect = false;
5256           continue;
5257         }
5258         // (Begini - Endi) - Stepi
5259         Res1 =
5260             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5261         if (!Res1.isUsable()) {
5262           IsCorrect = false;
5263           continue;
5264         }
5265         // (Begini - Endi) - Stepi - 1
5266         Res1 =
5267             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5268                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5269         if (!Res1.isUsable()) {
5270           IsCorrect = false;
5271           continue;
5272         }
5273         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5274         Res1 =
5275             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5276         if (!Res1.isUsable()) {
5277           IsCorrect = false;
5278           continue;
5279         }
5280         // Stepi > 0.
5281         ExprResult CmpRes =
5282             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5283                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5284         if (!CmpRes.isUsable()) {
5285           IsCorrect = false;
5286           continue;
5287         }
5288         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5289                                  Res.get(), Res1.get());
5290         if (!Res.isUsable()) {
5291           IsCorrect = false;
5292           continue;
5293         }
5294       }
5295       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5296       if (!Res.isUsable()) {
5297         IsCorrect = false;
5298         continue;
5299       }
5300 
5301       // Build counter update.
5302       // Build counter.
5303       auto *CounterVD =
5304           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5305                           D.IteratorDecl->getBeginLoc(), nullptr,
5306                           Res.get()->getType(), nullptr, SC_None);
5307       CounterVD->setImplicit();
5308       ExprResult RefRes =
5309           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5310                            D.IteratorDecl->getBeginLoc());
5311       // Build counter update.
5312       // I = Begini + counter * Stepi;
5313       ExprResult UpdateRes;
5314       if (D.Range.Step) {
5315         UpdateRes = CreateBuiltinBinOp(
5316             D.AssignmentLoc, BO_Mul,
5317             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5318       } else {
5319         UpdateRes = DefaultLvalueConversion(RefRes.get());
5320       }
5321       if (!UpdateRes.isUsable()) {
5322         IsCorrect = false;
5323         continue;
5324       }
5325       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5326                                      UpdateRes.get());
5327       if (!UpdateRes.isUsable()) {
5328         IsCorrect = false;
5329         continue;
5330       }
5331       ExprResult VDRes =
5332           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5333                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5334                            D.IteratorDecl->getBeginLoc());
5335       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5336                                      UpdateRes.get());
5337       if (!UpdateRes.isUsable()) {
5338         IsCorrect = false;
5339         continue;
5340       }
5341       UpdateRes =
5342           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5343       if (!UpdateRes.isUsable()) {
5344         IsCorrect = false;
5345         continue;
5346       }
5347       ExprResult CounterUpdateRes =
5348           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5349       if (!CounterUpdateRes.isUsable()) {
5350         IsCorrect = false;
5351         continue;
5352       }
5353       CounterUpdateRes =
5354           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5355       if (!CounterUpdateRes.isUsable()) {
5356         IsCorrect = false;
5357         continue;
5358       }
5359       OMPIteratorHelperData &HD = Helpers.emplace_back();
5360       HD.CounterVD = CounterVD;
5361       HD.Upper = Res.get();
5362       HD.Update = UpdateRes.get();
5363       HD.CounterUpdate = CounterUpdateRes.get();
5364     }
5365   } else {
5366     Helpers.assign(ID.size(), {});
5367   }
5368   if (!IsCorrect) {
5369     // Invalidate all created iterator declarations if error is found.
5370     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5371       if (Decl *ID = D.IteratorDecl)
5372         ID->setInvalidDecl();
5373     }
5374     return ExprError();
5375   }
5376   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5377                                  LLoc, RLoc, ID, Helpers);
5378 }
5379 
5380 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)5381 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5382                                       Expr *Idx, SourceLocation RLoc) {
5383   Expr *LHSExp = Base;
5384   Expr *RHSExp = Idx;
5385 
5386   ExprValueKind VK = VK_LValue;
5387   ExprObjectKind OK = OK_Ordinary;
5388 
5389   // Per C++ core issue 1213, the result is an xvalue if either operand is
5390   // a non-lvalue array, and an lvalue otherwise.
5391   if (getLangOpts().CPlusPlus11) {
5392     for (auto *Op : {LHSExp, RHSExp}) {
5393       Op = Op->IgnoreImplicit();
5394       if (Op->getType()->isArrayType() && !Op->isLValue())
5395         VK = VK_XValue;
5396     }
5397   }
5398 
5399   // Perform default conversions.
5400   if (!LHSExp->getType()->getAs<VectorType>()) {
5401     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5402     if (Result.isInvalid())
5403       return ExprError();
5404     LHSExp = Result.get();
5405   }
5406   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5407   if (Result.isInvalid())
5408     return ExprError();
5409   RHSExp = Result.get();
5410 
5411   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5412 
5413   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5414   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5415   // in the subscript position. As a result, we need to derive the array base
5416   // and index from the expression types.
5417   Expr *BaseExpr, *IndexExpr;
5418   QualType ResultType;
5419   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5420     BaseExpr = LHSExp;
5421     IndexExpr = RHSExp;
5422     ResultType = Context.DependentTy;
5423   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5424     BaseExpr = LHSExp;
5425     IndexExpr = RHSExp;
5426     ResultType = PTy->getPointeeType();
5427   } else if (const ObjCObjectPointerType *PTy =
5428                LHSTy->getAs<ObjCObjectPointerType>()) {
5429     BaseExpr = LHSExp;
5430     IndexExpr = RHSExp;
5431 
5432     // Use custom logic if this should be the pseudo-object subscript
5433     // expression.
5434     if (!LangOpts.isSubscriptPointerArithmetic())
5435       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5436                                           nullptr);
5437 
5438     ResultType = PTy->getPointeeType();
5439   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5440      // Handle the uncommon case of "123[Ptr]".
5441     BaseExpr = RHSExp;
5442     IndexExpr = LHSExp;
5443     ResultType = PTy->getPointeeType();
5444   } else if (const ObjCObjectPointerType *PTy =
5445                RHSTy->getAs<ObjCObjectPointerType>()) {
5446      // Handle the uncommon case of "123[Ptr]".
5447     BaseExpr = RHSExp;
5448     IndexExpr = LHSExp;
5449     ResultType = PTy->getPointeeType();
5450     if (!LangOpts.isSubscriptPointerArithmetic()) {
5451       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5452         << ResultType << BaseExpr->getSourceRange();
5453       return ExprError();
5454     }
5455   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5456     BaseExpr = LHSExp;    // vectors: V[123]
5457     IndexExpr = RHSExp;
5458     // We apply C++ DR1213 to vector subscripting too.
5459     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5460       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5461       if (Materialized.isInvalid())
5462         return ExprError();
5463       LHSExp = Materialized.get();
5464     }
5465     VK = LHSExp->getValueKind();
5466     if (VK != VK_RValue)
5467       OK = OK_VectorComponent;
5468 
5469     ResultType = VTy->getElementType();
5470     QualType BaseType = BaseExpr->getType();
5471     Qualifiers BaseQuals = BaseType.getQualifiers();
5472     Qualifiers MemberQuals = ResultType.getQualifiers();
5473     Qualifiers Combined = BaseQuals + MemberQuals;
5474     if (Combined != MemberQuals)
5475       ResultType = Context.getQualifiedType(ResultType, Combined);
5476   } else if (LHSTy->isArrayType()) {
5477     // If we see an array that wasn't promoted by
5478     // DefaultFunctionArrayLvalueConversion, it must be an array that
5479     // wasn't promoted because of the C90 rule that doesn't
5480     // allow promoting non-lvalue arrays.  Warn, then
5481     // force the promotion here.
5482     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5483         << LHSExp->getSourceRange();
5484     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5485                                CK_ArrayToPointerDecay).get();
5486     LHSTy = LHSExp->getType();
5487 
5488     BaseExpr = LHSExp;
5489     IndexExpr = RHSExp;
5490     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5491   } else if (RHSTy->isArrayType()) {
5492     // Same as previous, except for 123[f().a] case
5493     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5494         << RHSExp->getSourceRange();
5495     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5496                                CK_ArrayToPointerDecay).get();
5497     RHSTy = RHSExp->getType();
5498 
5499     BaseExpr = RHSExp;
5500     IndexExpr = LHSExp;
5501     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5502   } else {
5503     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5504        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5505   }
5506   // C99 6.5.2.1p1
5507   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5508     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5509                      << IndexExpr->getSourceRange());
5510 
5511   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5512        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5513          && !IndexExpr->isTypeDependent())
5514     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5515 
5516   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5517   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5518   // type. Note that Functions are not objects, and that (in C99 parlance)
5519   // incomplete types are not object types.
5520   if (ResultType->isFunctionType()) {
5521     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5522         << ResultType << BaseExpr->getSourceRange();
5523     return ExprError();
5524   }
5525 
5526   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5527     // GNU extension: subscripting on pointer to void
5528     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5529       << BaseExpr->getSourceRange();
5530 
5531     // C forbids expressions of unqualified void type from being l-values.
5532     // See IsCForbiddenLValueType.
5533     if (!ResultType.hasQualifiers()) VK = VK_RValue;
5534   } else if (!ResultType->isDependentType() &&
5535              RequireCompleteSizedType(
5536                  LLoc, ResultType,
5537                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5538     return ExprError();
5539 
5540   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5541          !ResultType.isCForbiddenLValueType());
5542 
5543   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5544       FunctionScopes.size() > 1) {
5545     if (auto *TT =
5546             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5547       for (auto I = FunctionScopes.rbegin(),
5548                 E = std::prev(FunctionScopes.rend());
5549            I != E; ++I) {
5550         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5551         if (CSI == nullptr)
5552           break;
5553         DeclContext *DC = nullptr;
5554         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5555           DC = LSI->CallOperator;
5556         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5557           DC = CRSI->TheCapturedDecl;
5558         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5559           DC = BSI->TheDecl;
5560         if (DC) {
5561           if (DC->containsDecl(TT->getDecl()))
5562             break;
5563           captureVariablyModifiedType(
5564               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5565         }
5566       }
5567     }
5568   }
5569 
5570   return new (Context)
5571       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5572 }
5573 
CheckCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5574 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5575                                   ParmVarDecl *Param) {
5576   if (Param->hasUnparsedDefaultArg()) {
5577     // If we've already cleared out the location for the default argument,
5578     // that means we're parsing it right now.
5579     if (!UnparsedDefaultArgLocs.count(Param)) {
5580       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5581       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5582       Param->setInvalidDecl();
5583       return true;
5584     }
5585 
5586     Diag(CallLoc,
5587          diag::err_use_of_default_argument_to_function_declared_later) <<
5588       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5589     Diag(UnparsedDefaultArgLocs[Param],
5590          diag::note_default_argument_declared_here);
5591     return true;
5592   }
5593 
5594   if (Param->hasUninstantiatedDefaultArg() &&
5595       InstantiateDefaultArgument(CallLoc, FD, Param))
5596     return true;
5597 
5598   assert(Param->hasInit() && "default argument but no initializer?");
5599 
5600   // If the default expression creates temporaries, we need to
5601   // push them to the current stack of expression temporaries so they'll
5602   // be properly destroyed.
5603   // FIXME: We should really be rebuilding the default argument with new
5604   // bound temporaries; see the comment in PR5810.
5605   // We don't need to do that with block decls, though, because
5606   // blocks in default argument expression can never capture anything.
5607   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5608     // Set the "needs cleanups" bit regardless of whether there are
5609     // any explicit objects.
5610     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5611 
5612     // Append all the objects to the cleanup list.  Right now, this
5613     // should always be a no-op, because blocks in default argument
5614     // expressions should never be able to capture anything.
5615     assert(!Init->getNumObjects() &&
5616            "default argument expression has capturing blocks?");
5617   }
5618 
5619   // We already type-checked the argument, so we know it works.
5620   // Just mark all of the declarations in this potentially-evaluated expression
5621   // as being "referenced".
5622   EnterExpressionEvaluationContext EvalContext(
5623       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5624   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5625                                    /*SkipLocalVariables=*/true);
5626   return false;
5627 }
5628 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5629 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5630                                         FunctionDecl *FD, ParmVarDecl *Param) {
5631   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5632   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5633     return ExprError();
5634   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5635 }
5636 
5637 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)5638 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5639                           Expr *Fn) {
5640   if (Proto && Proto->isVariadic()) {
5641     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5642       return VariadicConstructor;
5643     else if (Fn && Fn->getType()->isBlockPointerType())
5644       return VariadicBlock;
5645     else if (FDecl) {
5646       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5647         if (Method->isInstance())
5648           return VariadicMethod;
5649     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5650       return VariadicMethod;
5651     return VariadicFunction;
5652   }
5653   return VariadicDoesNotApply;
5654 }
5655 
5656 namespace {
5657 class FunctionCallCCC final : public FunctionCallFilterCCC {
5658 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)5659   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5660                   unsigned NumArgs, MemberExpr *ME)
5661       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5662         FunctionName(FuncName) {}
5663 
ValidateCandidate(const TypoCorrection & candidate)5664   bool ValidateCandidate(const TypoCorrection &candidate) override {
5665     if (!candidate.getCorrectionSpecifier() ||
5666         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5667       return false;
5668     }
5669 
5670     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5671   }
5672 
clone()5673   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5674     return std::make_unique<FunctionCallCCC>(*this);
5675   }
5676 
5677 private:
5678   const IdentifierInfo *const FunctionName;
5679 };
5680 }
5681 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)5682 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5683                                                FunctionDecl *FDecl,
5684                                                ArrayRef<Expr *> Args) {
5685   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5686   DeclarationName FuncName = FDecl->getDeclName();
5687   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5688 
5689   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5690   if (TypoCorrection Corrected = S.CorrectTypo(
5691           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5692           S.getScopeForContext(S.CurContext), nullptr, CCC,
5693           Sema::CTK_ErrorRecovery)) {
5694     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5695       if (Corrected.isOverloaded()) {
5696         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5697         OverloadCandidateSet::iterator Best;
5698         for (NamedDecl *CD : Corrected) {
5699           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5700             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5701                                    OCS);
5702         }
5703         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5704         case OR_Success:
5705           ND = Best->FoundDecl;
5706           Corrected.setCorrectionDecl(ND);
5707           break;
5708         default:
5709           break;
5710         }
5711       }
5712       ND = ND->getUnderlyingDecl();
5713       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5714         return Corrected;
5715     }
5716   }
5717   return TypoCorrection();
5718 }
5719 
5720 /// ConvertArgumentsForCall - Converts the arguments specified in
5721 /// Args/NumArgs to the parameter types of the function FDecl with
5722 /// function prototype Proto. Call is the call expression itself, and
5723 /// Fn is the function expression. For a C++ member function, this
5724 /// routine does not attempt to convert the object argument. Returns
5725 /// true if the call is ill-formed.
5726 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)5727 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5728                               FunctionDecl *FDecl,
5729                               const FunctionProtoType *Proto,
5730                               ArrayRef<Expr *> Args,
5731                               SourceLocation RParenLoc,
5732                               bool IsExecConfig) {
5733   // Bail out early if calling a builtin with custom typechecking.
5734   if (FDecl)
5735     if (unsigned ID = FDecl->getBuiltinID())
5736       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5737         return false;
5738 
5739   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5740   // assignment, to the types of the corresponding parameter, ...
5741   unsigned NumParams = Proto->getNumParams();
5742   bool Invalid = false;
5743   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5744   unsigned FnKind = Fn->getType()->isBlockPointerType()
5745                        ? 1 /* block */
5746                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5747                                        : 0 /* function */);
5748 
5749   // If too few arguments are available (and we don't have default
5750   // arguments for the remaining parameters), don't make the call.
5751   if (Args.size() < NumParams) {
5752     if (Args.size() < MinArgs) {
5753       TypoCorrection TC;
5754       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5755         unsigned diag_id =
5756             MinArgs == NumParams && !Proto->isVariadic()
5757                 ? diag::err_typecheck_call_too_few_args_suggest
5758                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5759         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5760                                         << static_cast<unsigned>(Args.size())
5761                                         << TC.getCorrectionRange());
5762       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5763         Diag(RParenLoc,
5764              MinArgs == NumParams && !Proto->isVariadic()
5765                  ? diag::err_typecheck_call_too_few_args_one
5766                  : diag::err_typecheck_call_too_few_args_at_least_one)
5767             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5768       else
5769         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5770                             ? diag::err_typecheck_call_too_few_args
5771                             : diag::err_typecheck_call_too_few_args_at_least)
5772             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5773             << Fn->getSourceRange();
5774 
5775       // Emit the location of the prototype.
5776       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5777         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5778 
5779       return true;
5780     }
5781     // We reserve space for the default arguments when we create
5782     // the call expression, before calling ConvertArgumentsForCall.
5783     assert((Call->getNumArgs() == NumParams) &&
5784            "We should have reserved space for the default arguments before!");
5785   }
5786 
5787   // If too many are passed and not variadic, error on the extras and drop
5788   // them.
5789   if (Args.size() > NumParams) {
5790     if (!Proto->isVariadic()) {
5791       TypoCorrection TC;
5792       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5793         unsigned diag_id =
5794             MinArgs == NumParams && !Proto->isVariadic()
5795                 ? diag::err_typecheck_call_too_many_args_suggest
5796                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5797         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5798                                         << static_cast<unsigned>(Args.size())
5799                                         << TC.getCorrectionRange());
5800       } else if (NumParams == 1 && FDecl &&
5801                  FDecl->getParamDecl(0)->getDeclName())
5802         Diag(Args[NumParams]->getBeginLoc(),
5803              MinArgs == NumParams
5804                  ? diag::err_typecheck_call_too_many_args_one
5805                  : diag::err_typecheck_call_too_many_args_at_most_one)
5806             << FnKind << FDecl->getParamDecl(0)
5807             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5808             << SourceRange(Args[NumParams]->getBeginLoc(),
5809                            Args.back()->getEndLoc());
5810       else
5811         Diag(Args[NumParams]->getBeginLoc(),
5812              MinArgs == NumParams
5813                  ? diag::err_typecheck_call_too_many_args
5814                  : diag::err_typecheck_call_too_many_args_at_most)
5815             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5816             << Fn->getSourceRange()
5817             << SourceRange(Args[NumParams]->getBeginLoc(),
5818                            Args.back()->getEndLoc());
5819 
5820       // Emit the location of the prototype.
5821       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5822         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5823 
5824       // This deletes the extra arguments.
5825       Call->shrinkNumArgs(NumParams);
5826       return true;
5827     }
5828   }
5829   SmallVector<Expr *, 8> AllArgs;
5830   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5831 
5832   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5833                                    AllArgs, CallType);
5834   if (Invalid)
5835     return true;
5836   unsigned TotalNumArgs = AllArgs.size();
5837   for (unsigned i = 0; i < TotalNumArgs; ++i)
5838     Call->setArg(i, AllArgs[i]);
5839 
5840   return false;
5841 }
5842 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)5843 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5844                                   const FunctionProtoType *Proto,
5845                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5846                                   SmallVectorImpl<Expr *> &AllArgs,
5847                                   VariadicCallType CallType, bool AllowExplicit,
5848                                   bool IsListInitialization) {
5849   unsigned NumParams = Proto->getNumParams();
5850   bool Invalid = false;
5851   size_t ArgIx = 0;
5852   // Continue to check argument types (even if we have too few/many args).
5853   for (unsigned i = FirstParam; i < NumParams; i++) {
5854     QualType ProtoArgType = Proto->getParamType(i);
5855 
5856     Expr *Arg;
5857     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5858     if (ArgIx < Args.size()) {
5859       Arg = Args[ArgIx++];
5860 
5861       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5862                               diag::err_call_incomplete_argument, Arg))
5863         return true;
5864 
5865       // Strip the unbridged-cast placeholder expression off, if applicable.
5866       bool CFAudited = false;
5867       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5868           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5869           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5870         Arg = stripARCUnbridgedCast(Arg);
5871       else if (getLangOpts().ObjCAutoRefCount &&
5872                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5873                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5874         CFAudited = true;
5875 
5876       if (Proto->getExtParameterInfo(i).isNoEscape())
5877         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5878           BE->getBlockDecl()->setDoesNotEscape();
5879 
5880       InitializedEntity Entity =
5881           Param ? InitializedEntity::InitializeParameter(Context, Param,
5882                                                          ProtoArgType)
5883                 : InitializedEntity::InitializeParameter(
5884                       Context, ProtoArgType, Proto->isParamConsumed(i));
5885 
5886       // Remember that parameter belongs to a CF audited API.
5887       if (CFAudited)
5888         Entity.setParameterCFAudited();
5889 
5890       ExprResult ArgE = PerformCopyInitialization(
5891           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5892       if (ArgE.isInvalid())
5893         return true;
5894 
5895       Arg = ArgE.getAs<Expr>();
5896     } else {
5897       assert(Param && "can't use default arguments without a known callee");
5898 
5899       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5900       if (ArgExpr.isInvalid())
5901         return true;
5902 
5903       Arg = ArgExpr.getAs<Expr>();
5904     }
5905 
5906     // Check for array bounds violations for each argument to the call. This
5907     // check only triggers warnings when the argument isn't a more complex Expr
5908     // with its own checking, such as a BinaryOperator.
5909     CheckArrayAccess(Arg);
5910 
5911     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5912     CheckStaticArrayArgument(CallLoc, Param, Arg);
5913 
5914     AllArgs.push_back(Arg);
5915   }
5916 
5917   // If this is a variadic call, handle args passed through "...".
5918   if (CallType != VariadicDoesNotApply) {
5919     // Assume that extern "C" functions with variadic arguments that
5920     // return __unknown_anytype aren't *really* variadic.
5921     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5922         FDecl->isExternC()) {
5923       for (Expr *A : Args.slice(ArgIx)) {
5924         QualType paramType; // ignored
5925         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5926         Invalid |= arg.isInvalid();
5927         AllArgs.push_back(arg.get());
5928       }
5929 
5930     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5931     } else {
5932       for (Expr *A : Args.slice(ArgIx)) {
5933         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5934         Invalid |= Arg.isInvalid();
5935         AllArgs.push_back(Arg.get());
5936       }
5937     }
5938 
5939     // Check for array bounds violations.
5940     for (Expr *A : Args.slice(ArgIx))
5941       CheckArrayAccess(A);
5942   }
5943   return Invalid;
5944 }
5945 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)5946 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5947   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5948   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5949     TL = DTL.getOriginalLoc();
5950   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5951     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5952       << ATL.getLocalSourceRange();
5953 }
5954 
5955 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5956 /// array parameter, check that it is non-null, and that if it is formed by
5957 /// array-to-pointer decay, the underlying array is sufficiently large.
5958 ///
5959 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5960 /// array type derivation, then for each call to the function, the value of the
5961 /// corresponding actual argument shall provide access to the first element of
5962 /// an array with at least as many elements as specified by the size expression.
5963 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)5964 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5965                                ParmVarDecl *Param,
5966                                const Expr *ArgExpr) {
5967   // Static array parameters are not supported in C++.
5968   if (!Param || getLangOpts().CPlusPlus)
5969     return;
5970 
5971   QualType OrigTy = Param->getOriginalType();
5972 
5973   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5974   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5975     return;
5976 
5977   if (ArgExpr->isNullPointerConstant(Context,
5978                                      Expr::NPC_NeverValueDependent)) {
5979     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5980     DiagnoseCalleeStaticArrayParam(*this, Param);
5981     return;
5982   }
5983 
5984   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5985   if (!CAT)
5986     return;
5987 
5988   const ConstantArrayType *ArgCAT =
5989     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5990   if (!ArgCAT)
5991     return;
5992 
5993   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5994                                              ArgCAT->getElementType())) {
5995     if (ArgCAT->getSize().ult(CAT->getSize())) {
5996       Diag(CallLoc, diag::warn_static_array_too_small)
5997           << ArgExpr->getSourceRange()
5998           << (unsigned)ArgCAT->getSize().getZExtValue()
5999           << (unsigned)CAT->getSize().getZExtValue() << 0;
6000       DiagnoseCalleeStaticArrayParam(*this, Param);
6001     }
6002     return;
6003   }
6004 
6005   Optional<CharUnits> ArgSize =
6006       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6007   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6008   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6009     Diag(CallLoc, diag::warn_static_array_too_small)
6010         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6011         << (unsigned)ParmSize->getQuantity() << 1;
6012     DiagnoseCalleeStaticArrayParam(*this, Param);
6013   }
6014 }
6015 
6016 /// Given a function expression of unknown-any type, try to rebuild it
6017 /// to have a function type.
6018 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6019 
6020 /// Is the given type a placeholder that we need to lower out
6021 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)6022 static bool isPlaceholderToRemoveAsArg(QualType type) {
6023   // Placeholders are never sugared.
6024   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6025   if (!placeholder) return false;
6026 
6027   switch (placeholder->getKind()) {
6028   // Ignore all the non-placeholder types.
6029 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6030   case BuiltinType::Id:
6031 #include "clang/Basic/OpenCLImageTypes.def"
6032 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6033   case BuiltinType::Id:
6034 #include "clang/Basic/OpenCLExtensionTypes.def"
6035   // In practice we'll never use this, since all SVE types are sugared
6036   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6037 #define SVE_TYPE(Name, Id, SingletonId) \
6038   case BuiltinType::Id:
6039 #include "clang/Basic/AArch64SVEACLETypes.def"
6040 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6041 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6042 #include "clang/AST/BuiltinTypes.def"
6043     return false;
6044 
6045   // We cannot lower out overload sets; they might validly be resolved
6046   // by the call machinery.
6047   case BuiltinType::Overload:
6048     return false;
6049 
6050   // Unbridged casts in ARC can be handled in some call positions and
6051   // should be left in place.
6052   case BuiltinType::ARCUnbridgedCast:
6053     return false;
6054 
6055   // Pseudo-objects should be converted as soon as possible.
6056   case BuiltinType::PseudoObject:
6057     return true;
6058 
6059   // The debugger mode could theoretically but currently does not try
6060   // to resolve unknown-typed arguments based on known parameter types.
6061   case BuiltinType::UnknownAny:
6062     return true;
6063 
6064   // These are always invalid as call arguments and should be reported.
6065   case BuiltinType::BoundMember:
6066   case BuiltinType::BuiltinFn:
6067   case BuiltinType::IncompleteMatrixIdx:
6068   case BuiltinType::OMPArraySection:
6069   case BuiltinType::OMPArrayShaping:
6070   case BuiltinType::OMPIterator:
6071     return true;
6072 
6073   }
6074   llvm_unreachable("bad builtin type kind");
6075 }
6076 
6077 /// Check an argument list for placeholders that we won't try to
6078 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)6079 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6080   // Apply this processing to all the arguments at once instead of
6081   // dying at the first failure.
6082   bool hasInvalid = false;
6083   for (size_t i = 0, e = args.size(); i != e; i++) {
6084     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6085       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6086       if (result.isInvalid()) hasInvalid = true;
6087       else args[i] = result.get();
6088     } else if (hasInvalid) {
6089       (void)S.CorrectDelayedTyposInExpr(args[i]);
6090     }
6091   }
6092   return hasInvalid;
6093 }
6094 
6095 /// If a builtin function has a pointer argument with no explicit address
6096 /// space, then it should be able to accept a pointer to any address
6097 /// space as input.  In order to do this, we need to replace the
6098 /// standard builtin declaration with one that uses the same address space
6099 /// as the call.
6100 ///
6101 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6102 ///                  it does not contain any pointer arguments without
6103 ///                  an address space qualifer.  Otherwise the rewritten
6104 ///                  FunctionDecl is returned.
6105 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,FunctionDecl * FDecl,MultiExprArg ArgExprs)6106 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6107                                                 FunctionDecl *FDecl,
6108                                                 MultiExprArg ArgExprs) {
6109 
6110   QualType DeclType = FDecl->getType();
6111   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6112 
6113   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6114       ArgExprs.size() < FT->getNumParams())
6115     return nullptr;
6116 
6117   bool NeedsNewDecl = false;
6118   unsigned i = 0;
6119   SmallVector<QualType, 8> OverloadParams;
6120 
6121   for (QualType ParamType : FT->param_types()) {
6122 
6123     // Convert array arguments to pointer to simplify type lookup.
6124     ExprResult ArgRes =
6125         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6126     if (ArgRes.isInvalid())
6127       return nullptr;
6128     Expr *Arg = ArgRes.get();
6129     QualType ArgType = Arg->getType();
6130     if (!ParamType->isPointerType() ||
6131         ParamType.hasAddressSpace() ||
6132         !ArgType->isPointerType() ||
6133         !ArgType->getPointeeType().hasAddressSpace()) {
6134       OverloadParams.push_back(ParamType);
6135       continue;
6136     }
6137 
6138     QualType PointeeType = ParamType->getPointeeType();
6139     if (PointeeType.hasAddressSpace())
6140       continue;
6141 
6142     NeedsNewDecl = true;
6143     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6144 
6145     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6146     OverloadParams.push_back(Context.getPointerType(PointeeType));
6147   }
6148 
6149   if (!NeedsNewDecl)
6150     return nullptr;
6151 
6152   FunctionProtoType::ExtProtoInfo EPI;
6153   EPI.Variadic = FT->isVariadic();
6154   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6155                                                 OverloadParams, EPI);
6156   DeclContext *Parent = FDecl->getParent();
6157   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6158                                                     FDecl->getLocation(),
6159                                                     FDecl->getLocation(),
6160                                                     FDecl->getIdentifier(),
6161                                                     OverloadTy,
6162                                                     /*TInfo=*/nullptr,
6163                                                     SC_Extern, false,
6164                                                     /*hasPrototype=*/true);
6165   SmallVector<ParmVarDecl*, 16> Params;
6166   FT = cast<FunctionProtoType>(OverloadTy);
6167   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6168     QualType ParamType = FT->getParamType(i);
6169     ParmVarDecl *Parm =
6170         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6171                                 SourceLocation(), nullptr, ParamType,
6172                                 /*TInfo=*/nullptr, SC_None, nullptr);
6173     Parm->setScopeInfo(0, i);
6174     Params.push_back(Parm);
6175   }
6176   OverloadDecl->setParams(Params);
6177   return OverloadDecl;
6178 }
6179 
checkDirectCallValidity(Sema & S,const Expr * Fn,FunctionDecl * Callee,MultiExprArg ArgExprs)6180 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6181                                     FunctionDecl *Callee,
6182                                     MultiExprArg ArgExprs) {
6183 
6184   // For purecap CHERI, output a warning if the callee doesn't have a prototype
6185   // and we are passing arguments. This would normally lead to using the
6186   // variadic calling convention. In the case of MIPS CHERI, this could lead to
6187   // runtime stack corruption if the callee function is not actually variadic.
6188   if (S.Context.getTargetInfo().SupportsCapabilities()) {
6189     bool NoProto = !Callee->getBuiltinID() && Callee->getType()->isFunctionNoProtoType();
6190     if (NoProto && ArgExprs.size() > 0) {
6191       S.Diag(Fn->getBeginLoc(), diag::warn_cheri_call_no_func_proto)
6192           << Callee->getName() << Fn->getSourceRange();
6193       S.Diag(Callee->getLocation(), diag::note_cheri_func_decl_add_types);
6194       S.Diag(Fn->getBeginLoc(), diag::note_cheri_func_noproto_explanation);
6195       return;
6196     }
6197   }
6198 
6199   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6200   // similar attributes) really don't like it when functions are called with an
6201   // invalid number of args.
6202   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6203                          /*PartialOverloading=*/false) &&
6204       !Callee->isVariadic())
6205     return;
6206   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6207     return;
6208 
6209   if (const EnableIfAttr *Attr =
6210           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6211     S.Diag(Fn->getBeginLoc(),
6212            isa<CXXMethodDecl>(Callee)
6213                ? diag::err_ovl_no_viable_member_function_in_call
6214                : diag::err_ovl_no_viable_function_in_call)
6215         << Callee << Callee->getSourceRange();
6216     S.Diag(Callee->getLocation(),
6217            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6218         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6219     return;
6220   }
6221 }
6222 
enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr * const UME,Sema & S)6223 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6224     const UnresolvedMemberExpr *const UME, Sema &S) {
6225 
6226   const auto GetFunctionLevelDCIfCXXClass =
6227       [](Sema &S) -> const CXXRecordDecl * {
6228     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6229     if (!DC || !DC->getParent())
6230       return nullptr;
6231 
6232     // If the call to some member function was made from within a member
6233     // function body 'M' return return 'M's parent.
6234     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6235       return MD->getParent()->getCanonicalDecl();
6236     // else the call was made from within a default member initializer of a
6237     // class, so return the class.
6238     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6239       return RD->getCanonicalDecl();
6240     return nullptr;
6241   };
6242   // If our DeclContext is neither a member function nor a class (in the
6243   // case of a lambda in a default member initializer), we can't have an
6244   // enclosing 'this'.
6245 
6246   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6247   if (!CurParentClass)
6248     return false;
6249 
6250   // The naming class for implicit member functions call is the class in which
6251   // name lookup starts.
6252   const CXXRecordDecl *const NamingClass =
6253       UME->getNamingClass()->getCanonicalDecl();
6254   assert(NamingClass && "Must have naming class even for implicit access");
6255 
6256   // If the unresolved member functions were found in a 'naming class' that is
6257   // related (either the same or derived from) to the class that contains the
6258   // member function that itself contained the implicit member access.
6259 
6260   return CurParentClass == NamingClass ||
6261          CurParentClass->isDerivedFrom(NamingClass);
6262 }
6263 
6264 static void
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema & S,const UnresolvedMemberExpr * const UME,SourceLocation CallLoc)6265 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6266     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6267 
6268   if (!UME)
6269     return;
6270 
6271   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6272   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6273   // already been captured, or if this is an implicit member function call (if
6274   // it isn't, an attempt to capture 'this' should already have been made).
6275   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6276       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6277     return;
6278 
6279   // Check if the naming class in which the unresolved members were found is
6280   // related (same as or is a base of) to the enclosing class.
6281 
6282   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6283     return;
6284 
6285 
6286   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6287   // If the enclosing function is not dependent, then this lambda is
6288   // capture ready, so if we can capture this, do so.
6289   if (!EnclosingFunctionCtx->isDependentContext()) {
6290     // If the current lambda and all enclosing lambdas can capture 'this' -
6291     // then go ahead and capture 'this' (since our unresolved overload set
6292     // contains at least one non-static member function).
6293     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6294       S.CheckCXXThisCapture(CallLoc);
6295   } else if (S.CurContext->isDependentContext()) {
6296     // ... since this is an implicit member reference, that might potentially
6297     // involve a 'this' capture, mark 'this' for potential capture in
6298     // enclosing lambdas.
6299     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6300       CurLSI->addPotentialThisCapture(CallLoc);
6301   }
6302 }
6303 
ActOnCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig)6304 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6305                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6306                                Expr *ExecConfig) {
6307   ExprResult Call =
6308       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6309   if (Call.isInvalid())
6310     return Call;
6311 
6312   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6313   // language modes.
6314   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6315     if (ULE->hasExplicitTemplateArgs() &&
6316         ULE->decls_begin() == ULE->decls_end()) {
6317       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6318                                  ? diag::warn_cxx17_compat_adl_only_template_id
6319                                  : diag::ext_adl_only_template_id)
6320           << ULE->getName();
6321     }
6322   }
6323 
6324   if (LangOpts.OpenMP)
6325     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6326                            ExecConfig);
6327 
6328   return Call;
6329 }
6330 
6331 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6332 /// This provides the location of the left/right parens and a list of comma
6333 /// locations.
BuildCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)6334 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6335                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6336                                Expr *ExecConfig, bool IsExecConfig) {
6337   // Since this might be a postfix expression, get rid of ParenListExprs.
6338   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6339   if (Result.isInvalid()) return ExprError();
6340   Fn = Result.get();
6341 
6342   if (checkArgsForPlaceholders(*this, ArgExprs))
6343     return ExprError();
6344 
6345   if (getLangOpts().CPlusPlus) {
6346     // If this is a pseudo-destructor expression, build the call immediately.
6347     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6348       if (!ArgExprs.empty()) {
6349         // Pseudo-destructor calls should not have any arguments.
6350         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6351             << FixItHint::CreateRemoval(
6352                    SourceRange(ArgExprs.front()->getBeginLoc(),
6353                                ArgExprs.back()->getEndLoc()));
6354       }
6355 
6356       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6357                               VK_RValue, RParenLoc);
6358     }
6359     if (Fn->getType() == Context.PseudoObjectTy) {
6360       ExprResult result = CheckPlaceholderExpr(Fn);
6361       if (result.isInvalid()) return ExprError();
6362       Fn = result.get();
6363     }
6364 
6365     // Determine whether this is a dependent call inside a C++ template,
6366     // in which case we won't do any semantic analysis now.
6367     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6368       if (ExecConfig) {
6369         return CUDAKernelCallExpr::Create(
6370             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6371             Context.DependentTy, VK_RValue, RParenLoc);
6372       } else {
6373 
6374         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6375             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6376             Fn->getBeginLoc());
6377 
6378         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6379                                 VK_RValue, RParenLoc);
6380       }
6381     }
6382 
6383     // Determine whether this is a call to an object (C++ [over.call.object]).
6384     if (Fn->getType()->isRecordType())
6385       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6386                                           RParenLoc);
6387 
6388     if (Fn->getType() == Context.UnknownAnyTy) {
6389       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6390       if (result.isInvalid()) return ExprError();
6391       Fn = result.get();
6392     }
6393 
6394     if (Fn->getType() == Context.BoundMemberTy) {
6395       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6396                                        RParenLoc);
6397     }
6398   }
6399 
6400   // Check for overloaded calls.  This can happen even in C due to extensions.
6401   if (Fn->getType() == Context.OverloadTy) {
6402     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6403 
6404     // We aren't supposed to apply this logic if there's an '&' involved.
6405     if (!find.HasFormOfMemberPointer) {
6406       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6407         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6408                                 VK_RValue, RParenLoc);
6409       OverloadExpr *ovl = find.Expression;
6410       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6411         return BuildOverloadedCallExpr(
6412             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6413             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6414       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6415                                        RParenLoc);
6416     }
6417   }
6418 
6419   // If we're directly calling a function, get the appropriate declaration.
6420   if (Fn->getType() == Context.UnknownAnyTy) {
6421     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6422     if (result.isInvalid()) return ExprError();
6423     Fn = result.get();
6424   }
6425 
6426   Expr *NakedFn = Fn->IgnoreParens();
6427 
6428   bool CallingNDeclIndirectly = false;
6429   NamedDecl *NDecl = nullptr;
6430   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6431     if (UnOp->getOpcode() == UO_AddrOf) {
6432       CallingNDeclIndirectly = true;
6433       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6434     }
6435   }
6436 
6437   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6438     NDecl = DRE->getDecl();
6439 
6440     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6441     if (FDecl && FDecl->getBuiltinID()) {
6442       // Rewrite the function decl for this builtin by replacing parameters
6443       // with no explicit address space with the address space of the arguments
6444       // in ArgExprs.
6445       if ((FDecl =
6446                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6447         NDecl = FDecl;
6448         Fn = DeclRefExpr::Create(
6449             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6450             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6451             nullptr, DRE->isNonOdrUse());
6452       }
6453     }
6454   } else if (isa<MemberExpr>(NakedFn))
6455     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6456 
6457   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6458     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6459                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6460       return ExprError();
6461 
6462     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6463       return ExprError();
6464 
6465     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6466   }
6467 
6468   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6469                                ExecConfig, IsExecConfig);
6470 }
6471 
6472 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6473 ///
6474 /// __builtin_astype( value, dst type )
6475 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6476 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6477                                  SourceLocation BuiltinLoc,
6478                                  SourceLocation RParenLoc) {
6479   ExprValueKind VK = VK_RValue;
6480   ExprObjectKind OK = OK_Ordinary;
6481   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6482   QualType SrcTy = E->getType();
6483   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6484     return ExprError(Diag(BuiltinLoc,
6485                           diag::err_invalid_astype_of_different_size)
6486                      << DstTy
6487                      << SrcTy
6488                      << E->getSourceRange());
6489   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6490 }
6491 
6492 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6493 /// provided arguments.
6494 ///
6495 /// __builtin_convertvector( value, dst type )
6496 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6497 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6498                                         SourceLocation BuiltinLoc,
6499                                         SourceLocation RParenLoc) {
6500   TypeSourceInfo *TInfo;
6501   GetTypeFromParser(ParsedDestTy, &TInfo);
6502   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6503 }
6504 
6505 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6506 /// i.e. an expression not of \p OverloadTy.  The expression should
6507 /// unary-convert to an expression of function-pointer or
6508 /// block-pointer type.
6509 ///
6510 /// \param NDecl the declaration being called, if available
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig,ADLCallKind UsesADL)6511 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6512                                        SourceLocation LParenLoc,
6513                                        ArrayRef<Expr *> Args,
6514                                        SourceLocation RParenLoc, Expr *Config,
6515                                        bool IsExecConfig, ADLCallKind UsesADL) {
6516   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6517   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6518 
6519   if (!BuiltinID)
6520     if (NamedDecl *currentDecl = getCurFunctionOrMethodDecl())
6521       if (currentDecl->hasAttr<SensitiveAttr>() &&
6522           (!FDecl || !FDecl->hasAttr<SensitiveAttr>()))
6523         Diag(RParenLoc, diag::warn_calling_non_sensitive_from_sensitive)
6524             << FDecl << currentDecl;
6525 
6526 
6527   // Functions with 'interrupt' attribute cannot be called directly.
6528   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6529     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6530     return ExprError();
6531   }
6532 
6533   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6534   // so there's some risk when calling out to non-interrupt handler functions
6535   // that the callee might not preserve them. This is easy to diagnose here,
6536   // but can be very challenging to debug.
6537   if (auto *Caller = getCurFunctionDecl())
6538     if (Caller->hasAttr<ARMInterruptAttr>()) {
6539       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6540       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6541         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6542     }
6543 
6544   // Promote the function operand.
6545   // We special-case function promotion here because we only allow promoting
6546   // builtin functions to function pointers in the callee of a call.
6547   ExprResult Result;
6548   QualType ResultTy;
6549   if (BuiltinID &&
6550       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6551     // Extract the return type from the (builtin) function pointer type.
6552     // FIXME Several builtins still have setType in
6553     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6554     // Builtins.def to ensure they are correct before removing setType calls.
6555     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6556     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6557     ResultTy = FDecl->getCallResultType();
6558   } else {
6559     Result = CallExprUnaryConversions(Fn);
6560     ResultTy = Context.BoolTy;
6561   }
6562   if (Result.isInvalid())
6563     return ExprError();
6564   Fn = Result.get();
6565 
6566   // Check for a valid function type, but only if it is not a builtin which
6567   // requires custom type checking. These will be handled by
6568   // CheckBuiltinFunctionCall below just after creation of the call expression.
6569   const FunctionType *FuncT = nullptr;
6570   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6571   retry:
6572     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6573       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6574       // have type pointer to function".
6575       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6576       if (!FuncT)
6577         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6578                          << Fn->getType() << Fn->getSourceRange());
6579     } else if (const BlockPointerType *BPT =
6580                    Fn->getType()->getAs<BlockPointerType>()) {
6581       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6582     } else {
6583       // Handle calls to expressions of unknown-any type.
6584       if (Fn->getType() == Context.UnknownAnyTy) {
6585         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6586         if (rewrite.isInvalid())
6587           return ExprError();
6588         Fn = rewrite.get();
6589         goto retry;
6590       }
6591 
6592       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6593                        << Fn->getType() << Fn->getSourceRange());
6594     }
6595   }
6596 
6597   // Get the number of parameters in the function prototype, if any.
6598   // We will allocate space for max(Args.size(), NumParams) arguments
6599   // in the call expression.
6600   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6601   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6602 
6603   CallExpr *TheCall;
6604   if (Config) {
6605     assert(UsesADL == ADLCallKind::NotADL &&
6606            "CUDAKernelCallExpr should not use ADL");
6607     TheCall =
6608         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6609                                    ResultTy, VK_RValue, RParenLoc, NumParams);
6610   } else {
6611     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6612                                RParenLoc, NumParams, UsesADL);
6613   }
6614 
6615   if (!getLangOpts().CPlusPlus) {
6616     // Forget about the nulled arguments since typo correction
6617     // do not handle them well.
6618     TheCall->shrinkNumArgs(Args.size());
6619     // C cannot always handle TypoExpr nodes in builtin calls and direct
6620     // function calls as their argument checking don't necessarily handle
6621     // dependent types properly, so make sure any TypoExprs have been
6622     // dealt with.
6623     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6624     if (!Result.isUsable()) return ExprError();
6625     CallExpr *TheOldCall = TheCall;
6626     TheCall = dyn_cast<CallExpr>(Result.get());
6627     bool CorrectedTypos = TheCall != TheOldCall;
6628     if (!TheCall) return Result;
6629     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6630 
6631     // A new call expression node was created if some typos were corrected.
6632     // However it may not have been constructed with enough storage. In this
6633     // case, rebuild the node with enough storage. The waste of space is
6634     // immaterial since this only happens when some typos were corrected.
6635     if (CorrectedTypos && Args.size() < NumParams) {
6636       if (Config)
6637         TheCall = CUDAKernelCallExpr::Create(
6638             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6639             RParenLoc, NumParams);
6640       else
6641         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6642                                    RParenLoc, NumParams, UsesADL);
6643     }
6644     // We can now handle the nulled arguments for the default arguments.
6645     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6646   }
6647 
6648   // Bail out early if calling a builtin with custom type checking.
6649   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6650     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6651 
6652   if (getLangOpts().CUDA) {
6653     if (Config) {
6654       // CUDA: Kernel calls must be to global functions
6655       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6656         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6657             << FDecl << Fn->getSourceRange());
6658 
6659       // CUDA: Kernel function must have 'void' return type
6660       if (!FuncT->getReturnType()->isVoidType() &&
6661           !FuncT->getReturnType()->getAs<AutoType>() &&
6662           !FuncT->getReturnType()->isInstantiationDependentType())
6663         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6664             << Fn->getType() << Fn->getSourceRange());
6665     } else {
6666       // CUDA: Calls to global functions must be configured
6667       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6668         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6669             << FDecl << Fn->getSourceRange());
6670     }
6671   }
6672 
6673   // Check for a valid return type
6674   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6675                           FDecl))
6676     return ExprError();
6677 
6678   // We know the result type of the call, set it.
6679   TheCall->setType(FuncT->getCallResultType(Context));
6680   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6681 
6682   if (Proto) {
6683     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6684                                 IsExecConfig))
6685       return ExprError();
6686   } else {
6687     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6688 
6689     if (FDecl) {
6690       // Check if we have too few/too many template arguments, based
6691       // on our knowledge of the function definition.
6692       const FunctionDecl *Def = nullptr;
6693       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6694         Proto = Def->getType()->getAs<FunctionProtoType>();
6695        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6696           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6697           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6698       }
6699 
6700       // If the function we're calling isn't a function prototype, but we have
6701       // a function prototype from a prior declaratiom, use that prototype.
6702       if (!FDecl->hasPrototype())
6703         Proto = FDecl->getType()->getAs<FunctionProtoType>();
6704     }
6705 
6706     // Promote the arguments (C99 6.5.2.2p6).
6707     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6708       Expr *Arg = Args[i];
6709 
6710       if (Proto && i < Proto->getNumParams()) {
6711         InitializedEntity Entity = InitializedEntity::InitializeParameter(
6712             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6713         ExprResult ArgE =
6714             PerformCopyInitialization(Entity, SourceLocation(), Arg);
6715         if (ArgE.isInvalid())
6716           return true;
6717 
6718         Arg = ArgE.getAs<Expr>();
6719 
6720       } else {
6721         ExprResult ArgE = DefaultArgumentPromotion(Arg);
6722 
6723         if (ArgE.isInvalid())
6724           return true;
6725 
6726         Arg = ArgE.getAs<Expr>();
6727       }
6728 
6729       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6730                               diag::err_call_incomplete_argument, Arg))
6731         return ExprError();
6732 
6733       TheCall->setArg(i, Arg);
6734     }
6735   }
6736 
6737   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6738     if (!Method->isStatic())
6739       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6740         << Fn->getSourceRange());
6741 
6742   // Check for sentinels
6743   if (NDecl)
6744     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6745 
6746   // Warn for unions passing across security boundary (CMSE).
6747   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6748     for (unsigned i = 0, e = Args.size(); i != e; i++) {
6749       if (const auto *RT =
6750               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6751         if (RT->getDecl()->isOrContainsUnion())
6752           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6753               << 0 << i;
6754       }
6755     }
6756   }
6757 
6758   // Do special checking on direct calls to functions.
6759   if (FDecl) {
6760     if (CheckFunctionCall(FDecl, TheCall, Proto))
6761       return ExprError();
6762 
6763     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6764 
6765     if (BuiltinID)
6766       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6767   } else if (NDecl) {
6768     if (CheckPointerCall(NDecl, TheCall, Proto))
6769       return ExprError();
6770   } else {
6771     if (CheckOtherCall(TheCall, Proto))
6772       return ExprError();
6773   }
6774 
6775   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6776 }
6777 
6778 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)6779 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6780                            SourceLocation RParenLoc, Expr *InitExpr) {
6781   assert(Ty && "ActOnCompoundLiteral(): missing type");
6782   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6783 
6784   TypeSourceInfo *TInfo;
6785   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6786   if (!TInfo)
6787     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6788 
6789   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6790 }
6791 
6792 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)6793 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6794                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6795   QualType literalType = TInfo->getType();
6796 
6797   if (literalType->isArrayType()) {
6798     if (RequireCompleteSizedType(
6799             LParenLoc, Context.getBaseElementType(literalType),
6800             diag::err_array_incomplete_or_sizeless_type,
6801             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6802       return ExprError();
6803     if (literalType->isVariableArrayType())
6804       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6805         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6806   } else if (!literalType->isDependentType() &&
6807              RequireCompleteType(LParenLoc, literalType,
6808                diag::err_typecheck_decl_incomplete_type,
6809                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6810     return ExprError();
6811 
6812   InitializedEntity Entity
6813     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6814   InitializationKind Kind
6815     = InitializationKind::CreateCStyleCast(LParenLoc,
6816                                            SourceRange(LParenLoc, RParenLoc),
6817                                            /*InitList=*/true);
6818   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6819   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6820                                       &literalType);
6821   if (Result.isInvalid())
6822     return ExprError();
6823   LiteralExpr = Result.get();
6824 
6825   bool isFileScope = !CurContext->isFunctionOrMethod();
6826 
6827   // In C, compound literals are l-values for some reason.
6828   // For GCC compatibility, in C++, file-scope array compound literals with
6829   // constant initializers are also l-values, and compound literals are
6830   // otherwise prvalues.
6831   //
6832   // (GCC also treats C++ list-initialized file-scope array prvalues with
6833   // constant initializers as l-values, but that's non-conforming, so we don't
6834   // follow it there.)
6835   //
6836   // FIXME: It would be better to handle the lvalue cases as materializing and
6837   // lifetime-extending a temporary object, but our materialized temporaries
6838   // representation only supports lifetime extension from a variable, not "out
6839   // of thin air".
6840   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6841   // is bound to the result of applying array-to-pointer decay to the compound
6842   // literal.
6843   // FIXME: GCC supports compound literals of reference type, which should
6844   // obviously have a value kind derived from the kind of reference involved.
6845   ExprValueKind VK =
6846       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6847           ? VK_RValue
6848           : VK_LValue;
6849 
6850   if (isFileScope)
6851     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6852       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6853         Expr *Init = ILE->getInit(i);
6854         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6855       }
6856 
6857   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6858                                               VK, LiteralExpr, isFileScope);
6859   if (isFileScope) {
6860     if (!LiteralExpr->isTypeDependent() &&
6861         !LiteralExpr->isValueDependent() &&
6862         !literalType->isDependentType()) // C99 6.5.2.5p3
6863       if (CheckForConstantInitializer(LiteralExpr, literalType))
6864         return ExprError();
6865   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6866              literalType.getAddressSpace() != LangAS::Default) {
6867     // Embedded-C extensions to C99 6.5.2.5:
6868     //   "If the compound literal occurs inside the body of a function, the
6869     //   type name shall not be qualified by an address-space qualifier."
6870     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6871       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6872     return ExprError();
6873   }
6874 
6875   if (!isFileScope && !getLangOpts().CPlusPlus) {
6876     // Compound literals that have automatic storage duration are destroyed at
6877     // the end of the scope in C; in C++, they're just temporaries.
6878 
6879     // Emit diagnostics if it is or contains a C union type that is non-trivial
6880     // to destruct.
6881     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6882       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6883                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6884 
6885     // Diagnose jumps that enter or exit the lifetime of the compound literal.
6886     if (literalType.isDestructedType()) {
6887       Cleanup.setExprNeedsCleanups(true);
6888       ExprCleanupObjects.push_back(E);
6889       getCurFunction()->setHasBranchProtectedScope();
6890     }
6891   }
6892 
6893   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6894       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6895     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6896                                        E->getInitializer()->getExprLoc());
6897 
6898   return MaybeBindToTemporary(E);
6899 }
6900 
6901 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)6902 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6903                     SourceLocation RBraceLoc) {
6904   // Only produce each kind of designated initialization diagnostic once.
6905   SourceLocation FirstDesignator;
6906   bool DiagnosedArrayDesignator = false;
6907   bool DiagnosedNestedDesignator = false;
6908   bool DiagnosedMixedDesignator = false;
6909 
6910   // Check that any designated initializers are syntactically valid in the
6911   // current language mode.
6912   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6913     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6914       if (FirstDesignator.isInvalid())
6915         FirstDesignator = DIE->getBeginLoc();
6916 
6917       if (!getLangOpts().CPlusPlus)
6918         break;
6919 
6920       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6921         DiagnosedNestedDesignator = true;
6922         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6923           << DIE->getDesignatorsSourceRange();
6924       }
6925 
6926       for (auto &Desig : DIE->designators()) {
6927         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6928           DiagnosedArrayDesignator = true;
6929           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6930             << Desig.getSourceRange();
6931         }
6932       }
6933 
6934       if (!DiagnosedMixedDesignator &&
6935           !isa<DesignatedInitExpr>(InitArgList[0])) {
6936         DiagnosedMixedDesignator = true;
6937         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6938           << DIE->getSourceRange();
6939         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6940           << InitArgList[0]->getSourceRange();
6941       }
6942     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6943                isa<DesignatedInitExpr>(InitArgList[0])) {
6944       DiagnosedMixedDesignator = true;
6945       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6946       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6947         << DIE->getSourceRange();
6948       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6949         << InitArgList[I]->getSourceRange();
6950     }
6951   }
6952 
6953   if (FirstDesignator.isValid()) {
6954     // Only diagnose designated initiaization as a C++20 extension if we didn't
6955     // already diagnose use of (non-C++20) C99 designator syntax.
6956     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6957         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6958       Diag(FirstDesignator, getLangOpts().CPlusPlus20
6959                                 ? diag::warn_cxx17_compat_designated_init
6960                                 : diag::ext_cxx_designated_init);
6961     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6962       Diag(FirstDesignator, diag::ext_designated_init);
6963     }
6964   }
6965 
6966   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6967 }
6968 
6969 ExprResult
BuildInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)6970 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6971                     SourceLocation RBraceLoc) {
6972   // Semantic analysis for initializers is done by ActOnDeclarator() and
6973   // CheckInitializer() - it requires knowledge of the object being initialized.
6974 
6975   // Immediately handle non-overload placeholders.  Overloads can be
6976   // resolved contextually, but everything else here can't.
6977   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6978     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6979       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6980 
6981       // Ignore failures; dropping the entire initializer list because
6982       // of one failure would be terrible for indexing/etc.
6983       if (result.isInvalid()) continue;
6984 
6985       InitArgList[I] = result.get();
6986     }
6987   }
6988 
6989   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6990                                                RBraceLoc);
6991   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6992   return E;
6993 }
6994 
6995 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)6996 void Sema::maybeExtendBlockObject(ExprResult &E) {
6997   assert(E.get()->getType()->isBlockPointerType());
6998   assert(E.get()->isRValue());
6999 
7000   // Only do this in an r-value context.
7001   if (!getLangOpts().ObjCAutoRefCount) return;
7002 
7003   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
7004                                CK_ARCExtendBlockObject, E.get(),
7005                                /*base path*/ nullptr, VK_RValue);
7006   Cleanup.setExprNeedsCleanups(true);
7007 }
7008 
7009 /// Prepare a conversion of the given expression to an ObjC object
7010 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)7011 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7012   QualType type = E.get()->getType();
7013   if (type->isObjCObjectPointerType()) {
7014     return CK_BitCast;
7015   } else if (type->isBlockPointerType()) {
7016     maybeExtendBlockObject(E);
7017     return CK_BlockPointerToObjCPointerCast;
7018   } else {
7019     assert(type->isPointerType());
7020     return CK_CPointerToObjCPointerCast;
7021   }
7022 }
7023 
7024 /// Prepares for a scalar cast, performing all the necessary stages
7025 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)7026 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7027   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7028   // Also, callers should have filtered out the invalid cases with
7029   // pointers.  Everything else should be possible.
7030 
7031   QualType SrcTy = Src.get()->getType();
7032   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7033     return CK_NoOp;
7034 
7035   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7036   case Type::STK_MemberPointer:
7037     llvm_unreachable("member pointer type in C");
7038 
7039   case Type::STK_CPointer:
7040   case Type::STK_BlockPointer:
7041   case Type::STK_ObjCObjectPointer:
7042     switch (DestTy->getScalarTypeKind()) {
7043     case Type::STK_CPointer: {
7044       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7045       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7046       if (SrcAS != DestAS)
7047         return CK_AddressSpaceConversion;
7048       else if (!SrcTy->isCHERICapabilityType(Context) && DestTy->isCHERICapabilityType(Context))
7049         return CK_PointerToCHERICapability;
7050       else if (SrcTy->isCHERICapabilityType(Context) && !DestTy->isCHERICapabilityType(Context))
7051         return CK_CHERICapabilityToPointer;
7052       else if (Context.hasCvrSimilarType(SrcTy, DestTy))
7053         return CK_NoOp;
7054       return CK_BitCast;
7055     }
7056     case Type::STK_BlockPointer:
7057       return (SrcKind == Type::STK_BlockPointer
7058                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7059     case Type::STK_ObjCObjectPointer:
7060       if (SrcKind == Type::STK_ObjCObjectPointer)
7061         return CK_BitCast;
7062       if (SrcKind == Type::STK_CPointer)
7063         return CK_CPointerToObjCPointerCast;
7064       maybeExtendBlockObject(Src);
7065       return CK_BlockPointerToObjCPointerCast;
7066     case Type::STK_Bool:
7067       return CK_PointerToBoolean;
7068     case Type::STK_Integral:
7069       return CK_PointerToIntegral;
7070     case Type::STK_Floating:
7071     case Type::STK_FloatingComplex:
7072     case Type::STK_IntegralComplex:
7073     case Type::STK_MemberPointer:
7074     case Type::STK_FixedPoint:
7075       llvm_unreachable("illegal cast from pointer");
7076     }
7077     llvm_unreachable("Should have returned before this");
7078 
7079   case Type::STK_FixedPoint:
7080     switch (DestTy->getScalarTypeKind()) {
7081     case Type::STK_FixedPoint:
7082       return CK_FixedPointCast;
7083     case Type::STK_Bool:
7084       return CK_FixedPointToBoolean;
7085     case Type::STK_Integral:
7086       return CK_FixedPointToIntegral;
7087     case Type::STK_Floating:
7088     case Type::STK_IntegralComplex:
7089     case Type::STK_FloatingComplex:
7090       Diag(Src.get()->getExprLoc(),
7091            diag::err_unimplemented_conversion_with_fixed_point_type)
7092           << DestTy;
7093       return CK_IntegralCast;
7094     case Type::STK_CPointer:
7095     case Type::STK_ObjCObjectPointer:
7096     case Type::STK_BlockPointer:
7097     case Type::STK_MemberPointer:
7098       llvm_unreachable("illegal cast to pointer type");
7099     }
7100     llvm_unreachable("Should have returned before this");
7101 
7102   case Type::STK_Bool: // casting from bool is like casting from an integer
7103   case Type::STK_Integral:
7104     switch (DestTy->getScalarTypeKind()) {
7105     case Type::STK_CPointer:
7106     case Type::STK_ObjCObjectPointer:
7107     case Type::STK_BlockPointer:
7108       if (Src.get()->isNullPointerConstant(Context,
7109                                            Expr::NPC_ValueDependentIsNull))
7110         return CK_NullToPointer;
7111       return CK_IntegralToPointer;
7112     case Type::STK_Bool:
7113       return CK_IntegralToBoolean;
7114     case Type::STK_Integral:
7115       return CK_IntegralCast;
7116     case Type::STK_Floating:
7117       return CK_IntegralToFloating;
7118     case Type::STK_IntegralComplex:
7119       Src = ImpCastExprToType(Src.get(),
7120                       DestTy->castAs<ComplexType>()->getElementType(),
7121                       CK_IntegralCast);
7122       return CK_IntegralRealToComplex;
7123     case Type::STK_FloatingComplex:
7124       Src = ImpCastExprToType(Src.get(),
7125                       DestTy->castAs<ComplexType>()->getElementType(),
7126                       CK_IntegralToFloating);
7127       return CK_FloatingRealToComplex;
7128     case Type::STK_MemberPointer:
7129       llvm_unreachable("member pointer type in C");
7130     case Type::STK_FixedPoint:
7131       return CK_IntegralToFixedPoint;
7132     }
7133     llvm_unreachable("Should have returned before this");
7134 
7135   case Type::STK_Floating:
7136     switch (DestTy->getScalarTypeKind()) {
7137     case Type::STK_Floating:
7138       return CK_FloatingCast;
7139     case Type::STK_Bool:
7140       return CK_FloatingToBoolean;
7141     case Type::STK_Integral:
7142       return CK_FloatingToIntegral;
7143     case Type::STK_FloatingComplex:
7144       Src = ImpCastExprToType(Src.get(),
7145                               DestTy->castAs<ComplexType>()->getElementType(),
7146                               CK_FloatingCast);
7147       return CK_FloatingRealToComplex;
7148     case Type::STK_IntegralComplex:
7149       Src = ImpCastExprToType(Src.get(),
7150                               DestTy->castAs<ComplexType>()->getElementType(),
7151                               CK_FloatingToIntegral);
7152       return CK_IntegralRealToComplex;
7153     case Type::STK_CPointer:
7154     case Type::STK_ObjCObjectPointer:
7155     case Type::STK_BlockPointer:
7156       llvm_unreachable("valid float->pointer cast?");
7157     case Type::STK_MemberPointer:
7158       llvm_unreachable("member pointer type in C");
7159     case Type::STK_FixedPoint:
7160       Diag(Src.get()->getExprLoc(),
7161            diag::err_unimplemented_conversion_with_fixed_point_type)
7162           << SrcTy;
7163       return CK_IntegralCast;
7164     }
7165     llvm_unreachable("Should have returned before this");
7166 
7167   case Type::STK_FloatingComplex:
7168     switch (DestTy->getScalarTypeKind()) {
7169     case Type::STK_FloatingComplex:
7170       return CK_FloatingComplexCast;
7171     case Type::STK_IntegralComplex:
7172       return CK_FloatingComplexToIntegralComplex;
7173     case Type::STK_Floating: {
7174       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7175       if (Context.hasSameType(ET, DestTy))
7176         return CK_FloatingComplexToReal;
7177       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7178       return CK_FloatingCast;
7179     }
7180     case Type::STK_Bool:
7181       return CK_FloatingComplexToBoolean;
7182     case Type::STK_Integral:
7183       Src = ImpCastExprToType(Src.get(),
7184                               SrcTy->castAs<ComplexType>()->getElementType(),
7185                               CK_FloatingComplexToReal);
7186       return CK_FloatingToIntegral;
7187     case Type::STK_CPointer:
7188     case Type::STK_ObjCObjectPointer:
7189     case Type::STK_BlockPointer:
7190       llvm_unreachable("valid complex float->pointer cast?");
7191     case Type::STK_MemberPointer:
7192       llvm_unreachable("member pointer type in C");
7193     case Type::STK_FixedPoint:
7194       Diag(Src.get()->getExprLoc(),
7195            diag::err_unimplemented_conversion_with_fixed_point_type)
7196           << SrcTy;
7197       return CK_IntegralCast;
7198     }
7199     llvm_unreachable("Should have returned before this");
7200 
7201   case Type::STK_IntegralComplex:
7202     switch (DestTy->getScalarTypeKind()) {
7203     case Type::STK_FloatingComplex:
7204       return CK_IntegralComplexToFloatingComplex;
7205     case Type::STK_IntegralComplex:
7206       return CK_IntegralComplexCast;
7207     case Type::STK_Integral: {
7208       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7209       if (Context.hasSameType(ET, DestTy))
7210         return CK_IntegralComplexToReal;
7211       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7212       return CK_IntegralCast;
7213     }
7214     case Type::STK_Bool:
7215       return CK_IntegralComplexToBoolean;
7216     case Type::STK_Floating:
7217       Src = ImpCastExprToType(Src.get(),
7218                               SrcTy->castAs<ComplexType>()->getElementType(),
7219                               CK_IntegralComplexToReal);
7220       return CK_IntegralToFloating;
7221     case Type::STK_CPointer:
7222     case Type::STK_ObjCObjectPointer:
7223     case Type::STK_BlockPointer:
7224       llvm_unreachable("valid complex int->pointer cast?");
7225     case Type::STK_MemberPointer:
7226       llvm_unreachable("member pointer type in C");
7227     case Type::STK_FixedPoint:
7228       Diag(Src.get()->getExprLoc(),
7229            diag::err_unimplemented_conversion_with_fixed_point_type)
7230           << SrcTy;
7231       return CK_IntegralCast;
7232     }
7233     llvm_unreachable("Should have returned before this");
7234   }
7235 
7236   llvm_unreachable("Unhandled scalar cast");
7237 }
7238 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)7239 static bool breakDownVectorType(QualType type, uint64_t &len,
7240                                 QualType &eltType) {
7241   // Vectors are simple.
7242   if (const VectorType *vecType = type->getAs<VectorType>()) {
7243     len = vecType->getNumElements();
7244     eltType = vecType->getElementType();
7245     assert(eltType->isScalarType());
7246     return true;
7247   }
7248 
7249   // We allow lax conversion to and from non-vector types, but only if
7250   // they're real types (i.e. non-complex, non-pointer scalar types).
7251   if (!type->isRealType()) return false;
7252 
7253   len = 1;
7254   eltType = type;
7255   return true;
7256 }
7257 
7258 /// Are the two types lax-compatible vector types?  That is, given
7259 /// that one of them is a vector, do they have equal storage sizes,
7260 /// where the storage size is the number of elements times the element
7261 /// size?
7262 ///
7263 /// This will also return false if either of the types is neither a
7264 /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)7265 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7266   assert(destTy->isVectorType() || srcTy->isVectorType());
7267 
7268   // Disallow lax conversions between scalars and ExtVectors (these
7269   // conversions are allowed for other vector types because common headers
7270   // depend on them).  Most scalar OP ExtVector cases are handled by the
7271   // splat path anyway, which does what we want (convert, not bitcast).
7272   // What this rules out for ExtVectors is crazy things like char4*float.
7273   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7274   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7275 
7276   uint64_t srcLen, destLen;
7277   QualType srcEltTy, destEltTy;
7278   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7279   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7280 
7281   // ASTContext::getTypeSize will return the size rounded up to a
7282   // power of 2, so instead of using that, we need to use the raw
7283   // element size multiplied by the element count.
7284   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7285   uint64_t destEltSize = Context.getTypeSize(destEltTy);
7286 
7287   return (srcLen * srcEltSize == destLen * destEltSize);
7288 }
7289 
7290 /// Is this a legal conversion between two types, one of which is
7291 /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)7292 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7293   assert(destTy->isVectorType() || srcTy->isVectorType());
7294 
7295   switch (Context.getLangOpts().getLaxVectorConversions()) {
7296   case LangOptions::LaxVectorConversionKind::None:
7297     return false;
7298 
7299   case LangOptions::LaxVectorConversionKind::Integer:
7300     if (!srcTy->isIntegralOrEnumerationType()) {
7301       auto *Vec = srcTy->getAs<VectorType>();
7302       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7303         return false;
7304     }
7305     if (!destTy->isIntegralOrEnumerationType()) {
7306       auto *Vec = destTy->getAs<VectorType>();
7307       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7308         return false;
7309     }
7310     // OK, integer (vector) -> integer (vector) bitcast.
7311     break;
7312 
7313     case LangOptions::LaxVectorConversionKind::All:
7314     break;
7315   }
7316 
7317   return areLaxCompatibleVectorTypes(srcTy, destTy);
7318 }
7319 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)7320 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7321                            CastKind &Kind) {
7322   assert(VectorTy->isVectorType() && "Not a vector type!");
7323 
7324   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7325     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7326       return Diag(R.getBegin(),
7327                   Ty->isVectorType() ?
7328                   diag::err_invalid_conversion_between_vectors :
7329                   diag::err_invalid_conversion_between_vector_and_integer)
7330         << VectorTy << Ty << R;
7331   } else
7332     return Diag(R.getBegin(),
7333                 diag::err_invalid_conversion_between_vector_and_scalar)
7334       << VectorTy << Ty << R;
7335 
7336   Kind = CK_BitCast;
7337   return false;
7338 }
7339 
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)7340 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7341   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7342 
7343   if (DestElemTy == SplattedExpr->getType())
7344     return SplattedExpr;
7345 
7346   assert(DestElemTy->isFloatingType() ||
7347          DestElemTy->isIntegralOrEnumerationType());
7348 
7349   CastKind CK;
7350   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7351     // OpenCL requires that we convert `true` boolean expressions to -1, but
7352     // only when splatting vectors.
7353     if (DestElemTy->isFloatingType()) {
7354       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7355       // in two steps: boolean to signed integral, then to floating.
7356       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7357                                                  CK_BooleanToSignedIntegral);
7358       SplattedExpr = CastExprRes.get();
7359       CK = CK_IntegralToFloating;
7360     } else {
7361       CK = CK_BooleanToSignedIntegral;
7362     }
7363   } else {
7364     ExprResult CastExprRes = SplattedExpr;
7365     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7366     if (CastExprRes.isInvalid())
7367       return ExprError();
7368     SplattedExpr = CastExprRes.get();
7369   }
7370   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7371 }
7372 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)7373 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7374                                     Expr *CastExpr, CastKind &Kind) {
7375   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7376 
7377   QualType SrcTy = CastExpr->getType();
7378 
7379   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7380   // an ExtVectorType.
7381   // In OpenCL, casts between vectors of different types are not allowed.
7382   // (See OpenCL 6.2).
7383   if (SrcTy->isVectorType()) {
7384     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7385         (getLangOpts().OpenCL &&
7386          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7387       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7388         << DestTy << SrcTy << R;
7389       return ExprError();
7390     }
7391     Kind = CK_BitCast;
7392     return CastExpr;
7393   }
7394 
7395   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7396   // conversion will take place first from scalar to elt type, and then
7397   // splat from elt type to vector.
7398   if (SrcTy->isPointerType())
7399     return Diag(R.getBegin(),
7400                 diag::err_invalid_conversion_between_vector_and_scalar)
7401       << DestTy << SrcTy << R;
7402 
7403   Kind = CK_VectorSplat;
7404   return prepareVectorSplat(DestTy, CastExpr);
7405 }
7406 
7407 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)7408 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7409                     Declarator &D, ParsedType &Ty,
7410                     SourceLocation RParenLoc, Expr *CastExpr) {
7411   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7412          "ActOnCastExpr(): missing type or expr");
7413 
7414   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7415   if (D.isInvalidType())
7416     return ExprError();
7417 
7418   if (getLangOpts().CPlusPlus) {
7419     // Check that there are no default arguments (C++ only).
7420     CheckExtraCXXDefaultArguments(D);
7421   } else {
7422     // Make sure any TypoExprs have been dealt with.
7423     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7424     if (!Res.isUsable())
7425       return ExprError();
7426     CastExpr = Res.get();
7427   }
7428 
7429   checkUnusedDeclAttributes(D);
7430 
7431   QualType castType = castTInfo->getType();
7432   Ty = CreateParsedType(castType, castTInfo);
7433 
7434   bool isVectorLiteral = false;
7435 
7436   // Check for an altivec or OpenCL literal,
7437   // i.e. all the elements are integer constants.
7438   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7439   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7440   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7441        && castType->isVectorType() && (PE || PLE)) {
7442     if (PLE && PLE->getNumExprs() == 0) {
7443       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7444       return ExprError();
7445     }
7446     if (PE || PLE->getNumExprs() == 1) {
7447       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7448       if (!E->getType()->isVectorType())
7449         isVectorLiteral = true;
7450     }
7451     else
7452       isVectorLiteral = true;
7453   }
7454 
7455   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7456   // then handle it as such.
7457   if (isVectorLiteral)
7458     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7459 
7460   // If the Expr being casted is a ParenListExpr, handle it specially.
7461   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7462   // sequence of BinOp comma operators.
7463   if (isa<ParenListExpr>(CastExpr)) {
7464     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7465     if (Result.isInvalid()) return ExprError();
7466     CastExpr = Result.get();
7467   }
7468 
7469   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7470       !getSourceManager().isInSystemMacro(LParenLoc))
7471     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7472 
7473   CheckTollFreeBridgeCast(castType, CastExpr);
7474 
7475   CheckObjCBridgeRelatedCast(castType, CastExpr);
7476 
7477   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7478 
7479   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7480 }
7481 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)7482 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7483                                     SourceLocation RParenLoc, Expr *E,
7484                                     TypeSourceInfo *TInfo) {
7485   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7486          "Expected paren or paren list expression");
7487 
7488   Expr **exprs;
7489   unsigned numExprs;
7490   Expr *subExpr;
7491   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7492   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7493     LiteralLParenLoc = PE->getLParenLoc();
7494     LiteralRParenLoc = PE->getRParenLoc();
7495     exprs = PE->getExprs();
7496     numExprs = PE->getNumExprs();
7497   } else { // isa<ParenExpr> by assertion at function entrance
7498     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7499     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7500     subExpr = cast<ParenExpr>(E)->getSubExpr();
7501     exprs = &subExpr;
7502     numExprs = 1;
7503   }
7504 
7505   QualType Ty = TInfo->getType();
7506   assert(Ty->isVectorType() && "Expected vector type");
7507 
7508   SmallVector<Expr *, 8> initExprs;
7509   const VectorType *VTy = Ty->castAs<VectorType>();
7510   unsigned numElems = VTy->getNumElements();
7511 
7512   // '(...)' form of vector initialization in AltiVec: the number of
7513   // initializers must be one or must match the size of the vector.
7514   // If a single value is specified in the initializer then it will be
7515   // replicated to all the components of the vector
7516   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7517     // The number of initializers must be one or must match the size of the
7518     // vector. If a single value is specified in the initializer then it will
7519     // be replicated to all the components of the vector
7520     if (numExprs == 1) {
7521       QualType ElemTy = VTy->getElementType();
7522       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7523       if (Literal.isInvalid())
7524         return ExprError();
7525       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7526                                   PrepareScalarCast(Literal, ElemTy));
7527       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7528     }
7529     else if (numExprs < numElems) {
7530       Diag(E->getExprLoc(),
7531            diag::err_incorrect_number_of_vector_initializers);
7532       return ExprError();
7533     }
7534     else
7535       initExprs.append(exprs, exprs + numExprs);
7536   }
7537   else {
7538     // For OpenCL, when the number of initializers is a single value,
7539     // it will be replicated to all components of the vector.
7540     if (getLangOpts().OpenCL &&
7541         VTy->getVectorKind() == VectorType::GenericVector &&
7542         numExprs == 1) {
7543         QualType ElemTy = VTy->getElementType();
7544         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7545         if (Literal.isInvalid())
7546           return ExprError();
7547         Literal = ImpCastExprToType(Literal.get(), ElemTy,
7548                                     PrepareScalarCast(Literal, ElemTy));
7549         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7550     }
7551 
7552     initExprs.append(exprs, exprs + numExprs);
7553   }
7554   // FIXME: This means that pretty-printing the final AST will produce curly
7555   // braces instead of the original commas.
7556   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7557                                                    initExprs, LiteralRParenLoc);
7558   initE->setType(Ty);
7559   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7560 }
7561 
7562 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7563 /// the ParenListExpr into a sequence of comma binary operators.
7564 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)7565 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7566   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7567   if (!E)
7568     return OrigExpr;
7569 
7570   ExprResult Result(E->getExpr(0));
7571 
7572   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7573     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7574                         E->getExpr(i));
7575 
7576   if (Result.isInvalid()) return ExprError();
7577 
7578   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7579 }
7580 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)7581 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7582                                     SourceLocation R,
7583                                     MultiExprArg Val) {
7584   return ParenListExpr::Create(Context, L, Val, R);
7585 }
7586 
7587 /// Emit a specialized diagnostic when one expression is a null pointer
7588 /// constant and the other is not a pointer.  Returns true if a diagnostic is
7589 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)7590 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7591                                       SourceLocation QuestionLoc) {
7592   Expr *NullExpr = LHSExpr;
7593   Expr *NonPointerExpr = RHSExpr;
7594   Expr::NullPointerConstantKind NullKind =
7595       NullExpr->isNullPointerConstant(Context,
7596                                       Expr::NPC_ValueDependentIsNotNull);
7597 
7598   if (NullKind == Expr::NPCK_NotNull) {
7599     NullExpr = RHSExpr;
7600     NonPointerExpr = LHSExpr;
7601     NullKind =
7602         NullExpr->isNullPointerConstant(Context,
7603                                         Expr::NPC_ValueDependentIsNotNull);
7604   }
7605 
7606   if (NullKind == Expr::NPCK_NotNull)
7607     return false;
7608 
7609   if (NullKind == Expr::NPCK_ZeroExpression)
7610     return false;
7611 
7612   if (NullKind == Expr::NPCK_ZeroLiteral) {
7613     // In this case, check to make sure that we got here from a "NULL"
7614     // string in the source code.
7615     NullExpr = NullExpr->IgnoreParenImpCasts();
7616     SourceLocation loc = NullExpr->getExprLoc();
7617     if (!findMacroSpelling(loc, "NULL"))
7618       return false;
7619   }
7620 
7621   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7622   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7623       << NonPointerExpr->getType() << DiagType
7624       << NonPointerExpr->getSourceRange();
7625   return true;
7626 }
7627 
7628 /// Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)7629 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7630   QualType CondTy = Cond->getType();
7631 
7632   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7633   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7634     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7635       << CondTy << Cond->getSourceRange();
7636     return true;
7637   }
7638 
7639   // C99 6.5.15p2
7640   if (CondTy->isScalarType()) return false;
7641 
7642   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7643     << CondTy << Cond->getSourceRange();
7644   return true;
7645 }
7646 
7647 /// Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)7648 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7649                                          ExprResult &RHS) {
7650     Expr *LHSExpr = LHS.get();
7651     Expr *RHSExpr = RHS.get();
7652 
7653     if (!LHSExpr->getType()->isVoidType())
7654       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7655           << RHSExpr->getSourceRange();
7656     if (!RHSExpr->getType()->isVoidType())
7657       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7658           << LHSExpr->getSourceRange();
7659     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7660     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7661     return S.Context.VoidTy;
7662 }
7663 
7664 /// Return false if the NullExpr can be promoted to PointerTy,
7665 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)7666 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7667                                         QualType PointerTy) {
7668   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7669       !NullExpr.get()->isNullPointerConstant(S.Context,
7670                                             Expr::NPC_ValueDependentIsNull))
7671     return true;
7672 
7673   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7674   return false;
7675 }
7676 
7677 /// Checks compatibility between two pointers and return the resulting
7678 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7679 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7680                                                      ExprResult &RHS,
7681                                                      SourceLocation Loc) {
7682   QualType LHSTy = LHS.get()->getType();
7683   QualType RHSTy = RHS.get()->getType();
7684 
7685   if (S.Context.hasSameType(LHSTy, RHSTy)) {
7686     // Two identical pointers types are always compatible.
7687     return LHSTy;
7688   }
7689 
7690   QualType lhptee, rhptee;
7691 
7692   // Get the pointee types.
7693   bool IsBlockPointer = false;
7694   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7695     lhptee = LHSBTy->getPointeeType();
7696     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7697     IsBlockPointer = true;
7698   } else {
7699     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7700     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7701   }
7702 
7703   // C99 6.5.15p6: If both operands are pointers to compatible types or to
7704   // differently qualified versions of compatible types, the result type is
7705   // a pointer to an appropriately qualified version of the composite
7706   // type.
7707 
7708   // Only CVR-qualifiers exist in the standard, and the differently-qualified
7709   // clause doesn't make sense for our extensions. E.g. address space 2 should
7710   // be incompatible with address space 3: they may live on different devices or
7711   // anything.
7712   Qualifiers lhQual = lhptee.getQualifiers();
7713   Qualifiers rhQual = rhptee.getQualifiers();
7714 
7715   LangAS ResultAddrSpace = LangAS::Default;
7716   LangAS LAddrSpace = lhQual.getAddressSpace();
7717   LangAS RAddrSpace = rhQual.getAddressSpace();
7718 
7719   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7720   // spaces is disallowed.
7721   if (lhQual.isAddressSpaceSupersetOf(rhQual))
7722     ResultAddrSpace = LAddrSpace;
7723   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7724     ResultAddrSpace = RAddrSpace;
7725   else {
7726     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7727         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7728         << RHS.get()->getSourceRange();
7729     return QualType();
7730   }
7731 
7732   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7733   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7734   lhQual.removeCVRQualifiers();
7735   rhQual.removeCVRQualifiers();
7736 
7737   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7738   // (C99 6.7.3) for address spaces. We assume that the check should behave in
7739   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7740   // qual types are compatible iff
7741   //  * corresponded types are compatible
7742   //  * CVR qualifiers are equal
7743   //  * address spaces are equal
7744   // Thus for conditional operator we merge CVR and address space unqualified
7745   // pointees and if there is a composite type we return a pointer to it with
7746   // merged qualifiers.
7747   LHSCastKind =
7748       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7749   RHSCastKind =
7750       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7751   lhQual.removeAddressSpace();
7752   rhQual.removeAddressSpace();
7753 
7754   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7755   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7756 
7757   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7758 
7759   if (CompositeTy.isNull()) {
7760     // In this situation, we assume void* type. No especially good
7761     // reason, but this is what gcc does, and we do have to pick
7762     // to get a consistent AST.
7763     QualType incompatTy;
7764     incompatTy = S.Context.getPointerType(
7765         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7766     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7767     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7768 
7769     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7770     // for casts between types with incompatible address space qualifiers.
7771     // For the following code the compiler produces casts between global and
7772     // local address spaces of the corresponded innermost pointees:
7773     // local int *global *a;
7774     // global int *global *b;
7775     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7776     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7777         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7778         << RHS.get()->getSourceRange();
7779 
7780     return incompatTy;
7781   }
7782 
7783   // The pointer types are compatible.
7784   // In case of OpenCL ResultTy should have the address space qualifier
7785   // which is a superset of address spaces of both the 2nd and the 3rd
7786   // operands of the conditional operator.
7787   QualType ResultTy = [&, ResultAddrSpace]() {
7788     if (S.getLangOpts().OpenCL) {
7789       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7790       CompositeQuals.setAddressSpace(ResultAddrSpace);
7791       return S.Context
7792           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7793           .withCVRQualifiers(MergedCVRQual);
7794     }
7795     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7796   }();
7797   if (IsBlockPointer)
7798     ResultTy = S.Context.getBlockPointerType(ResultTy);
7799   else {
7800     PointerInterpretationKind PIK =
7801         S.Context.getDefaultPointerInterpretation();
7802     if (LHSTy->isCHERICapabilityType(S.Context, false) ||
7803         RHSTy->isCHERICapabilityType(S.Context, false)) {
7804       PIK = PIK_Capability;
7805     }
7806     ResultTy = S.Context.getPointerType(ResultTy, PIK);
7807   }
7808 
7809   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7810   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7811   return ResultTy;
7812 }
7813 
7814 /// Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7815 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7816                                                           ExprResult &LHS,
7817                                                           ExprResult &RHS,
7818                                                           SourceLocation Loc) {
7819   QualType LHSTy = LHS.get()->getType();
7820   QualType RHSTy = RHS.get()->getType();
7821 
7822   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7823     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7824       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7825       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7826       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7827       return destType;
7828     }
7829     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7830       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7831       << RHS.get()->getSourceRange();
7832     return QualType();
7833   }
7834 
7835   // We have 2 block pointer types.
7836   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7837 }
7838 
7839 /// Return the resulting type when the operands are both pointers.
7840 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7841 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7842                                             ExprResult &RHS,
7843                                             SourceLocation Loc) {
7844   // get the pointer types
7845   QualType LHSTy = LHS.get()->getType();
7846   QualType RHSTy = RHS.get()->getType();
7847 
7848   // get the "pointed to" types
7849   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7850   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7851 
7852   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7853   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7854     // Figure out necessary qualifiers (C99 6.5.15p6)
7855     QualType destPointee
7856       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7857     QualType destType = S.Context.getPointerType(
7858         destPointee, RHSTy->castAs<PointerType>()->getPointerInterpretation());
7859     // Add qualifiers if necessary.
7860     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7861     // Promote to void*.
7862     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7863     return destType;
7864   }
7865   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7866     QualType destPointee
7867       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7868     QualType destType = S.Context.getPointerType(
7869         destPointee, LHSTy->castAs<PointerType>()->getPointerInterpretation());
7870     // Add qualifiers if necessary.
7871     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7872     // Promote to void*.
7873     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7874     return destType;
7875   }
7876 
7877   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7878 }
7879 
7880 /// Return false if the first expression is not an integer and the second
7881 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)7882 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7883                                         Expr* PointerExpr, SourceLocation Loc,
7884                                         bool IsIntFirstExpr) {
7885   if (!PointerExpr->getType()->isPointerType() ||
7886       !Int.get()->getType()->isIntegerType())
7887     return false;
7888 
7889   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7890   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7891 
7892   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7893     << Expr1->getType() << Expr2->getType()
7894     << Expr1->getSourceRange() << Expr2->getSourceRange();
7895   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7896                             CK_IntegralToPointer);
7897   return true;
7898 }
7899 
7900 /// Simple conversion between integer and floating point types.
7901 ///
7902 /// Used when handling the OpenCL conditional operator where the
7903 /// condition is a vector while the other operands are scalar.
7904 ///
7905 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7906 /// types are either integer or floating type. Between the two
7907 /// operands, the type with the higher rank is defined as the "result
7908 /// type". The other operand needs to be promoted to the same type. No
7909 /// other type promotion is allowed. We cannot use
7910 /// UsualArithmeticConversions() for this purpose, since it always
7911 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)7912 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7913                                             ExprResult &RHS,
7914                                             SourceLocation QuestionLoc) {
7915   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7916   if (LHS.isInvalid())
7917     return QualType();
7918   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7919   if (RHS.isInvalid())
7920     return QualType();
7921 
7922   // For conversion purposes, we ignore any qualifiers.
7923   // For example, "const float" and "float" are equivalent.
7924   QualType LHSType =
7925     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7926   QualType RHSType =
7927     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7928 
7929   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7930     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7931       << LHSType << LHS.get()->getSourceRange();
7932     return QualType();
7933   }
7934 
7935   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7936     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7937       << RHSType << RHS.get()->getSourceRange();
7938     return QualType();
7939   }
7940 
7941   // If both types are identical, no conversion is needed.
7942   if (LHSType == RHSType)
7943     return LHSType;
7944 
7945   // Now handle "real" floating types (i.e. float, double, long double).
7946   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7947     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7948                                  /*IsCompAssign = */ false);
7949 
7950   // Finally, we have two differing integer types.
7951   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7952   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7953 }
7954 
7955 /// Convert scalar operands to a vector that matches the
7956 ///        condition in length.
7957 ///
7958 /// Used when handling the OpenCL conditional operator where the
7959 /// condition is a vector while the other operands are scalar.
7960 ///
7961 /// We first compute the "result type" for the scalar operands
7962 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7963 /// into a vector of that type where the length matches the condition
7964 /// vector type. s6.11.6 requires that the element types of the result
7965 /// and the condition must have the same number of bits.
7966 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)7967 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7968                               QualType CondTy, SourceLocation QuestionLoc) {
7969   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7970   if (ResTy.isNull()) return QualType();
7971 
7972   const VectorType *CV = CondTy->getAs<VectorType>();
7973   assert(CV);
7974 
7975   // Determine the vector result type
7976   unsigned NumElements = CV->getNumElements();
7977   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7978 
7979   // Ensure that all types have the same number of bits
7980   if (S.Context.getTypeSize(CV->getElementType())
7981       != S.Context.getTypeSize(ResTy)) {
7982     // Since VectorTy is created internally, it does not pretty print
7983     // with an OpenCL name. Instead, we just print a description.
7984     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7985     SmallString<64> Str;
7986     llvm::raw_svector_ostream OS(Str);
7987     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7988     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7989       << CondTy << OS.str();
7990     return QualType();
7991   }
7992 
7993   // Convert operands to the vector result type
7994   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7995   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7996 
7997   return VectorTy;
7998 }
7999 
8000 /// Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)8001 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8002                                        SourceLocation QuestionLoc) {
8003   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8004   // integral type.
8005   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8006   assert(CondTy);
8007   QualType EleTy = CondTy->getElementType();
8008   if (EleTy->isIntegerType()) return false;
8009 
8010   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8011     << Cond->getType() << Cond->getSourceRange();
8012   return true;
8013 }
8014 
8015 /// Return false if the vector condition type and the vector
8016 ///        result type are compatible.
8017 ///
8018 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8019 /// number of elements, and their element types have the same number
8020 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)8021 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8022                               SourceLocation QuestionLoc) {
8023   const VectorType *CV = CondTy->getAs<VectorType>();
8024   const VectorType *RV = VecResTy->getAs<VectorType>();
8025   assert(CV && RV);
8026 
8027   if (CV->getNumElements() != RV->getNumElements()) {
8028     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8029       << CondTy << VecResTy;
8030     return true;
8031   }
8032 
8033   QualType CVE = CV->getElementType();
8034   QualType RVE = RV->getElementType();
8035 
8036   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8037     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8038       << CondTy << VecResTy;
8039     return true;
8040   }
8041 
8042   return false;
8043 }
8044 
8045 /// Return the resulting type for the conditional operator in
8046 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8047 ///        s6.3.i) when the condition is a vector type.
8048 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8049 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8050                              ExprResult &LHS, ExprResult &RHS,
8051                              SourceLocation QuestionLoc) {
8052   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8053   if (Cond.isInvalid())
8054     return QualType();
8055   QualType CondTy = Cond.get()->getType();
8056 
8057   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8058     return QualType();
8059 
8060   // If either operand is a vector then find the vector type of the
8061   // result as specified in OpenCL v1.1 s6.3.i.
8062   if (LHS.get()->getType()->isVectorType() ||
8063       RHS.get()->getType()->isVectorType()) {
8064     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8065                                               /*isCompAssign*/false,
8066                                               /*AllowBothBool*/true,
8067                                               /*AllowBoolConversions*/false);
8068     if (VecResTy.isNull()) return QualType();
8069     // The result type must match the condition type as specified in
8070     // OpenCL v1.1 s6.11.6.
8071     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8072       return QualType();
8073     return VecResTy;
8074   }
8075 
8076   // Both operands are scalar.
8077   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8078 }
8079 
8080 /// Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)8081 static bool checkBlockType(Sema &S, const Expr *E) {
8082   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8083     QualType Ty = CE->getCallee()->getType();
8084     if (Ty->isBlockPointerType()) {
8085       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8086       return true;
8087     }
8088   }
8089   return false;
8090 }
8091 
8092 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8093 /// In that case, LHS = cond.
8094 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)8095 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8096                                         ExprResult &RHS, ExprValueKind &VK,
8097                                         ExprObjectKind &OK,
8098                                         SourceLocation QuestionLoc) {
8099 
8100   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8101   if (!LHSResult.isUsable()) return QualType();
8102   LHS = LHSResult;
8103 
8104   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8105   if (!RHSResult.isUsable()) return QualType();
8106   RHS = RHSResult;
8107 
8108   // C++ is sufficiently different to merit its own checker.
8109   if (getLangOpts().CPlusPlus)
8110     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8111 
8112   VK = VK_RValue;
8113   OK = OK_Ordinary;
8114 
8115   // The OpenCL operator with a vector condition is sufficiently
8116   // different to merit its own checker.
8117   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8118       Cond.get()->getType()->isExtVectorType())
8119     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8120 
8121   // First, check the condition.
8122   Cond = UsualUnaryConversions(Cond.get());
8123   if (Cond.isInvalid())
8124     return QualType();
8125   if (checkCondition(*this, Cond.get(), QuestionLoc))
8126     return QualType();
8127 
8128   // Now check the two expressions.
8129   if (LHS.get()->getType()->isVectorType() ||
8130       RHS.get()->getType()->isVectorType())
8131     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8132                                /*AllowBothBool*/true,
8133                                /*AllowBoolConversions*/false);
8134 
8135   QualType ResTy =
8136       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8137   if (LHS.isInvalid() || RHS.isInvalid())
8138     return QualType();
8139 
8140   QualType LHSTy = LHS.get()->getType();
8141   QualType RHSTy = RHS.get()->getType();
8142 
8143   // Diagnose attempts to convert between __float128 and long double where
8144   // such conversions currently can't be handled.
8145   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8146     Diag(QuestionLoc,
8147          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8148       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8149     return QualType();
8150   }
8151 
8152   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8153   // selection operator (?:).
8154   if (getLangOpts().OpenCL &&
8155       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8156     return QualType();
8157   }
8158 
8159   // If both operands have arithmetic type, do the usual arithmetic conversions
8160   // to find a common type: C99 6.5.15p3,5.
8161   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8162     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8163     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8164 
8165     return ResTy;
8166   }
8167 
8168   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8169   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8170     return LHSTy;
8171   }
8172 
8173   // If both operands are the same structure or union type, the result is that
8174   // type.
8175   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8176     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8177       if (LHSRT->getDecl() == RHSRT->getDecl())
8178         // "If both the operands have structure or union type, the result has
8179         // that type."  This implies that CV qualifiers are dropped.
8180         return LHSTy.getUnqualifiedType();
8181     // FIXME: Type of conditional expression must be complete in C mode.
8182   }
8183 
8184   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8185   // The following || allows only one side to be void (a GCC-ism).
8186   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8187     return checkConditionalVoidType(*this, LHS, RHS);
8188   }
8189 
8190   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8191   // the type of the other operand."
8192   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8193   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8194 
8195   // All objective-c pointer type analysis is done here.
8196   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8197                                                         QuestionLoc);
8198   if (LHS.isInvalid() || RHS.isInvalid())
8199     return QualType();
8200   if (!compositeType.isNull())
8201     return compositeType;
8202 
8203 
8204   // Handle block pointer types.
8205   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8206     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8207                                                      QuestionLoc);
8208 
8209   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8210   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8211     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8212                                                        QuestionLoc);
8213 
8214   // GCC compatibility: soften pointer/integer mismatch.  Note that
8215   // null pointers have been filtered out by this point.
8216   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8217       /*IsIntFirstExpr=*/true))
8218     return RHSTy;
8219   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8220       /*IsIntFirstExpr=*/false))
8221     return LHSTy;
8222 
8223   // Allow ?: operations in which both operands have the same
8224   // built-in sizeless type.
8225   if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8226     return LHSTy;
8227 
8228   // Emit a better diagnostic if one of the expressions is a null pointer
8229   // constant and the other is not a pointer type. In this case, the user most
8230   // likely forgot to take the address of the other expression.
8231   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8232     return QualType();
8233 
8234   // Otherwise, the operands are not compatible.
8235   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8236     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8237     << RHS.get()->getSourceRange();
8238   return QualType();
8239 }
8240 
8241 /// FindCompositeObjCPointerType - Helper method to find composite type of
8242 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8243 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8244                                             SourceLocation QuestionLoc) {
8245   QualType LHSTy = LHS.get()->getType();
8246   QualType RHSTy = RHS.get()->getType();
8247 
8248   // Handle things like Class and struct objc_class*.  Here we case the result
8249   // to the pseudo-builtin, because that will be implicitly cast back to the
8250   // redefinition type if an attempt is made to access its fields.
8251   if (LHSTy->isObjCClassType() &&
8252       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8253     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8254     return LHSTy;
8255   }
8256   if (RHSTy->isObjCClassType() &&
8257       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8258     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8259     return RHSTy;
8260   }
8261   // And the same for struct objc_object* / id
8262   if (LHSTy->isObjCIdType() &&
8263       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8264     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8265     return LHSTy;
8266   }
8267   if (RHSTy->isObjCIdType() &&
8268       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8269     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8270     return RHSTy;
8271   }
8272   // And the same for struct objc_selector* / SEL
8273   if (Context.isObjCSelType(LHSTy) &&
8274       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8275     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8276     return LHSTy;
8277   }
8278   if (Context.isObjCSelType(RHSTy) &&
8279       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8280     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8281     return RHSTy;
8282   }
8283   // Check constraints for Objective-C object pointers types.
8284   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8285 
8286     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8287       // Two identical object pointer types are always compatible.
8288       return LHSTy;
8289     }
8290     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8291     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8292     QualType compositeType = LHSTy;
8293 
8294     // If both operands are interfaces and either operand can be
8295     // assigned to the other, use that type as the composite
8296     // type. This allows
8297     //   xxx ? (A*) a : (B*) b
8298     // where B is a subclass of A.
8299     //
8300     // Additionally, as for assignment, if either type is 'id'
8301     // allow silent coercion. Finally, if the types are
8302     // incompatible then make sure to use 'id' as the composite
8303     // type so the result is acceptable for sending messages to.
8304 
8305     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8306     // It could return the composite type.
8307     if (!(compositeType =
8308           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8309       // Nothing more to do.
8310     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8311       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8312     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8313       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8314     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8315                 RHSOPT->isObjCQualifiedIdType()) &&
8316                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8317                                                          true)) {
8318       // Need to handle "id<xx>" explicitly.
8319       // GCC allows qualified id and any Objective-C type to devolve to
8320       // id. Currently localizing to here until clear this should be
8321       // part of ObjCQualifiedIdTypesAreCompatible.
8322       compositeType = Context.getObjCIdType();
8323     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8324       compositeType = Context.getObjCIdType();
8325     } else {
8326       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8327       << LHSTy << RHSTy
8328       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8329       QualType incompatTy = Context.getObjCIdType();
8330       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8331       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8332       return incompatTy;
8333     }
8334     // The object pointer types are compatible.
8335     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8336     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8337     return compositeType;
8338   }
8339   // Check Objective-C object pointer types and 'void *'
8340   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8341     if (getLangOpts().ObjCAutoRefCount) {
8342       // ARC forbids the implicit conversion of object pointers to 'void *',
8343       // so these types are not compatible.
8344       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8345           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8346       LHS = RHS = true;
8347       return QualType();
8348     }
8349     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8350     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8351     QualType destPointee
8352     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8353     QualType destType = Context.getPointerType(destPointee);
8354     // Add qualifiers if necessary.
8355     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8356     // Promote to void*.
8357     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8358     return destType;
8359   }
8360   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8361     if (getLangOpts().ObjCAutoRefCount) {
8362       // ARC forbids the implicit conversion of object pointers to 'void *',
8363       // so these types are not compatible.
8364       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8365           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8366       LHS = RHS = true;
8367       return QualType();
8368     }
8369     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8370     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8371     QualType destPointee
8372     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8373     QualType destType = Context.getPointerType(destPointee);
8374     // Add qualifiers if necessary.
8375     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8376     // Promote to void*.
8377     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8378     return destType;
8379   }
8380   return QualType();
8381 }
8382 
8383 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8384 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)8385 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8386                                const PartialDiagnostic &Note,
8387                                SourceRange ParenRange) {
8388   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8389   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8390       EndLoc.isValid()) {
8391     Self.Diag(Loc, Note)
8392       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8393       << FixItHint::CreateInsertion(EndLoc, ")");
8394   } else {
8395     // We can't display the parentheses, so just show the bare note.
8396     Self.Diag(Loc, Note) << ParenRange;
8397   }
8398 }
8399 
IsArithmeticOp(BinaryOperatorKind Opc)8400 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8401   return BinaryOperator::isAdditiveOp(Opc) ||
8402          BinaryOperator::isMultiplicativeOp(Opc) ||
8403          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8404   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8405   // not any of the logical operators.  Bitwise-xor is commonly used as a
8406   // logical-xor because there is no logical-xor operator.  The logical
8407   // operators, including uses of xor, have a high false positive rate for
8408   // precedence warnings.
8409 }
8410 
8411 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8412 /// expression, either using a built-in or overloaded operator,
8413 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8414 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)8415 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8416                                    Expr **RHSExprs) {
8417   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8418   E = E->IgnoreImpCasts();
8419   E = E->IgnoreConversionOperator();
8420   E = E->IgnoreImpCasts();
8421   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8422     E = MTE->getSubExpr();
8423     E = E->IgnoreImpCasts();
8424   }
8425 
8426   // Built-in binary operator.
8427   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8428     if (IsArithmeticOp(OP->getOpcode())) {
8429       *Opcode = OP->getOpcode();
8430       *RHSExprs = OP->getRHS();
8431       return true;
8432     }
8433   }
8434 
8435   // Overloaded operator.
8436   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8437     if (Call->getNumArgs() != 2)
8438       return false;
8439 
8440     // Make sure this is really a binary operator that is safe to pass into
8441     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8442     OverloadedOperatorKind OO = Call->getOperator();
8443     if (OO < OO_Plus || OO > OO_Arrow ||
8444         OO == OO_PlusPlus || OO == OO_MinusMinus)
8445       return false;
8446 
8447     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8448     if (IsArithmeticOp(OpKind)) {
8449       *Opcode = OpKind;
8450       *RHSExprs = Call->getArg(1);
8451       return true;
8452     }
8453   }
8454 
8455   return false;
8456 }
8457 
8458 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8459 /// or is a logical expression such as (x==y) which has int type, but is
8460 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)8461 static bool ExprLooksBoolean(Expr *E) {
8462   E = E->IgnoreParenImpCasts();
8463 
8464   if (E->getType()->isBooleanType())
8465     return true;
8466   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8467     return OP->isComparisonOp() || OP->isLogicalOp();
8468   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8469     return OP->getOpcode() == UO_LNot;
8470   if (E->getType()->isPointerType())
8471     return true;
8472   // FIXME: What about overloaded operator calls returning "unspecified boolean
8473   // type"s (commonly pointer-to-members)?
8474 
8475   return false;
8476 }
8477 
8478 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8479 /// and binary operator are mixed in a way that suggests the programmer assumed
8480 /// the conditional operator has higher precedence, for example:
8481 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)8482 static void DiagnoseConditionalPrecedence(Sema &Self,
8483                                           SourceLocation OpLoc,
8484                                           Expr *Condition,
8485                                           Expr *LHSExpr,
8486                                           Expr *RHSExpr) {
8487   BinaryOperatorKind CondOpcode;
8488   Expr *CondRHS;
8489 
8490   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8491     return;
8492   if (!ExprLooksBoolean(CondRHS))
8493     return;
8494 
8495   // The condition is an arithmetic binary expression, with a right-
8496   // hand side that looks boolean, so warn.
8497 
8498   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8499                         ? diag::warn_precedence_bitwise_conditional
8500                         : diag::warn_precedence_conditional;
8501 
8502   Self.Diag(OpLoc, DiagID)
8503       << Condition->getSourceRange()
8504       << BinaryOperator::getOpcodeStr(CondOpcode);
8505 
8506   SuggestParentheses(
8507       Self, OpLoc,
8508       Self.PDiag(diag::note_precedence_silence)
8509           << BinaryOperator::getOpcodeStr(CondOpcode),
8510       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8511 
8512   SuggestParentheses(Self, OpLoc,
8513                      Self.PDiag(diag::note_precedence_conditional_first),
8514                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8515 }
8516 
8517 /// Compute the nullability of a conditional expression.
computeConditionalNullability(QualType ResTy,bool IsBin,QualType LHSTy,QualType RHSTy,ASTContext & Ctx)8518 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8519                                               QualType LHSTy, QualType RHSTy,
8520                                               ASTContext &Ctx) {
8521   if (!ResTy->isAnyPointerType())
8522     return ResTy;
8523 
8524   auto GetNullability = [&Ctx](QualType Ty) {
8525     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8526     if (Kind)
8527       return *Kind;
8528     return NullabilityKind::Unspecified;
8529   };
8530 
8531   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8532   NullabilityKind MergedKind;
8533 
8534   // Compute nullability of a binary conditional expression.
8535   if (IsBin) {
8536     if (LHSKind == NullabilityKind::NonNull)
8537       MergedKind = NullabilityKind::NonNull;
8538     else
8539       MergedKind = RHSKind;
8540   // Compute nullability of a normal conditional expression.
8541   } else {
8542     if (LHSKind == NullabilityKind::Nullable ||
8543         RHSKind == NullabilityKind::Nullable)
8544       MergedKind = NullabilityKind::Nullable;
8545     else if (LHSKind == NullabilityKind::NonNull)
8546       MergedKind = RHSKind;
8547     else if (RHSKind == NullabilityKind::NonNull)
8548       MergedKind = LHSKind;
8549     else
8550       MergedKind = NullabilityKind::Unspecified;
8551   }
8552 
8553   // Return if ResTy already has the correct nullability.
8554   if (GetNullability(ResTy) == MergedKind)
8555     return ResTy;
8556 
8557   // Strip all nullability from ResTy.
8558   while (ResTy->getNullability(Ctx))
8559     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8560 
8561   // Create a new AttributedType with the new nullability kind.
8562   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8563   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8564 }
8565 
8566 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
8567 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)8568 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8569                                     SourceLocation ColonLoc,
8570                                     Expr *CondExpr, Expr *LHSExpr,
8571                                     Expr *RHSExpr) {
8572   if (!getLangOpts().CPlusPlus) {
8573     // C cannot handle TypoExpr nodes in the condition because it
8574     // doesn't handle dependent types properly, so make sure any TypoExprs have
8575     // been dealt with before checking the operands.
8576     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8577     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8578     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8579 
8580     if (!CondResult.isUsable())
8581       return ExprError();
8582 
8583     if (LHSExpr) {
8584       if (!LHSResult.isUsable())
8585         return ExprError();
8586     }
8587 
8588     if (!RHSResult.isUsable())
8589       return ExprError();
8590 
8591     CondExpr = CondResult.get();
8592     LHSExpr = LHSResult.get();
8593     RHSExpr = RHSResult.get();
8594   }
8595 
8596   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8597   // was the condition.
8598   OpaqueValueExpr *opaqueValue = nullptr;
8599   Expr *commonExpr = nullptr;
8600   if (!LHSExpr) {
8601     commonExpr = CondExpr;
8602     // Lower out placeholder types first.  This is important so that we don't
8603     // try to capture a placeholder. This happens in few cases in C++; such
8604     // as Objective-C++'s dictionary subscripting syntax.
8605     if (commonExpr->hasPlaceholderType()) {
8606       ExprResult result = CheckPlaceholderExpr(commonExpr);
8607       if (!result.isUsable()) return ExprError();
8608       commonExpr = result.get();
8609     }
8610     // We usually want to apply unary conversions *before* saving, except
8611     // in the special case of a C++ l-value conditional.
8612     if (!(getLangOpts().CPlusPlus
8613           && !commonExpr->isTypeDependent()
8614           && commonExpr->getValueKind() == RHSExpr->getValueKind()
8615           && commonExpr->isGLValue()
8616           && commonExpr->isOrdinaryOrBitFieldObject()
8617           && RHSExpr->isOrdinaryOrBitFieldObject()
8618           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8619       ExprResult commonRes = UsualUnaryConversions(commonExpr);
8620       if (commonRes.isInvalid())
8621         return ExprError();
8622       commonExpr = commonRes.get();
8623     }
8624 
8625     // If the common expression is a class or array prvalue, materialize it
8626     // so that we can safely refer to it multiple times.
8627     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8628                                    commonExpr->getType()->isArrayType())) {
8629       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8630       if (MatExpr.isInvalid())
8631         return ExprError();
8632       commonExpr = MatExpr.get();
8633     }
8634 
8635     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8636                                                 commonExpr->getType(),
8637                                                 commonExpr->getValueKind(),
8638                                                 commonExpr->getObjectKind(),
8639                                                 commonExpr);
8640     LHSExpr = CondExpr = opaqueValue;
8641   }
8642 
8643   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8644   ExprValueKind VK = VK_RValue;
8645   ExprObjectKind OK = OK_Ordinary;
8646   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8647   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8648                                              VK, OK, QuestionLoc);
8649   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8650       RHS.isInvalid())
8651     return ExprError();
8652 
8653   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8654                                 RHS.get());
8655 
8656   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8657 
8658   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8659                                          Context);
8660 
8661   if (!commonExpr)
8662     return new (Context)
8663         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8664                             RHS.get(), result, VK, OK);
8665 
8666   return new (Context) BinaryConditionalOperator(
8667       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8668       ColonLoc, result, VK, OK);
8669 }
8670 
8671 // Check if we have a conversion between incompatible cmse function pointer
8672 // types, that is, a conversion between a function pointer with the
8673 // cmse_nonsecure_call attribute and one without.
IsInvalidCmseNSCallConversion(Sema & S,QualType FromType,QualType ToType)8674 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8675                                           QualType ToType) {
8676   if (const auto *ToFn =
8677           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8678     if (const auto *FromFn =
8679             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8680       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8681       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8682 
8683       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8684     }
8685   }
8686   return false;
8687 }
8688 
8689 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8690 // being closely modeled after the C99 spec:-). The odd characteristic of this
8691 // routine is it effectively iqnores the qualifiers on the top level pointee.
8692 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8693 // FIXME: add a couple examples in this comment.
8694 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8695 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8696   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8697   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8698 
8699   // get the "pointed to" type (ignoring qualifiers at the top level)
8700   const Type *lhptee, *rhptee;
8701   Qualifiers lhq, rhq;
8702   std::tie(lhptee, lhq) =
8703       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8704   std::tie(rhptee, rhq) =
8705       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8706 
8707   Sema::AssignConvertType ConvTy = Sema::Compatible;
8708 
8709   // C99 6.5.16.1p1: This following citation is common to constraints
8710   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8711   // qualifiers of the type *pointed to* by the right;
8712 
8713   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8714   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8715       lhq.compatiblyIncludesObjCLifetime(rhq)) {
8716     // Ignore lifetime for further calculation.
8717     lhq.removeObjCLifetime();
8718     rhq.removeObjCLifetime();
8719   }
8720 
8721   if (!lhq.compatiblyIncludes(rhq)) {
8722     // Treat address-space mismatches as fatal.
8723     if (!lhq.isAddressSpaceSupersetOf(rhq))
8724       return Sema::IncompatiblePointerDiscardsQualifiers;
8725 
8726     // It's okay to add or remove GC or lifetime qualifiers when converting to
8727     // and from void*.
8728     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8729                         .compatiblyIncludes(
8730                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8731              && (lhptee->isVoidType() || rhptee->isVoidType()))
8732       ; // keep old
8733 
8734     // Treat lifetime mismatches as fatal.
8735     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8736       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8737 
8738     // For GCC/MS compatibility, other qualifier mismatches are treated
8739     // as still compatible in C.
8740     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8741   }
8742 
8743   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8744   // incomplete type and the other is a pointer to a qualified or unqualified
8745   // version of void...
8746   if (lhptee->isVoidType()) {
8747     if (rhptee->isIncompleteOrObjectType())
8748       return ConvTy;
8749 
8750     // As an extension, we allow cast to/from void* to function pointer.
8751     assert(rhptee->isFunctionType());
8752     return Sema::FunctionVoidPointer;
8753   }
8754 
8755   if (rhptee->isVoidType()) {
8756     if (lhptee->isIncompleteOrObjectType())
8757       return ConvTy;
8758 
8759     // As an extension, we allow cast to/from void* to function pointer.
8760     assert(lhptee->isFunctionType());
8761     return Sema::FunctionVoidPointer;
8762   }
8763 
8764   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8765   // unqualified versions of compatible types, ...
8766   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8767   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8768     // Check if the pointee types are compatible ignoring the sign.
8769     // We explicitly check for char so that we catch "char" vs
8770     // "unsigned char" on systems where "char" is unsigned.
8771     if (lhptee->isCharType())
8772       ltrans = S.Context.UnsignedCharTy;
8773     else if (lhptee->hasSignedIntegerRepresentation())
8774       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8775 
8776     if (rhptee->isCharType())
8777       rtrans = S.Context.UnsignedCharTy;
8778     else if (rhptee->hasSignedIntegerRepresentation())
8779       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8780 
8781     if (ltrans == rtrans) {
8782       // Types are compatible ignoring the sign. Qualifier incompatibility
8783       // takes priority over sign incompatibility because the sign
8784       // warning can be disabled.
8785       if (ConvTy != Sema::Compatible)
8786         return ConvTy;
8787 
8788       return Sema::IncompatiblePointerSign;
8789     }
8790 
8791     // If we are a multi-level pointer, it's possible that our issue is simply
8792     // one of qualification - e.g. char ** -> const char ** is not allowed. If
8793     // the eventual target type is the same and the pointers have the same
8794     // level of indirection, this must be the issue.
8795     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8796       do {
8797         std::tie(lhptee, lhq) =
8798           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8799         std::tie(rhptee, rhq) =
8800           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8801 
8802         // Inconsistent address spaces at this point is invalid, even if the
8803         // address spaces would be compatible.
8804         // FIXME: This doesn't catch address space mismatches for pointers of
8805         // different nesting levels, like:
8806         //   __local int *** a;
8807         //   int ** b = a;
8808         // It's not clear how to actually determine when such pointers are
8809         // invalidly incompatible.
8810         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8811           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8812 
8813       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8814 
8815       if (lhptee == rhptee)
8816         return Sema::IncompatibleNestedPointerQualifiers;
8817     }
8818 
8819     // General pointer incompatibility takes priority over qualifiers.
8820     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8821       return Sema::IncompatibleFunctionPointer;
8822     return Sema::IncompatiblePointer;
8823   }
8824   if (!S.getLangOpts().CPlusPlus &&
8825       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8826     return Sema::IncompatibleFunctionPointer;
8827   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8828     return Sema::IncompatibleFunctionPointer;
8829   return ConvTy;
8830 }
8831 
8832 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8833 /// block pointer types are compatible or whether a block and normal pointer
8834 /// are compatible. It is more restrict than comparing two function pointer
8835 // types.
8836 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8837 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8838                                     QualType RHSType) {
8839   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8840   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8841 
8842   QualType lhptee, rhptee;
8843 
8844   // get the "pointed to" type (ignoring qualifiers at the top level)
8845   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8846   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8847 
8848   // In C++, the types have to match exactly.
8849   if (S.getLangOpts().CPlusPlus)
8850     return Sema::IncompatibleBlockPointer;
8851 
8852   Sema::AssignConvertType ConvTy = Sema::Compatible;
8853 
8854   // For blocks we enforce that qualifiers are identical.
8855   Qualifiers LQuals = lhptee.getLocalQualifiers();
8856   Qualifiers RQuals = rhptee.getLocalQualifiers();
8857   if (S.getLangOpts().OpenCL) {
8858     LQuals.removeAddressSpace();
8859     RQuals.removeAddressSpace();
8860   }
8861   if (LQuals != RQuals)
8862     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8863 
8864   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8865   // assignment.
8866   // The current behavior is similar to C++ lambdas. A block might be
8867   // assigned to a variable iff its return type and parameters are compatible
8868   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8869   // an assignment. Presumably it should behave in way that a function pointer
8870   // assignment does in C, so for each parameter and return type:
8871   //  * CVR and address space of LHS should be a superset of CVR and address
8872   //  space of RHS.
8873   //  * unqualified types should be compatible.
8874   if (S.getLangOpts().OpenCL) {
8875     if (!S.Context.typesAreBlockPointerCompatible(
8876             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8877             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8878       return Sema::IncompatibleBlockPointer;
8879   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8880     return Sema::IncompatibleBlockPointer;
8881 
8882   return ConvTy;
8883 }
8884 
8885 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8886 /// for assignment compatibility.
8887 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8888 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8889                                    QualType RHSType) {
8890   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8891   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8892 
8893   if (LHSType->isObjCBuiltinType()) {
8894     // Class is not compatible with ObjC object pointers.
8895     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8896         !RHSType->isObjCQualifiedClassType())
8897       return Sema::IncompatiblePointer;
8898     return Sema::Compatible;
8899   }
8900   if (RHSType->isObjCBuiltinType()) {
8901     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8902         !LHSType->isObjCQualifiedClassType())
8903       return Sema::IncompatiblePointer;
8904     return Sema::Compatible;
8905   }
8906   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8907   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8908 
8909   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8910       // make an exception for id<P>
8911       !LHSType->isObjCQualifiedIdType())
8912     return Sema::CompatiblePointerDiscardsQualifiers;
8913 
8914   if (S.Context.typesAreCompatible(LHSType, RHSType))
8915     return Sema::Compatible;
8916   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8917     return Sema::IncompatibleObjCQualifiedId;
8918   return Sema::IncompatiblePointer;
8919 }
8920 
8921 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)8922 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8923                                  QualType LHSType, QualType RHSType) {
8924   // Fake up an opaque expression.  We don't actually care about what
8925   // cast operations are required, so if CheckAssignmentConstraints
8926   // adds casts to this they'll be wasted, but fortunately that doesn't
8927   // usually happen on valid code.
8928   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8929   ExprResult RHSPtr = &RHSExpr;
8930   CastKind K;
8931 
8932   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8933 }
8934 
8935 /// This helper function returns true if QT is a vector type that has element
8936 /// type ElementType.
isVector(QualType QT,QualType ElementType)8937 static bool isVector(QualType QT, QualType ElementType) {
8938   if (const VectorType *VT = QT->getAs<VectorType>())
8939     return VT->getElementType().getCanonicalType() == ElementType;
8940   return false;
8941 }
8942 
8943 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8944 /// has code to accommodate several GCC extensions when type checking
8945 /// pointers. Here are some objectionable examples that GCC considers warnings:
8946 ///
8947 ///  int a, *pint;
8948 ///  short *pshort;
8949 ///  struct foo *pfoo;
8950 ///
8951 ///  pint = pshort; // warning: assignment from incompatible pointer type
8952 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8953 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8954 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8955 ///
8956 /// As a result, the code for dealing with pointers is more complex than the
8957 /// C99 spec dictates.
8958 ///
8959 /// Sets 'Kind' for any result kind except Incompatible.
8960 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)8961 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8962                                  CastKind &Kind, bool ConvertRHS) {
8963   QualType RHSType = RHS.get()->getType();
8964   QualType OrigLHSType = LHSType;
8965   QualType OrigRHSType = RHSType;
8966 
8967   // Get canonical types.  We're not formatting these types, just comparing
8968   // them.
8969   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8970   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8971 
8972   // Common case: no conversion required.
8973   if (LHSType == RHSType) {
8974     Kind = CK_NoOp;
8975     return Compatible;
8976   }
8977 
8978   // If we have an atomic type, try a non-atomic assignment, then just add an
8979   // atomic qualification step.
8980   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8981     Sema::AssignConvertType result =
8982       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8983     if (result != Compatible)
8984       return result;
8985     if (Kind != CK_NoOp && ConvertRHS)
8986       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8987     Kind = CK_NonAtomicToAtomic;
8988     return Compatible;
8989   }
8990 
8991   // If the left-hand side is a reference type, then we are in a
8992   // (rare!) case where we've allowed the use of references in C,
8993   // e.g., as a parameter type in a built-in function. In this case,
8994   // just make sure that the type referenced is compatible with the
8995   // right-hand side type. The caller is responsible for adjusting
8996   // LHSType so that the resulting expression does not have reference
8997   // type.
8998   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8999     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9000       Kind = CK_LValueBitCast;
9001       return Compatible;
9002     }
9003     return Incompatible;
9004   }
9005 
9006   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9007   // to the same ExtVector type.
9008   if (LHSType->isExtVectorType()) {
9009     if (RHSType->isExtVectorType())
9010       return Incompatible;
9011     if (RHSType->isArithmeticType()) {
9012       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9013       if (ConvertRHS)
9014         RHS = prepareVectorSplat(LHSType, RHS.get());
9015       Kind = CK_VectorSplat;
9016       return Compatible;
9017     }
9018   }
9019 
9020   // Conversions to or from vector type.
9021   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9022     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9023       // Allow assignments of an AltiVec vector type to an equivalent GCC
9024       // vector type and vice versa
9025       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9026         Kind = CK_BitCast;
9027         return Compatible;
9028       }
9029 
9030       // If we are allowing lax vector conversions, and LHS and RHS are both
9031       // vectors, the total size only needs to be the same. This is a bitcast;
9032       // no bits are changed but the result type is different.
9033       if (isLaxVectorConversion(RHSType, LHSType)) {
9034         Kind = CK_BitCast;
9035         return IncompatibleVectors;
9036       }
9037     }
9038 
9039     // When the RHS comes from another lax conversion (e.g. binops between
9040     // scalars and vectors) the result is canonicalized as a vector. When the
9041     // LHS is also a vector, the lax is allowed by the condition above. Handle
9042     // the case where LHS is a scalar.
9043     if (LHSType->isScalarType()) {
9044       const VectorType *VecType = RHSType->getAs<VectorType>();
9045       if (VecType && VecType->getNumElements() == 1 &&
9046           isLaxVectorConversion(RHSType, LHSType)) {
9047         ExprResult *VecExpr = &RHS;
9048         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9049         Kind = CK_BitCast;
9050         return Compatible;
9051       }
9052     }
9053 
9054     return Incompatible;
9055   }
9056 
9057   // Diagnose attempts to convert between __float128 and long double where
9058   // such conversions currently can't be handled.
9059   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9060     return Incompatible;
9061 
9062   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9063   // discards the imaginary part.
9064   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9065       !LHSType->getAs<ComplexType>())
9066     return Incompatible;
9067 
9068   // Arithmetic conversions.
9069   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9070       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9071     if (ConvertRHS)
9072       Kind = PrepareScalarCast(RHS, LHSType);
9073     return Compatible;
9074   }
9075 
9076   // CHERI callbacks may only be cast to other cheri callback types
9077   bool RHSIsCallback = false;
9078   bool LHSIsCallback = false;
9079   if (auto RHSPointer = dyn_cast<PointerType>(RHSType))
9080     if (auto RHSFnPTy = RHSPointer->getPointeeType()->getAs<FunctionType>())
9081       if (RHSFnPTy->getCallConv() == CC_CHERICCallback)
9082         RHSIsCallback = true;
9083   if (auto LHSPointer = dyn_cast<PointerType>(LHSType))
9084     if (auto LHSFnPTy = LHSPointer->getPointeeType()->getAs<FunctionType>())
9085       if (LHSFnPTy->getCallConv() == CC_CHERICCallback)
9086         LHSIsCallback = true;
9087   if (RHSIsCallback != LHSIsCallback)
9088     return Incompatible;
9089 
9090   // Conversions to normal pointers.
9091   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9092     // U* -> T*
9093     if (const PointerType *RHSPointer = dyn_cast<PointerType>(RHSType)) {
9094       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9095       LangAS AddrSpaceR = RHSPointer->getPointeeType().getAddressSpace();
9096       if (AddrSpaceL != AddrSpaceR) {
9097         Kind = CK_AddressSpaceConversion;
9098       } else if (LHSPointer->isCHERICapability() !=
9099                  RHSPointer->isCHERICapability()) {
9100         // all other implicit casts to and from capabilities are not allowed
9101         Kind = RHSPointer->isCHERICapability() ? CK_CHERICapabilityToPointer
9102                                                : CK_PointerToCHERICapability;
9103         return RHSPointer->isCHERICapability() ? CHERICapabilityToPointer
9104                                                : PointerToCHERICapability;
9105       } else {
9106         if (Context.hasCvrSimilarType(RHSType, LHSType))
9107           Kind = CK_NoOp;
9108         else
9109           Kind = CK_BitCast;
9110         if (RHSPointer->isCHERICapability() && isa<PointerType>(OrigRHSType) &&
9111             RHSPointer->getPointeeType()->isVoidType())
9112           if (auto *TT = dyn_cast<TypedefType>(
9113                 cast<PointerType>(OrigRHSType)->getPointeeType())) {
9114             unsigned FromAlign = Context.getTypeAlignInChars(TT).getQuantity();
9115             unsigned ToAlign =
9116               Context.getTypeAlignInChars(LHSType).getQuantity();
9117             if ((FromAlign > 1) && (ToAlign > FromAlign))
9118               Diag(RHS.get()->getExprLoc(), diag::err_cheri_ptr_align) <<
9119                 OrigRHSType << LHSType << FromAlign << ToAlign;
9120           }
9121       }
9122       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9123     }
9124 
9125     // int -> T*
9126     if (RHSType->isIntegerType()) {
9127       bool RHSIsNull =
9128           RHS.get()->isNullPointerConstant(
9129               Context, Expr::NPC_ValueDependentIsNotNull) != Expr::NPCK_NotNull;
9130       Kind = RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer;
9131       return IntToPointer;
9132     }
9133 
9134     // C pointers are not compatible with ObjC object pointers,
9135     // with two exceptions:
9136     if (isa<ObjCObjectPointerType>(RHSType)) {
9137       //  - conversions to void*
9138       if (LHSPointer->getPointeeType()->isVoidType()) {
9139         Kind = CK_BitCast;
9140         return Compatible;
9141       }
9142 
9143       //  - conversions from 'Class' to the redefinition type
9144       if (RHSType->isObjCClassType() &&
9145           Context.hasSameType(LHSType,
9146                               Context.getObjCClassRedefinitionType())) {
9147         Kind = CK_BitCast;
9148         return Compatible;
9149       }
9150 
9151       Kind = CK_BitCast;
9152       return IncompatiblePointer;
9153     }
9154 
9155     // U^ -> void*
9156     if (RHSType->getAs<BlockPointerType>()) {
9157       if (LHSPointer->getPointeeType()->isVoidType()) {
9158         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9159         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9160                                 ->getPointeeType()
9161                                 .getAddressSpace();
9162         Kind =
9163             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9164         return Compatible;
9165       }
9166     }
9167 
9168     return Incompatible;
9169   }
9170 
9171   // Conversions to block pointers.
9172   if (isa<BlockPointerType>(LHSType)) {
9173     // U^ -> T^
9174     if (RHSType->isBlockPointerType()) {
9175       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9176                               ->getPointeeType()
9177                               .getAddressSpace();
9178       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9179                               ->getPointeeType()
9180                               .getAddressSpace();
9181       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9182       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9183     }
9184 
9185     // int or null -> T^
9186     if (RHSType->isIntegerType()) {
9187       Kind = CK_IntegralToPointer; // FIXME: null
9188       return IntToBlockPointer;
9189     }
9190 
9191     // id -> T^
9192     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9193       Kind = CK_AnyPointerToBlockPointerCast;
9194       return Compatible;
9195     }
9196 
9197     // void* -> T^
9198     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9199       if (RHSPT->getPointeeType()->isVoidType()) {
9200         Kind = CK_AnyPointerToBlockPointerCast;
9201         return Compatible;
9202       }
9203 
9204     return Incompatible;
9205   }
9206 
9207   // Conversions to Objective-C pointers.
9208   if (isa<ObjCObjectPointerType>(LHSType)) {
9209     // A* -> B*
9210     if (RHSType->isObjCObjectPointerType()) {
9211       Kind = CK_BitCast;
9212       Sema::AssignConvertType result =
9213         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9214       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9215           result == Compatible &&
9216           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9217         result = IncompatibleObjCWeakRef;
9218       return result;
9219     }
9220 
9221     // int or null -> A*
9222     if (RHSType->isIntegerType()) {
9223       assert(!LHSType->isCapabilityPointerType());
9224       Kind = CK_IntegralToPointer; // FIXME: null
9225       return IntToPointer;
9226     }
9227 
9228     // In general, C pointers are not compatible with ObjC object pointers,
9229     // with two exceptions:
9230     if (isa<PointerType>(RHSType)) {
9231       Kind = CK_CPointerToObjCPointerCast;
9232 
9233       //  - conversions from 'void*'
9234       if (RHSType->isVoidPointerType()) {
9235         return Compatible;
9236       }
9237 
9238       //  - conversions to 'Class' from its redefinition type
9239       if (LHSType->isObjCClassType() &&
9240           Context.hasSameType(RHSType,
9241                               Context.getObjCClassRedefinitionType())) {
9242         return Compatible;
9243       }
9244 
9245       return IncompatiblePointer;
9246     }
9247 
9248     // Only under strict condition T^ is compatible with an Objective-C pointer.
9249     if (RHSType->isBlockPointerType() &&
9250         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9251       if (ConvertRHS)
9252         maybeExtendBlockObject(RHS);
9253       Kind = CK_BlockPointerToObjCPointerCast;
9254       return Compatible;
9255     }
9256 
9257     return Incompatible;
9258   }
9259 
9260   // Conversions from pointers that are not covered by the above.
9261   if (const PointerType *RHSPointer = dyn_cast<PointerType>(RHSType)) {
9262     // T* -> _Bool
9263     if (LHSType == Context.BoolTy) {
9264       Kind = CK_PointerToBoolean;
9265       return Compatible;
9266     }
9267 
9268     // T* -> int
9269     if (LHSType->isIntegerType()) {
9270       Kind = CK_PointerToIntegral;
9271       return PointerToInt;
9272     }
9273 
9274     return Incompatible;
9275   }
9276 
9277   // Conversions from Objective-C pointers that are not covered by the above.
9278   if (isa<ObjCObjectPointerType>(RHSType)) {
9279     // T* -> _Bool
9280     if (LHSType == Context.BoolTy) {
9281       Kind = CK_PointerToBoolean;
9282       return Compatible;
9283     }
9284 
9285     // T* -> int
9286     if (LHSType->isIntegerType()) {
9287       Kind = CK_PointerToIntegral;
9288       return PointerToInt;
9289     }
9290 
9291     return Incompatible;
9292   }
9293 
9294   // struct A -> struct B
9295   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9296     if (Context.typesAreCompatible(LHSType, RHSType)) {
9297       Kind = CK_NoOp;
9298       return Compatible;
9299     }
9300   }
9301 
9302   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9303     Kind = CK_IntToOCLSampler;
9304     return Compatible;
9305   }
9306 
9307   return Incompatible;
9308 }
9309 
9310 /// Constructs a transparent union from an expression that is
9311 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)9312 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9313                                       ExprResult &EResult, QualType UnionType,
9314                                       FieldDecl *Field) {
9315   // Build an initializer list that designates the appropriate member
9316   // of the transparent union.
9317   Expr *E = EResult.get();
9318   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9319                                                    E, SourceLocation());
9320   Initializer->setType(UnionType);
9321   Initializer->setInitializedFieldInUnion(Field);
9322 
9323   // Build a compound literal constructing a value of the transparent
9324   // union type from this initializer list.
9325   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9326   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9327                                         VK_RValue, Initializer, false);
9328 }
9329 
9330 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)9331 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9332                                                ExprResult &RHS) {
9333   QualType RHSType = RHS.get()->getType();
9334 
9335   // If the ArgType is a Union type, we want to handle a potential
9336   // transparent_union GCC extension.
9337   const RecordType *UT = ArgType->getAsUnionType();
9338   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9339     return Incompatible;
9340 
9341   // The field to initialize within the transparent union.
9342   RecordDecl *UD = UT->getDecl();
9343   FieldDecl *InitField = nullptr;
9344   // It's compatible if the expression matches any of the fields.
9345   for (auto *it : UD->fields()) {
9346     if (it->getType()->isPointerType()) {
9347       // If the transparent union contains a pointer type, we allow:
9348       // 1) void pointer
9349       // 2) null pointer constant
9350       if (RHSType->isPointerType())
9351         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9352           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9353           InitField = it;
9354           break;
9355         }
9356 
9357       if (RHS.get()->isNullPointerConstant(Context,
9358                                            Expr::NPC_ValueDependentIsNull)) {
9359         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9360                                 CK_NullToPointer);
9361         InitField = it;
9362         break;
9363       }
9364     }
9365 
9366     CastKind Kind;
9367     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9368           == Compatible) {
9369       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9370       InitField = it;
9371       break;
9372     }
9373   }
9374 
9375   if (!InitField)
9376     return Incompatible;
9377 
9378   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9379   return Compatible;
9380 }
9381 
9382 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)9383 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9384                                        bool Diagnose,
9385                                        bool DiagnoseCFAudited,
9386                                        bool ConvertRHS) {
9387   // We need to be able to tell the caller whether we diagnosed a problem, if
9388   // they ask us to issue diagnostics.
9389   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9390 
9391   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9392   // we can't avoid *all* modifications at the moment, so we need some somewhere
9393   // to put the updated value.
9394   ExprResult LocalRHS = CallerRHS;
9395   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9396 
9397   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9398     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9399       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9400           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9401         Diag(RHS.get()->getExprLoc(),
9402              diag::warn_noderef_to_dereferenceable_pointer)
9403             << RHS.get()->getSourceRange();
9404       }
9405     }
9406   }
9407 
9408   if (getLangOpts().CPlusPlus) {
9409     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9410       // C++ 5.17p3: If the left operand is not of class type, the
9411       // expression is implicitly converted (C++ 4) to the
9412       // cv-unqualified type of the left operand.
9413       QualType RHSType = RHS.get()->getType();
9414       if (Diagnose) {
9415         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9416                                         AA_Assigning);
9417       } else {
9418         ImplicitConversionSequence ICS =
9419             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9420                                   /*SuppressUserConversions=*/false,
9421                                   AllowedExplicit::None,
9422                                   /*InOverloadResolution=*/false,
9423                                   /*CStyle=*/false,
9424                                   /*AllowObjCWritebackConversion=*/false);
9425         if (ICS.isFailure())
9426           return Incompatible;
9427         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9428                                         ICS, AA_Assigning);
9429       }
9430       if (RHS.isInvalid())
9431         return Incompatible;
9432       Sema::AssignConvertType result = Compatible;
9433       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9434           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9435         result = IncompatibleObjCWeakRef;
9436       return result;
9437     }
9438 
9439     // FIXME: Currently, we fall through and treat C++ classes like C
9440     // structures.
9441     // FIXME: We also fall through for atomics; not sure what should
9442     // happen there, though.
9443   } else if (RHS.get()->getType() == Context.OverloadTy) {
9444     // As a set of extensions to C, we support overloading on functions. These
9445     // functions need to be resolved here.
9446     DeclAccessPair DAP;
9447     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9448             RHS.get(), LHSType, /*Complain=*/false, DAP))
9449       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9450     else
9451       return Incompatible;
9452   }
9453 
9454   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9455   // a null pointer constant.
9456   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9457        LHSType->isBlockPointerType()) &&
9458       RHS.get()->isNullPointerConstant(Context,
9459                                        Expr::NPC_ValueDependentIsNull)) {
9460     if (Diagnose || ConvertRHS) {
9461       CastKind Kind;
9462       CXXCastPath Path;
9463       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9464                              /*IgnoreBaseAccess=*/false, Diagnose);
9465       if (ConvertRHS)
9466         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9467     }
9468     return Compatible;
9469   }
9470 
9471   // OpenCL queue_t type assignment.
9472   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9473                                  Context, Expr::NPC_ValueDependentIsNull)) {
9474     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9475     return Compatible;
9476   }
9477 
9478   // This check seems unnatural, however it is necessary to ensure the proper
9479   // conversion of functions/arrays. If the conversion were done for all
9480   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9481   // expressions that suppress this implicit conversion (&, sizeof).
9482   //
9483   // Suppress this for references: C++ 8.5.3p5.
9484   if (!LHSType->isReferenceType()) {
9485     // FIXME: We potentially allocate here even if ConvertRHS is false.
9486     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9487     if (RHS.isInvalid())
9488       return Incompatible;
9489   }
9490   CastKind Kind;
9491   Sema::AssignConvertType result =
9492     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9493 
9494   // C99 6.5.16.1p2: The value of the right operand is converted to the
9495   // type of the assignment expression.
9496   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9497   // so that we can use references in built-in functions even in C.
9498   // The getNonReferenceType() call makes sure that the resulting expression
9499   // does not have reference type.
9500   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9501     QualType Ty = LHSType.getNonLValueExprType(Context);
9502     Expr *E = RHS.get();
9503 
9504     // Check for various Objective-C errors. If we are not reporting
9505     // diagnostics and just checking for errors, e.g., during overload
9506     // resolution, return Incompatible to indicate the failure.
9507     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9508         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9509                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9510       if (!Diagnose)
9511         return Incompatible;
9512     }
9513     if (getLangOpts().ObjC &&
9514         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9515                                            E->getType(), E, Diagnose) ||
9516          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9517       if (!Diagnose)
9518         return Incompatible;
9519       // Replace the expression with a corrected version and continue so we
9520       // can find further errors.
9521       RHS = E;
9522       return Compatible;
9523     }
9524 
9525     if (ConvertRHS)
9526       RHS = ImpCastExprToType(E, Ty, Kind);
9527   }
9528 
9529   return result;
9530 }
9531 
9532 namespace {
9533 /// The original operand to an operator, prior to the application of the usual
9534 /// arithmetic conversions and converting the arguments of a builtin operator
9535 /// candidate.
9536 struct OriginalOperand {
OriginalOperand__anon496515c20a11::OriginalOperand9537   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9538     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9539       Op = MTE->getSubExpr();
9540     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9541       Op = BTE->getSubExpr();
9542     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9543       Orig = ICE->getSubExprAsWritten();
9544       Conversion = ICE->getConversionFunction();
9545     }
9546   }
9547 
getType__anon496515c20a11::OriginalOperand9548   QualType getType() const { return Orig->getType(); }
9549 
9550   Expr *Orig;
9551   NamedDecl *Conversion;
9552 };
9553 }
9554 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9555 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9556                                ExprResult &RHS) {
9557   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9558 
9559   Diag(Loc, diag::err_typecheck_invalid_operands)
9560     << OrigLHS.getType() << OrigRHS.getType()
9561     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9562 
9563   // If a user-defined conversion was applied to either of the operands prior
9564   // to applying the built-in operator rules, tell the user about it.
9565   if (OrigLHS.Conversion) {
9566     Diag(OrigLHS.Conversion->getLocation(),
9567          diag::note_typecheck_invalid_operands_converted)
9568       << 0 << LHS.get()->getType();
9569   }
9570   if (OrigRHS.Conversion) {
9571     Diag(OrigRHS.Conversion->getLocation(),
9572          diag::note_typecheck_invalid_operands_converted)
9573       << 1 << RHS.get()->getType();
9574   }
9575 
9576   return QualType();
9577 }
9578 
9579 // Diagnose cases where a scalar was implicitly converted to a vector and
9580 // diagnose the underlying types. Otherwise, diagnose the error
9581 // as invalid vector logical operands for non-C++ cases.
InvalidLogicalVectorOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9582 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9583                                             ExprResult &RHS) {
9584   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9585   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9586 
9587   bool LHSNatVec = LHSType->isVectorType();
9588   bool RHSNatVec = RHSType->isVectorType();
9589 
9590   if (!(LHSNatVec && RHSNatVec)) {
9591     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9592     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9593     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9594         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9595         << Vector->getSourceRange();
9596     return QualType();
9597   }
9598 
9599   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9600       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9601       << RHS.get()->getSourceRange();
9602 
9603   return QualType();
9604 }
9605 
9606 /// Try to convert a value of non-vector type to a vector type by converting
9607 /// the type to the element type of the vector and then performing a splat.
9608 /// If the language is OpenCL, we only use conversions that promote scalar
9609 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9610 /// for float->int.
9611 ///
9612 /// OpenCL V2.0 6.2.6.p2:
9613 /// An error shall occur if any scalar operand type has greater rank
9614 /// than the type of the vector element.
9615 ///
9616 /// \param scalar - if non-null, actually perform the conversions
9617 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy,unsigned & DiagID)9618 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9619                                      QualType scalarTy,
9620                                      QualType vectorEltTy,
9621                                      QualType vectorTy,
9622                                      unsigned &DiagID) {
9623   // The conversion to apply to the scalar before splatting it,
9624   // if necessary.
9625   CastKind scalarCast = CK_NoOp;
9626 
9627   if (vectorEltTy->isIntegralType(S.Context)) {
9628     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9629         (scalarTy->isIntegerType() &&
9630          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9631       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9632       return true;
9633     }
9634     if (!scalarTy->isIntegralType(S.Context))
9635       return true;
9636     scalarCast = CK_IntegralCast;
9637   } else if (vectorEltTy->isRealFloatingType()) {
9638     if (scalarTy->isRealFloatingType()) {
9639       if (S.getLangOpts().OpenCL &&
9640           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9641         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9642         return true;
9643       }
9644       scalarCast = CK_FloatingCast;
9645     }
9646     else if (scalarTy->isIntegralType(S.Context))
9647       scalarCast = CK_IntegralToFloating;
9648     else
9649       return true;
9650   } else {
9651     return true;
9652   }
9653 
9654   // Adjust scalar if desired.
9655   if (scalar) {
9656     if (scalarCast != CK_NoOp)
9657       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9658     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9659   }
9660   return false;
9661 }
9662 
9663 /// Convert vector E to a vector with the same number of elements but different
9664 /// element type.
convertVector(Expr * E,QualType ElementType,Sema & S)9665 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9666   const auto *VecTy = E->getType()->getAs<VectorType>();
9667   assert(VecTy && "Expression E must be a vector");
9668   QualType NewVecTy = S.Context.getVectorType(ElementType,
9669                                               VecTy->getNumElements(),
9670                                               VecTy->getVectorKind());
9671 
9672   // Look through the implicit cast. Return the subexpression if its type is
9673   // NewVecTy.
9674   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9675     if (ICE->getSubExpr()->getType() == NewVecTy)
9676       return ICE->getSubExpr();
9677 
9678   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9679   return S.ImpCastExprToType(E, NewVecTy, Cast);
9680 }
9681 
9682 /// Test if a (constant) integer Int can be casted to another integer type
9683 /// IntTy without losing precision.
canConvertIntToOtherIntTy(Sema & S,ExprResult * Int,QualType OtherIntTy)9684 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9685                                       QualType OtherIntTy) {
9686   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9687 
9688   // Reject cases where the value of the Int is unknown as that would
9689   // possibly cause truncation, but accept cases where the scalar can be
9690   // demoted without loss of precision.
9691   Expr::EvalResult EVResult;
9692   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9693   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9694   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9695   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9696 
9697   if (CstInt) {
9698     // If the scalar is constant and is of a higher order and has more active
9699     // bits that the vector element type, reject it.
9700     llvm::APSInt Result = EVResult.Val.getInt();
9701     unsigned NumBits = IntSigned
9702                            ? (Result.isNegative() ? Result.getMinSignedBits()
9703                                                   : Result.getActiveBits())
9704                            : Result.getActiveBits();
9705     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9706       return true;
9707 
9708     // If the signedness of the scalar type and the vector element type
9709     // differs and the number of bits is greater than that of the vector
9710     // element reject it.
9711     return (IntSigned != OtherIntSigned &&
9712             NumBits > S.Context.getIntWidth(OtherIntTy));
9713   }
9714 
9715   // Reject cases where the value of the scalar is not constant and it's
9716   // order is greater than that of the vector element type.
9717   return (Order < 0);
9718 }
9719 
9720 /// Test if a (constant) integer Int can be casted to floating point type
9721 /// FloatTy without losing precision.
canConvertIntTyToFloatTy(Sema & S,ExprResult * Int,QualType FloatTy)9722 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9723                                      QualType FloatTy) {
9724   QualType IntTy = Int->get()->getType().getUnqualifiedType();
9725 
9726   // Determine if the integer constant can be expressed as a floating point
9727   // number of the appropriate type.
9728   Expr::EvalResult EVResult;
9729   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9730 
9731   uint64_t Bits = 0;
9732   if (CstInt) {
9733     // Reject constants that would be truncated if they were converted to
9734     // the floating point type. Test by simple to/from conversion.
9735     // FIXME: Ideally the conversion to an APFloat and from an APFloat
9736     //        could be avoided if there was a convertFromAPInt method
9737     //        which could signal back if implicit truncation occurred.
9738     llvm::APSInt Result = EVResult.Val.getInt();
9739     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9740     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9741                            llvm::APFloat::rmTowardZero);
9742     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9743                              !IntTy->hasSignedIntegerRepresentation());
9744     bool Ignored = false;
9745     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9746                            &Ignored);
9747     if (Result != ConvertBack)
9748       return true;
9749   } else {
9750     // Reject types that cannot be fully encoded into the mantissa of
9751     // the float.
9752     Bits = S.Context.getTypeSize(IntTy);
9753     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9754         S.Context.getFloatTypeSemantics(FloatTy));
9755     if (Bits > FloatPrec)
9756       return true;
9757   }
9758 
9759   return false;
9760 }
9761 
9762 /// Attempt to convert and splat Scalar into a vector whose types matches
9763 /// Vector following GCC conversion rules. The rule is that implicit
9764 /// conversion can occur when Scalar can be casted to match Vector's element
9765 /// type without causing truncation of Scalar.
tryGCCVectorConvertAndSplat(Sema & S,ExprResult * Scalar,ExprResult * Vector)9766 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9767                                         ExprResult *Vector) {
9768   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9769   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9770   const VectorType *VT = VectorTy->getAs<VectorType>();
9771 
9772   assert(!isa<ExtVectorType>(VT) &&
9773          "ExtVectorTypes should not be handled here!");
9774 
9775   QualType VectorEltTy = VT->getElementType();
9776 
9777   // Reject cases where the vector element type or the scalar element type are
9778   // not integral or floating point types.
9779   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9780     return true;
9781 
9782   // The conversion to apply to the scalar before splatting it,
9783   // if necessary.
9784   CastKind ScalarCast = CK_NoOp;
9785 
9786   // Accept cases where the vector elements are integers and the scalar is
9787   // an integer.
9788   // FIXME: Notionally if the scalar was a floating point value with a precise
9789   //        integral representation, we could cast it to an appropriate integer
9790   //        type and then perform the rest of the checks here. GCC will perform
9791   //        this conversion in some cases as determined by the input language.
9792   //        We should accept it on a language independent basis.
9793   if (VectorEltTy->isIntegralType(S.Context) &&
9794       ScalarTy->isIntegralType(S.Context) &&
9795       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9796 
9797     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9798       return true;
9799 
9800     ScalarCast = CK_IntegralCast;
9801   } else if (VectorEltTy->isIntegralType(S.Context) &&
9802              ScalarTy->isRealFloatingType()) {
9803     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9804       ScalarCast = CK_FloatingToIntegral;
9805     else
9806       return true;
9807   } else if (VectorEltTy->isRealFloatingType()) {
9808     if (ScalarTy->isRealFloatingType()) {
9809 
9810       // Reject cases where the scalar type is not a constant and has a higher
9811       // Order than the vector element type.
9812       llvm::APFloat Result(0.0);
9813 
9814       // Determine whether this is a constant scalar. In the event that the
9815       // value is dependent (and thus cannot be evaluated by the constant
9816       // evaluator), skip the evaluation. This will then diagnose once the
9817       // expression is instantiated.
9818       bool CstScalar = Scalar->get()->isValueDependent() ||
9819                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
9820       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9821       if (!CstScalar && Order < 0)
9822         return true;
9823 
9824       // If the scalar cannot be safely casted to the vector element type,
9825       // reject it.
9826       if (CstScalar) {
9827         bool Truncated = false;
9828         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9829                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
9830         if (Truncated)
9831           return true;
9832       }
9833 
9834       ScalarCast = CK_FloatingCast;
9835     } else if (ScalarTy->isIntegralType(S.Context)) {
9836       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9837         return true;
9838 
9839       ScalarCast = CK_IntegralToFloating;
9840     } else
9841       return true;
9842   } else if (ScalarTy->isEnumeralType())
9843     return true;
9844 
9845   // Adjust scalar if desired.
9846   if (Scalar) {
9847     if (ScalarCast != CK_NoOp)
9848       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9849     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9850   }
9851   return false;
9852 }
9853 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)9854 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9855                                    SourceLocation Loc, bool IsCompAssign,
9856                                    bool AllowBothBool,
9857                                    bool AllowBoolConversions) {
9858   if (!IsCompAssign) {
9859     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9860     if (LHS.isInvalid())
9861       return QualType();
9862   }
9863   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9864   if (RHS.isInvalid())
9865     return QualType();
9866 
9867   // For conversion purposes, we ignore any qualifiers.
9868   // For example, "const float" and "float" are equivalent.
9869   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9870   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9871 
9872   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9873   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9874   assert(LHSVecType || RHSVecType);
9875 
9876   // AltiVec-style "vector bool op vector bool" combinations are allowed
9877   // for some operators but not others.
9878   if (!AllowBothBool &&
9879       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9880       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9881     return InvalidOperands(Loc, LHS, RHS);
9882 
9883   // If the vector types are identical, return.
9884   if (Context.hasSameType(LHSType, RHSType))
9885     return LHSType;
9886 
9887   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9888   if (LHSVecType && RHSVecType &&
9889       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9890     if (isa<ExtVectorType>(LHSVecType)) {
9891       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9892       return LHSType;
9893     }
9894 
9895     if (!IsCompAssign)
9896       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9897     return RHSType;
9898   }
9899 
9900   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9901   // can be mixed, with the result being the non-bool type.  The non-bool
9902   // operand must have integer element type.
9903   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9904       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9905       (Context.getTypeSize(LHSVecType->getElementType()) ==
9906        Context.getTypeSize(RHSVecType->getElementType()))) {
9907     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9908         LHSVecType->getElementType()->isIntegerType() &&
9909         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9910       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9911       return LHSType;
9912     }
9913     if (!IsCompAssign &&
9914         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9915         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9916         RHSVecType->getElementType()->isIntegerType()) {
9917       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9918       return RHSType;
9919     }
9920   }
9921 
9922   // If there's a vector type and a scalar, try to convert the scalar to
9923   // the vector element type and splat.
9924   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9925   if (!RHSVecType) {
9926     if (isa<ExtVectorType>(LHSVecType)) {
9927       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9928                                     LHSVecType->getElementType(), LHSType,
9929                                     DiagID))
9930         return LHSType;
9931     } else {
9932       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9933         return LHSType;
9934     }
9935   }
9936   if (!LHSVecType) {
9937     if (isa<ExtVectorType>(RHSVecType)) {
9938       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9939                                     LHSType, RHSVecType->getElementType(),
9940                                     RHSType, DiagID))
9941         return RHSType;
9942     } else {
9943       if (LHS.get()->getValueKind() == VK_LValue ||
9944           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9945         return RHSType;
9946     }
9947   }
9948 
9949   // FIXME: The code below also handles conversion between vectors and
9950   // non-scalars, we should break this down into fine grained specific checks
9951   // and emit proper diagnostics.
9952   QualType VecType = LHSVecType ? LHSType : RHSType;
9953   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9954   QualType OtherType = LHSVecType ? RHSType : LHSType;
9955   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9956   if (isLaxVectorConversion(OtherType, VecType)) {
9957     // If we're allowing lax vector conversions, only the total (data) size
9958     // needs to be the same. For non compound assignment, if one of the types is
9959     // scalar, the result is always the vector type.
9960     if (!IsCompAssign) {
9961       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9962       return VecType;
9963     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9964     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9965     // type. Note that this is already done by non-compound assignments in
9966     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9967     // <1 x T> -> T. The result is also a vector type.
9968     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9969                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9970       ExprResult *RHSExpr = &RHS;
9971       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9972       return VecType;
9973     }
9974   }
9975 
9976   // Okay, the expression is invalid.
9977 
9978   // If there's a non-vector, non-real operand, diagnose that.
9979   if ((!RHSVecType && !RHSType->isRealType()) ||
9980       (!LHSVecType && !LHSType->isRealType())) {
9981     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9982       << LHSType << RHSType
9983       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9984     return QualType();
9985   }
9986 
9987   // OpenCL V1.1 6.2.6.p1:
9988   // If the operands are of more than one vector type, then an error shall
9989   // occur. Implicit conversions between vector types are not permitted, per
9990   // section 6.2.1.
9991   if (getLangOpts().OpenCL &&
9992       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9993       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9994     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9995                                                            << RHSType;
9996     return QualType();
9997   }
9998 
9999 
10000   // If there is a vector type that is not a ExtVector and a scalar, we reach
10001   // this point if scalar could not be converted to the vector's element type
10002   // without truncation.
10003   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10004       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10005     QualType Scalar = LHSVecType ? RHSType : LHSType;
10006     QualType Vector = LHSVecType ? LHSType : RHSType;
10007     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10008     Diag(Loc,
10009          diag::err_typecheck_vector_not_convertable_implict_truncation)
10010         << ScalarOrVector << Scalar << Vector;
10011 
10012     return QualType();
10013   }
10014 
10015   // Otherwise, use the generic diagnostic.
10016   Diag(Loc, DiagID)
10017     << LHSType << RHSType
10018     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10019   return QualType();
10020 }
10021 
10022 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10023 // expression.  These are mainly cases where the null pointer is used as an
10024 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)10025 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10026                                 SourceLocation Loc, bool IsCompare) {
10027   // The canonical way to check for a GNU null is with isNullPointerConstant,
10028   // but we use a bit of a hack here for speed; this is a relatively
10029   // hot path, and isNullPointerConstant is slow.
10030   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10031   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10032 
10033   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10034 
10035   // Avoid analyzing cases where the result will either be invalid (and
10036   // diagnosed as such) or entirely valid and not something to warn about.
10037   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10038       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10039     return;
10040 
10041   // Comparison operations would not make sense with a null pointer no matter
10042   // what the other expression is.
10043   if (!IsCompare) {
10044     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10045         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10046         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10047     return;
10048   }
10049 
10050   // The rest of the operations only make sense with a null pointer
10051   // if the other expression is a pointer.
10052   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10053       NonNullType->canDecayToPointerType())
10054     return;
10055 
10056   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10057       << LHSNull /* LHS is NULL */ << NonNullType
10058       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10059 }
10060 
DiagnoseDivisionSizeofPointerOrArray(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc)10061 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10062                                           SourceLocation Loc) {
10063   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10064   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10065   if (!LUE || !RUE)
10066     return;
10067   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10068       RUE->getKind() != UETT_SizeOf)
10069     return;
10070 
10071   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10072   QualType LHSTy = LHSArg->getType();
10073   QualType RHSTy;
10074 
10075   if (RUE->isArgumentType())
10076     RHSTy = RUE->getArgumentType();
10077   else
10078     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10079 
10080   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10081     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10082       return;
10083 
10084     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10085     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10086       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10087         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10088             << LHSArgDecl;
10089     }
10090   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10091     QualType ArrayElemTy = ArrayTy->getElementType();
10092     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10093         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10094         ArrayElemTy->isCharType() ||
10095         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10096       return;
10097     S.Diag(Loc, diag::warn_division_sizeof_array)
10098         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10099     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10100       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10101         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10102             << LHSArgDecl;
10103     }
10104 
10105     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10106   }
10107 }
10108 
diagnoseAmbiguousProvenance(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10109 static void diagnoseAmbiguousProvenance(Sema &S, ExprResult &LHS,
10110                                         ExprResult &RHS, SourceLocation Loc,
10111                                         bool IsCompAssign) {
10112   // For compound assignment the provenance source is obvious
10113   // TODO: for compound assignment, we should implement a warning that a
10114   //  capability RHS with a non-cap LHS is potentially inefficient.
10115   if (IsCompAssign)
10116     return;
10117 
10118   const QualType LHSType = LHS.get()->getType();
10119   const QualType RHSType = RHS.get()->getType();
10120   bool isLHSCap = LHSType->isCHERICapabilityType(S.Context);
10121   bool isRHSCap = RHSType->isCHERICapabilityType(S.Context);
10122   // If both sides can carry provenance (i.e. not marked as non-provenance
10123   // carrying) we should emit a warning
10124   bool LHSProvenance = isLHSCap && !LHSType->hasAttr(attr::CHERINoProvenance);
10125   bool RHSProvenance = isRHSCap && !RHSType->hasAttr(attr::CHERINoProvenance);
10126 
10127   if (LHSProvenance && RHSProvenance) {
10128     S.DiagRuntimeBehavior(
10129         Loc, RHS.get(),
10130         S.PDiag(diag::warn_ambiguous_provenance_capability_binop)
10131             << LHSType << RHSType << LHS.get()->getSourceRange()
10132             << RHS.get()->getSourceRange());
10133     // In the case of ambiguous provenance we currently default to LHS-derived
10134     // values. To achieve this behaviour, flag the RHS as non-provenance
10135     // carrying for code-generation.
10136     // FIXME: in the future make this an error and require manual annotation.
10137     RHS.get()->setType(
10138         S.Context.getAttributedType(attr::CHERINoProvenance, RHSType, RHSType));
10139   }
10140 }
10141 
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)10142 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10143                                                ExprResult &RHS,
10144                                                SourceLocation Loc, bool IsDiv) {
10145   // Check for division/remainder by zero.
10146   Expr::EvalResult RHSValue;
10147   if (!RHS.get()->isValueDependent() &&
10148       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10149       RHSValue.Val.getInt() == 0)
10150     S.DiagRuntimeBehavior(Loc, RHS.get(),
10151                           S.PDiag(diag::warn_remainder_division_by_zero)
10152                             << IsDiv << RHS.get()->getSourceRange());
10153 }
10154 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)10155 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10156                                            SourceLocation Loc,
10157                                            bool IsCompAssign, bool IsDiv) {
10158   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10159 
10160   if (LHS.get()->getType()->isVectorType() ||
10161       RHS.get()->getType()->isVectorType())
10162     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10163                                /*AllowBothBool*/getLangOpts().AltiVec,
10164                                /*AllowBoolConversions*/false);
10165   if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10166                  RHS.get()->getType()->isConstantMatrixType()))
10167     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10168 
10169   QualType compType = UsualArithmeticConversions(
10170       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10171   if (LHS.isInvalid() || RHS.isInvalid())
10172     return QualType();
10173 
10174 
10175   if (compType.isNull() || !compType->isArithmeticType())
10176     return InvalidOperands(Loc, LHS, RHS);
10177   if (IsDiv) {
10178     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10179     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10180   } else {
10181     diagnoseAmbiguousProvenance(*this, LHS, RHS, Loc, IsCompAssign);
10182   }
10183   return compType;
10184 }
10185 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10186 QualType Sema::CheckRemainderOperands(
10187   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10188   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10189 
10190   // Remainder in offset mode will not work for alignment checks since it
10191   // doesn't take the base into account so we warn then
10192   if (getLangOpts().cheriUIntCapUsesOffset() &&
10193       (LHS.get()->getType()->isCHERICapabilityType(Context) ||
10194        RHS.get()->getType()->isCHERICapabilityType(Context)))
10195     DiagRuntimeBehavior(
10196         Loc, RHS.get(),
10197         PDiag(diag::warn_uintcap_bad_bitwise_op)
10198             << 2 /*=modulo*/ << 1 /* used for alignment checks */
10199             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange());
10200 
10201   if (LHS.get()->getType()->isVectorType() ||
10202       RHS.get()->getType()->isVectorType()) {
10203     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10204         RHS.get()->getType()->hasIntegerRepresentation())
10205       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10206                                  /*AllowBothBool*/getLangOpts().AltiVec,
10207                                  /*AllowBoolConversions*/false);
10208     return InvalidOperands(Loc, LHS, RHS);
10209   }
10210 
10211   QualType compType = UsualArithmeticConversions(
10212       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10213   if (LHS.isInvalid() || RHS.isInvalid())
10214     return QualType();
10215 
10216   if (compType.isNull() || !compType->isIntegerType())
10217     return InvalidOperands(Loc, LHS, RHS);
10218   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10219   return compType;
10220 }
10221 
10222 /// Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10223 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10224                                                 Expr *LHSExpr, Expr *RHSExpr) {
10225   S.Diag(Loc, S.getLangOpts().CPlusPlus
10226                 ? diag::err_typecheck_pointer_arith_void_type
10227                 : diag::ext_gnu_void_ptr)
10228     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10229                             << RHSExpr->getSourceRange();
10230 }
10231 
10232 /// Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10233 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10234                                             Expr *Pointer) {
10235   S.Diag(Loc, S.getLangOpts().CPlusPlus
10236                 ? diag::err_typecheck_pointer_arith_void_type
10237                 : diag::ext_gnu_void_ptr)
10238     << 0 /* one pointer */ << Pointer->getSourceRange();
10239 }
10240 
10241 /// Diagnose invalid arithmetic on a null pointer.
10242 ///
10243 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10244 /// idiom, which we recognize as a GNU extension.
10245 ///
diagnoseArithmeticOnNullPointer(Sema & S,SourceLocation Loc,Expr * Pointer,bool IsGNUIdiom)10246 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10247                                             Expr *Pointer, bool IsGNUIdiom) {
10248   if (IsGNUIdiom)
10249     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10250       << Pointer->getSourceRange();
10251   else
10252     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10253       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10254 }
10255 
10256 /// Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)10257 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10258                                                     Expr *LHS, Expr *RHS) {
10259   assert(LHS->getType()->isAnyPointerType());
10260   assert(RHS->getType()->isAnyPointerType());
10261   S.Diag(Loc, S.getLangOpts().CPlusPlus
10262                 ? diag::err_typecheck_pointer_arith_function_type
10263                 : diag::ext_gnu_ptr_func_arith)
10264     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10265     // We only show the second type if it differs from the first.
10266     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10267                                                    RHS->getType())
10268     << RHS->getType()->getPointeeType()
10269     << LHS->getSourceRange() << RHS->getSourceRange();
10270 }
10271 
10272 /// Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10273 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10274                                                 Expr *Pointer) {
10275   assert(Pointer->getType()->isAnyPointerType());
10276   S.Diag(Loc, S.getLangOpts().CPlusPlus
10277                 ? diag::err_typecheck_pointer_arith_function_type
10278                 : diag::ext_gnu_ptr_func_arith)
10279     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10280     << 0 /* one pointer, so only one type */
10281     << Pointer->getSourceRange();
10282 }
10283 
10284 /// Emit error if Operand is incomplete pointer type
10285 ///
10286 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)10287 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10288                                                  Expr *Operand) {
10289   QualType ResType = Operand->getType();
10290   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10291     ResType = ResAtomicType->getValueType();
10292 
10293   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10294   QualType PointeeTy = ResType->getPointeeType();
10295   return S.RequireCompleteSizedType(
10296       Loc, PointeeTy,
10297       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10298       Operand->getSourceRange());
10299 }
10300 
10301 /// Check the validity of an arithmetic pointer operand.
10302 ///
10303 /// If the operand has pointer type, this code will check for pointer types
10304 /// which are invalid in arithmetic operations. These will be diagnosed
10305 /// appropriately, including whether or not the use is supported as an
10306 /// extension.
10307 ///
10308 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)10309 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10310                                             Expr *Operand) {
10311   QualType ResType = Operand->getType();
10312   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10313     ResType = ResAtomicType->getValueType();
10314 
10315   if (!ResType->isAnyPointerType()) return true;
10316 
10317   QualType PointeeTy = ResType->getPointeeType();
10318   if (PointeeTy->isVoidType()) {
10319     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10320     return !S.getLangOpts().CPlusPlus;
10321   }
10322   if (PointeeTy->isFunctionType()) {
10323     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10324     return !S.getLangOpts().CPlusPlus;
10325   }
10326 
10327   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10328 
10329   return true;
10330 }
10331 
10332 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10333 /// operands.
10334 ///
10335 /// This routine will diagnose any invalid arithmetic on pointer operands much
10336 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10337 /// for emitting a single diagnostic even for operations where both LHS and RHS
10338 /// are (potentially problematic) pointers.
10339 ///
10340 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10341 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10342                                                 Expr *LHSExpr, Expr *RHSExpr) {
10343   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10344   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10345   if (!isLHSPointer && !isRHSPointer) return true;
10346 
10347   QualType LHSPointeeTy, RHSPointeeTy;
10348   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10349   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10350 
10351   // if both are pointers check if operation is valid wrt address spaces
10352   if (isLHSPointer && isRHSPointer) {
10353     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10354       S.Diag(Loc,
10355              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10356           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10357           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10358       return false;
10359     }
10360   }
10361 
10362   if (isLHSPointer && isRHSPointer &&
10363       LHSExpr->getType()->isCHERICapabilityType(S.Context) !=
10364           RHSExpr->getType()->isCHERICapabilityType(S.Context)) {
10365     S.Diag(Loc, diag::err_typecheck_sub_pointer_capability)
10366         << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10367         << RHSExpr->getSourceRange();
10368     return false;
10369   }
10370 
10371   // Check for arithmetic on pointers to incomplete types.
10372   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10373   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10374   if (isLHSVoidPtr || isRHSVoidPtr) {
10375     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10376     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10377     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10378 
10379     return !S.getLangOpts().CPlusPlus;
10380   }
10381 
10382   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10383   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10384   if (isLHSFuncPtr || isRHSFuncPtr) {
10385     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10386     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10387                                                                 RHSExpr);
10388     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10389 
10390     return !S.getLangOpts().CPlusPlus;
10391   }
10392 
10393   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10394     return false;
10395   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10396     return false;
10397 
10398   return true;
10399 }
10400 
10401 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10402 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10403 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10404                                   Expr *LHSExpr, Expr *RHSExpr) {
10405   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10406   Expr* IndexExpr = RHSExpr;
10407   if (!StrExpr) {
10408     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10409     IndexExpr = LHSExpr;
10410   }
10411 
10412   bool IsStringPlusInt = StrExpr &&
10413       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10414   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10415     return;
10416 
10417   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10418   Self.Diag(OpLoc, diag::warn_string_plus_int)
10419       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10420 
10421   // Only print a fixit for "str" + int, not for int + "str".
10422   if (IndexExpr == RHSExpr) {
10423     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10424     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10425         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10426         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10427         << FixItHint::CreateInsertion(EndLoc, "]");
10428   } else
10429     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10430 }
10431 
10432 /// Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10433 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10434                                    Expr *LHSExpr, Expr *RHSExpr) {
10435   const Expr *StringRefExpr = LHSExpr;
10436   const CharacterLiteral *CharExpr =
10437       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10438 
10439   if (!CharExpr) {
10440     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10441     StringRefExpr = RHSExpr;
10442   }
10443 
10444   if (!CharExpr || !StringRefExpr)
10445     return;
10446 
10447   const QualType StringType = StringRefExpr->getType();
10448 
10449   // Return if not a PointerType.
10450   if (!StringType->isAnyPointerType())
10451     return;
10452 
10453   // Return if not a CharacterType.
10454   if (!StringType->getPointeeType()->isAnyCharacterType())
10455     return;
10456 
10457   ASTContext &Ctx = Self.getASTContext();
10458   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10459 
10460   const QualType CharType = CharExpr->getType();
10461   if (!CharType->isAnyCharacterType() &&
10462       CharType->isIntegerType() &&
10463       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10464     Self.Diag(OpLoc, diag::warn_string_plus_char)
10465         << DiagRange << Ctx.CharTy;
10466   } else {
10467     Self.Diag(OpLoc, diag::warn_string_plus_char)
10468         << DiagRange << CharExpr->getType();
10469   }
10470 
10471   // Only print a fixit for str + char, not for char + str.
10472   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10473     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10474     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10475         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10476         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10477         << FixItHint::CreateInsertion(EndLoc, "]");
10478   } else {
10479     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10480   }
10481 }
10482 
10483 /// Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10484 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10485                                            Expr *LHSExpr, Expr *RHSExpr) {
10486   assert(LHSExpr->getType()->isAnyPointerType());
10487   assert(RHSExpr->getType()->isAnyPointerType());
10488   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10489     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10490     << RHSExpr->getSourceRange();
10491 }
10492 
10493 // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)10494 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10495                                      SourceLocation Loc, BinaryOperatorKind Opc,
10496                                      QualType* CompLHSTy) {
10497   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10498 
10499   if (LHS.get()->getType()->isVectorType() ||
10500       RHS.get()->getType()->isVectorType()) {
10501     QualType compType = CheckVectorOperands(
10502         LHS, RHS, Loc, CompLHSTy,
10503         /*AllowBothBool*/getLangOpts().AltiVec,
10504         /*AllowBoolConversions*/getLangOpts().ZVector);
10505     if (CompLHSTy) *CompLHSTy = compType;
10506     return compType;
10507   }
10508 
10509   if (LHS.get()->getType()->isConstantMatrixType() ||
10510       RHS.get()->getType()->isConstantMatrixType()) {
10511     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10512   }
10513 
10514   QualType compType = UsualArithmeticConversions(
10515       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10516   if (LHS.isInvalid() || RHS.isInvalid())
10517     return QualType();
10518 
10519   // Diagnose "string literal" '+' int and string '+' "char literal".
10520   if (Opc == BO_Add) {
10521     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10522     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10523   }
10524 
10525   // handle the common case first (both operands are arithmetic).
10526   if (!compType.isNull() && compType->isArithmeticType()) {
10527     if (CompLHSTy) *CompLHSTy = compType;
10528     assert(Opc == BO_AddAssign || Opc == BO_Add);
10529     diagnoseAmbiguousProvenance(*this, LHS, RHS, Loc, Opc == BO_AddAssign);
10530     return compType;
10531   }
10532 
10533   // Type-checking.  Ultimately the pointer's going to be in PExp;
10534   // note that we bias towards the LHS being the pointer.
10535   Expr *PExp = LHS.get(), *IExp = RHS.get();
10536 
10537   bool isObjCPointer;
10538   if (PExp->getType()->isPointerType()) {
10539     isObjCPointer = false;
10540   } else if (PExp->getType()->isObjCObjectPointerType()) {
10541     isObjCPointer = true;
10542   } else {
10543     std::swap(PExp, IExp);
10544     if (PExp->getType()->isPointerType()) {
10545       isObjCPointer = false;
10546     } else if (PExp->getType()->isObjCObjectPointerType()) {
10547       isObjCPointer = true;
10548     } else {
10549       return InvalidOperands(Loc, LHS, RHS);
10550     }
10551   }
10552   assert(PExp->getType()->isAnyPointerType());
10553 
10554   if (!IExp->getType()->isIntegerType())
10555     return InvalidOperands(Loc, LHS, RHS);
10556 
10557   // Adding to a null pointer results in undefined behavior.
10558   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10559           Context, Expr::NPC_ValueDependentIsNotNull)) {
10560     // In C++ adding zero to a null pointer is defined.
10561     Expr::EvalResult KnownVal;
10562     if (!getLangOpts().CPlusPlus ||
10563         (!IExp->isValueDependent() &&
10564          (!IExp->EvaluateAsInt(KnownVal, Context) ||
10565           KnownVal.Val.getInt() != 0))) {
10566       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10567       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10568           Context, BO_Add, PExp, IExp);
10569       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10570     }
10571   }
10572 
10573   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10574     return QualType();
10575 
10576   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10577     return QualType();
10578 
10579   // Check array bounds for pointer arithemtic
10580   CheckArrayAccess(PExp, IExp);
10581 
10582   if (CompLHSTy) {
10583     QualType LHSTy = Context.isPromotableBitField(LHS.get());
10584     if (LHSTy.isNull()) {
10585       LHSTy = LHS.get()->getType();
10586       if (LHSTy->isPromotableIntegerType())
10587         LHSTy = Context.getPromotedIntegerType(LHSTy);
10588     }
10589     *CompLHSTy = LHSTy;
10590   }
10591 
10592   return PExp->getType();
10593 }
10594 
10595 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)10596 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10597                                         SourceLocation Loc,
10598                                         QualType* CompLHSTy) {
10599   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10600 
10601   if (LHS.get()->getType()->isVectorType() ||
10602       RHS.get()->getType()->isVectorType()) {
10603     QualType compType = CheckVectorOperands(
10604         LHS, RHS, Loc, CompLHSTy,
10605         /*AllowBothBool*/getLangOpts().AltiVec,
10606         /*AllowBoolConversions*/getLangOpts().ZVector);
10607     if (CompLHSTy) *CompLHSTy = compType;
10608     return compType;
10609   }
10610 
10611   if (LHS.get()->getType()->isConstantMatrixType() ||
10612       RHS.get()->getType()->isConstantMatrixType()) {
10613     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10614   }
10615 
10616   QualType compType = UsualArithmeticConversions(
10617       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10618   if (LHS.isInvalid() || RHS.isInvalid())
10619     return QualType();
10620 
10621   // Enforce type constraints: C99 6.5.6p3.
10622 
10623   // Handle the common case first (both operands are arithmetic).
10624   if (!compType.isNull() && compType->isArithmeticType()) {
10625     if (CompLHSTy) *CompLHSTy = compType;
10626     return compType;
10627   }
10628 
10629   // Either ptr - int   or   ptr - ptr.
10630   if (LHS.get()->getType()->isAnyPointerType()) {
10631     QualType lpointee = LHS.get()->getType()->getPointeeType();
10632 
10633     // Diagnose bad cases where we step over interface counts.
10634     if (LHS.get()->getType()->isObjCObjectPointerType() &&
10635         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10636       return QualType();
10637 
10638     // The result type of a pointer-int computation is the pointer type.
10639     if (RHS.get()->getType()->isIntegerType()) {
10640       // Subtracting from a null pointer should produce a warning.
10641       // The last argument to the diagnose call says this doesn't match the
10642       // GNU int-to-pointer idiom.
10643       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10644                                            Expr::NPC_ValueDependentIsNotNull)) {
10645         // In C++ adding zero to a null pointer is defined.
10646         Expr::EvalResult KnownVal;
10647         if (!getLangOpts().CPlusPlus ||
10648             (!RHS.get()->isValueDependent() &&
10649              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10650               KnownVal.Val.getInt() != 0))) {
10651           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10652         }
10653       }
10654 
10655       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10656         return QualType();
10657 
10658       // Check array bounds for pointer arithemtic
10659       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10660                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10661 
10662       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10663       return LHS.get()->getType();
10664     }
10665 
10666     // Handle pointer-pointer subtractions.
10667     if (const PointerType *RHSPTy
10668           = RHS.get()->getType()->getAs<PointerType>()) {
10669       QualType rpointee = RHSPTy->getPointeeType();
10670 
10671       if (getLangOpts().CPlusPlus) {
10672         // Pointee types must be the same: C++ [expr.add]
10673         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10674           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10675         }
10676       } else {
10677         // Pointee types must be compatible C99 6.5.6p3
10678         if (!Context.typesAreCompatible(
10679                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10680                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10681           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10682           return QualType();
10683         }
10684       }
10685 
10686       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10687                                                LHS.get(), RHS.get()))
10688         return QualType();
10689 
10690       // FIXME: Add warnings for nullptr - ptr.
10691 
10692       // The pointee type may have zero size.  As an extension, a structure or
10693       // union may have zero size or an array may have zero length.  In this
10694       // case subtraction does not make sense.
10695       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10696         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10697         if (ElementSize.isZero()) {
10698           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10699             << rpointee.getUnqualifiedType()
10700             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10701         }
10702       }
10703 
10704       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10705       return Context.getPointerDiffType();
10706     }
10707   }
10708 
10709   return InvalidOperands(Loc, LHS, RHS);
10710 }
10711 
isScopedEnumerationType(QualType T)10712 static bool isScopedEnumerationType(QualType T) {
10713   if (const EnumType *ET = T->getAs<EnumType>())
10714     return ET->getDecl()->isScoped();
10715   return false;
10716 }
10717 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)10718 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10719                                    SourceLocation Loc, BinaryOperatorKind Opc,
10720                                    QualType LHSType) {
10721   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10722   // so skip remaining warnings as we don't want to modify values within Sema.
10723   if (S.getLangOpts().OpenCL)
10724     return;
10725 
10726   // Check right/shifter operand
10727   Expr::EvalResult RHSResult;
10728   if (RHS.get()->isValueDependent() ||
10729       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10730     return;
10731   llvm::APSInt Right = RHSResult.Val.getInt();
10732 
10733   if (Right.isNegative()) {
10734     S.DiagRuntimeBehavior(Loc, RHS.get(),
10735                           S.PDiag(diag::warn_shift_negative)
10736                             << RHS.get()->getSourceRange());
10737     return;
10738   }
10739 
10740   QualType LHSExprType = LHS.get()->getType();
10741   uint64_t LeftSize = LHSExprType->isExtIntType()
10742                           ? S.Context.getIntWidth(LHSExprType)
10743                           : S.Context.getTypeSize(LHSExprType);
10744   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10745   if (Right.uge(LeftBits)) {
10746     S.DiagRuntimeBehavior(Loc, RHS.get(),
10747                           S.PDiag(diag::warn_shift_gt_typewidth)
10748                             << RHS.get()->getSourceRange());
10749     return;
10750   }
10751 
10752   if (Opc != BO_Shl)
10753     return;
10754 
10755   // When left shifting an ICE which is signed, we can check for overflow which
10756   // according to C++ standards prior to C++2a has undefined behavior
10757   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10758   // more than the maximum value representable in the result type, so never
10759   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10760   // expression is still probably a bug.)
10761   Expr::EvalResult LHSResult;
10762   if (LHS.get()->isValueDependent() ||
10763       LHSType->hasUnsignedIntegerRepresentation() ||
10764       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10765     return;
10766   llvm::APSInt Left = LHSResult.Val.getInt();
10767 
10768   // If LHS does not have a signed type and non-negative value
10769   // then, the behavior is undefined before C++2a. Warn about it.
10770   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10771       !S.getLangOpts().CPlusPlus20) {
10772     S.DiagRuntimeBehavior(Loc, LHS.get(),
10773                           S.PDiag(diag::warn_shift_lhs_negative)
10774                             << LHS.get()->getSourceRange());
10775     return;
10776   }
10777 
10778   llvm::APInt ResultBits =
10779       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10780   if (LeftBits.uge(ResultBits))
10781     return;
10782   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10783   Result = Result.shl(Right);
10784 
10785   // Print the bit representation of the signed integer as an unsigned
10786   // hexadecimal number.
10787   SmallString<40> HexResult;
10788   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10789 
10790   // If we are only missing a sign bit, this is less likely to result in actual
10791   // bugs -- if the result is cast back to an unsigned type, it will have the
10792   // expected value. Thus we place this behind a different warning that can be
10793   // turned off separately if needed.
10794   if (LeftBits == ResultBits - 1) {
10795     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10796         << HexResult << LHSType
10797         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10798     return;
10799   }
10800 
10801   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10802     << HexResult.str() << Result.getMinSignedBits() << LHSType
10803     << Left.getBitWidth() << LHS.get()->getSourceRange()
10804     << RHS.get()->getSourceRange();
10805 }
10806 
10807 /// Return the resulting type when a vector is shifted
10808 ///        by a scalar or vector shift amount.
checkVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10809 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10810                                  SourceLocation Loc, bool IsCompAssign) {
10811   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10812   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10813       !LHS.get()->getType()->isVectorType()) {
10814     S.Diag(Loc, diag::err_shift_rhs_only_vector)
10815       << RHS.get()->getType() << LHS.get()->getType()
10816       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10817     return QualType();
10818   }
10819 
10820   if (!IsCompAssign) {
10821     LHS = S.UsualUnaryConversions(LHS.get());
10822     if (LHS.isInvalid()) return QualType();
10823   }
10824 
10825   RHS = S.UsualUnaryConversions(RHS.get());
10826   if (RHS.isInvalid()) return QualType();
10827 
10828   QualType LHSType = LHS.get()->getType();
10829   // Note that LHS might be a scalar because the routine calls not only in
10830   // OpenCL case.
10831   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10832   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10833 
10834   // Note that RHS might not be a vector.
10835   QualType RHSType = RHS.get()->getType();
10836   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10837   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10838 
10839   // The operands need to be integers.
10840   if (!LHSEleType->isIntegerType()) {
10841     S.Diag(Loc, diag::err_typecheck_expect_int)
10842       << LHS.get()->getType() << LHS.get()->getSourceRange();
10843     return QualType();
10844   }
10845 
10846   if (!RHSEleType->isIntegerType()) {
10847     S.Diag(Loc, diag::err_typecheck_expect_int)
10848       << RHS.get()->getType() << RHS.get()->getSourceRange();
10849     return QualType();
10850   }
10851 
10852   if (!LHSVecTy) {
10853     assert(RHSVecTy);
10854     if (IsCompAssign)
10855       return RHSType;
10856     if (LHSEleType != RHSEleType) {
10857       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10858       LHSEleType = RHSEleType;
10859     }
10860     QualType VecTy =
10861         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10862     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10863     LHSType = VecTy;
10864   } else if (RHSVecTy) {
10865     // OpenCL v1.1 s6.3.j says that for vector types, the operators
10866     // are applied component-wise. So if RHS is a vector, then ensure
10867     // that the number of elements is the same as LHS...
10868     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10869       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10870         << LHS.get()->getType() << RHS.get()->getType()
10871         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10872       return QualType();
10873     }
10874     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10875       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10876       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10877       if (LHSBT != RHSBT &&
10878           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10879         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10880             << LHS.get()->getType() << RHS.get()->getType()
10881             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10882       }
10883     }
10884   } else {
10885     // ...else expand RHS to match the number of elements in LHS.
10886     QualType VecTy =
10887       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10888     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10889   }
10890 
10891   return LHSType;
10892 }
10893 
10894 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)10895 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10896                                   SourceLocation Loc, BinaryOperatorKind Opc,
10897                                   bool IsCompAssign) {
10898   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10899 
10900   // Vector shifts promote their scalar inputs to vector type.
10901   if (LHS.get()->getType()->isVectorType() ||
10902       RHS.get()->getType()->isVectorType()) {
10903     if (LangOpts.ZVector) {
10904       // The shift operators for the z vector extensions work basically
10905       // like general shifts, except that neither the LHS nor the RHS is
10906       // allowed to be a "vector bool".
10907       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10908         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10909           return InvalidOperands(Loc, LHS, RHS);
10910       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10911         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10912           return InvalidOperands(Loc, LHS, RHS);
10913     }
10914     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10915   }
10916 
10917   // Shifts don't perform usual arithmetic conversions, they just do integer
10918   // promotions on each operand. C99 6.5.7p3
10919 
10920   // For the LHS, do usual unary conversions, but then reset them away
10921   // if this is a compound assignment.
10922   ExprResult OldLHS = LHS;
10923   LHS = UsualUnaryConversions(LHS.get());
10924   if (LHS.isInvalid())
10925     return QualType();
10926   QualType LHSType = LHS.get()->getType();
10927   if (IsCompAssign) LHS = OldLHS;
10928 
10929   // The RHS is simpler.
10930   RHS = UsualUnaryConversions(RHS.get());
10931   if (RHS.isInvalid())
10932     return QualType();
10933   QualType RHSType = RHS.get()->getType();
10934 
10935   // C99 6.5.7p2: Each of the operands shall have integer type.
10936   if (!LHSType->hasIntegerRepresentation() ||
10937       !RHSType->hasIntegerRepresentation())
10938     return InvalidOperands(Loc, LHS, RHS);
10939 
10940   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10941   // hasIntegerRepresentation() above instead of this.
10942   if (isScopedEnumerationType(LHSType) ||
10943       isScopedEnumerationType(RHSType)) {
10944     return InvalidOperands(Loc, LHS, RHS);
10945   }
10946   // Sanity-check shift operands
10947   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10948 
10949   // In CHERI offset mode shifts only look at the offset and ignore the base.
10950   // This is rarely the intended behaviour so warn if that is the case.
10951   if (getLangOpts().cheriUIntCapUsesOffset() &&
10952       (LHSType->isIntCapType() || RHSType->isIntCapType()) &&
10953       (Opc == BO_Shl || Opc == BO_ShlAssign || Opc == BO_Shr ||
10954        Opc == BO_ShrAssign))
10955     DiagRuntimeBehavior(Loc, RHS.get(),
10956                         PDiag(diag::warn_uintcap_bad_bitwise_op)
10957                             << 1 /*=shift*/ << 0 /* usecase is hashing */
10958                             << LHS.get()->getSourceRange()
10959                             << RHS.get()->getSourceRange());
10960 
10961   // "The type of the result is that of the promoted left operand."
10962   return LHSType;
10963 }
10964 
10965 /// Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)10966 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10967                                               ExprResult &LHS, ExprResult &RHS,
10968                                               bool IsError) {
10969   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10970                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10971     << LHS.get()->getType() << RHS.get()->getType()
10972     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10973 }
10974 
10975 /// Returns false if the pointers are converted to a composite type,
10976 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)10977 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10978                                            ExprResult &LHS, ExprResult &RHS) {
10979   // C++ [expr.rel]p2:
10980   //   [...] Pointer conversions (4.10) and qualification
10981   //   conversions (4.4) are performed on pointer operands (or on
10982   //   a pointer operand and a null pointer constant) to bring
10983   //   them to their composite pointer type. [...]
10984   //
10985   // C++ [expr.eq]p1 uses the same notion for (in)equality
10986   // comparisons of pointers.
10987 
10988   QualType LHSType = LHS.get()->getType();
10989   QualType RHSType = RHS.get()->getType();
10990   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10991          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10992 
10993   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10994   if (T.isNull()) {
10995     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10996         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10997       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10998     else
10999       S.InvalidOperands(Loc, LHS, RHS);
11000     return true;
11001   }
11002 
11003   return false;
11004 }
11005 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)11006 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11007                                                     ExprResult &LHS,
11008                                                     ExprResult &RHS,
11009                                                     bool IsError) {
11010   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11011                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11012     << LHS.get()->getType() << RHS.get()->getType()
11013     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11014 }
11015 
isObjCObjectLiteral(ExprResult & E)11016 static bool isObjCObjectLiteral(ExprResult &E) {
11017   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11018   case Stmt::ObjCArrayLiteralClass:
11019   case Stmt::ObjCDictionaryLiteralClass:
11020   case Stmt::ObjCStringLiteralClass:
11021   case Stmt::ObjCBoxedExprClass:
11022     return true;
11023   default:
11024     // Note that ObjCBoolLiteral is NOT an object literal!
11025     return false;
11026   }
11027 }
11028 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)11029 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11030   const ObjCObjectPointerType *Type =
11031     LHS->getType()->getAs<ObjCObjectPointerType>();
11032 
11033   // If this is not actually an Objective-C object, bail out.
11034   if (!Type)
11035     return false;
11036 
11037   // Get the LHS object's interface type.
11038   QualType InterfaceType = Type->getPointeeType();
11039 
11040   // If the RHS isn't an Objective-C object, bail out.
11041   if (!RHS->getType()->isObjCObjectPointerType())
11042     return false;
11043 
11044   // Try to find the -isEqual: method.
11045   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11046   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11047                                                       InterfaceType,
11048                                                       /*IsInstance=*/true);
11049   if (!Method) {
11050     if (Type->isObjCIdType()) {
11051       // For 'id', just check the global pool.
11052       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11053                                                   /*receiverId=*/true);
11054     } else {
11055       // Check protocols.
11056       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11057                                              /*IsInstance=*/true);
11058     }
11059   }
11060 
11061   if (!Method)
11062     return false;
11063 
11064   QualType T = Method->parameters()[0]->getType();
11065   if (!T->isObjCObjectPointerType())
11066     return false;
11067 
11068   QualType R = Method->getReturnType();
11069   if (!R->isScalarType())
11070     return false;
11071 
11072   return true;
11073 }
11074 
CheckLiteralKind(Expr * FromE)11075 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11076   FromE = FromE->IgnoreParenImpCasts();
11077   switch (FromE->getStmtClass()) {
11078     default:
11079       break;
11080     case Stmt::ObjCStringLiteralClass:
11081       // "string literal"
11082       return LK_String;
11083     case Stmt::ObjCArrayLiteralClass:
11084       // "array literal"
11085       return LK_Array;
11086     case Stmt::ObjCDictionaryLiteralClass:
11087       // "dictionary literal"
11088       return LK_Dictionary;
11089     case Stmt::BlockExprClass:
11090       return LK_Block;
11091     case Stmt::ObjCBoxedExprClass: {
11092       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11093       switch (Inner->getStmtClass()) {
11094         case Stmt::IntegerLiteralClass:
11095         case Stmt::FloatingLiteralClass:
11096         case Stmt::CharacterLiteralClass:
11097         case Stmt::ObjCBoolLiteralExprClass:
11098         case Stmt::CXXBoolLiteralExprClass:
11099           // "numeric literal"
11100           return LK_Numeric;
11101         case Stmt::ImplicitCastExprClass: {
11102           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11103           // Boolean literals can be represented by implicit casts.
11104           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11105             return LK_Numeric;
11106           break;
11107         }
11108         default:
11109           break;
11110       }
11111       return LK_Boxed;
11112     }
11113   }
11114   return LK_None;
11115 }
11116 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)11117 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11118                                           ExprResult &LHS, ExprResult &RHS,
11119                                           BinaryOperator::Opcode Opc){
11120   Expr *Literal;
11121   Expr *Other;
11122   if (isObjCObjectLiteral(LHS)) {
11123     Literal = LHS.get();
11124     Other = RHS.get();
11125   } else {
11126     Literal = RHS.get();
11127     Other = LHS.get();
11128   }
11129 
11130   // Don't warn on comparisons against nil.
11131   Other = Other->IgnoreParenCasts();
11132   if (Other->isNullPointerConstant(S.getASTContext(),
11133                                    Expr::NPC_ValueDependentIsNotNull))
11134     return;
11135 
11136   // This should be kept in sync with warn_objc_literal_comparison.
11137   // LK_String should always be after the other literals, since it has its own
11138   // warning flag.
11139   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11140   assert(LiteralKind != Sema::LK_Block);
11141   if (LiteralKind == Sema::LK_None) {
11142     llvm_unreachable("Unknown Objective-C object literal kind");
11143   }
11144 
11145   if (LiteralKind == Sema::LK_String)
11146     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11147       << Literal->getSourceRange();
11148   else
11149     S.Diag(Loc, diag::warn_objc_literal_comparison)
11150       << LiteralKind << Literal->getSourceRange();
11151 
11152   if (BinaryOperator::isEqualityOp(Opc) &&
11153       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11154     SourceLocation Start = LHS.get()->getBeginLoc();
11155     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11156     CharSourceRange OpRange =
11157       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11158 
11159     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11160       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11161       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11162       << FixItHint::CreateInsertion(End, "]");
11163   }
11164 }
11165 
11166 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
diagnoseLogicalNotOnLHSofCheck(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11167 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11168                                            ExprResult &RHS, SourceLocation Loc,
11169                                            BinaryOperatorKind Opc) {
11170   // Check that left hand side is !something.
11171   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11172   if (!UO || UO->getOpcode() != UO_LNot) return;
11173 
11174   // Only check if the right hand side is non-bool arithmetic type.
11175   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11176 
11177   // Make sure that the something in !something is not bool.
11178   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11179   if (SubExpr->isKnownToHaveBooleanValue()) return;
11180 
11181   // Emit warning.
11182   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11183   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11184       << Loc << IsBitwiseOp;
11185 
11186   // First note suggest !(x < y)
11187   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11188   SourceLocation FirstClose = RHS.get()->getEndLoc();
11189   FirstClose = S.getLocForEndOfToken(FirstClose);
11190   if (FirstClose.isInvalid())
11191     FirstOpen = SourceLocation();
11192   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11193       << IsBitwiseOp
11194       << FixItHint::CreateInsertion(FirstOpen, "(")
11195       << FixItHint::CreateInsertion(FirstClose, ")");
11196 
11197   // Second note suggests (!x) < y
11198   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11199   SourceLocation SecondClose = LHS.get()->getEndLoc();
11200   SecondClose = S.getLocForEndOfToken(SecondClose);
11201   if (SecondClose.isInvalid())
11202     SecondOpen = SourceLocation();
11203   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11204       << FixItHint::CreateInsertion(SecondOpen, "(")
11205       << FixItHint::CreateInsertion(SecondClose, ")");
11206 }
11207 
11208 // Returns true if E refers to a non-weak array.
checkForArray(const Expr * E)11209 static bool checkForArray(const Expr *E) {
11210   const ValueDecl *D = nullptr;
11211   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11212     D = DR->getDecl();
11213   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11214     if (Mem->isImplicitAccess())
11215       D = Mem->getMemberDecl();
11216   }
11217   if (!D)
11218     return false;
11219   return D->getType()->isArrayType() && !D->isWeak();
11220 }
11221 
11222 /// Diagnose some forms of syntactically-obvious tautological comparison.
diagnoseTautologicalComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS,BinaryOperatorKind Opc)11223 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11224                                            Expr *LHS, Expr *RHS,
11225                                            BinaryOperatorKind Opc) {
11226   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11227   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11228 
11229   QualType LHSType = LHS->getType();
11230   QualType RHSType = RHS->getType();
11231   if (LHSType->hasFloatingRepresentation() ||
11232       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11233       S.inTemplateInstantiation())
11234     return;
11235 
11236   // Comparisons between two array types are ill-formed for operator<=>, so
11237   // we shouldn't emit any additional warnings about it.
11238   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11239     return;
11240 
11241   // For non-floating point types, check for self-comparisons of the form
11242   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11243   // often indicate logic errors in the program.
11244   //
11245   // NOTE: Don't warn about comparison expressions resulting from macro
11246   // expansion. Also don't warn about comparisons which are only self
11247   // comparisons within a template instantiation. The warnings should catch
11248   // obvious cases in the definition of the template anyways. The idea is to
11249   // warn when the typed comparison operator will always evaluate to the same
11250   // result.
11251 
11252   // Used for indexing into %select in warn_comparison_always
11253   enum {
11254     AlwaysConstant,
11255     AlwaysTrue,
11256     AlwaysFalse,
11257     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11258   };
11259 
11260   // C++2a [depr.array.comp]:
11261   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11262   //   operands of array type are deprecated.
11263   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11264       RHSStripped->getType()->isArrayType()) {
11265     S.Diag(Loc, diag::warn_depr_array_comparison)
11266         << LHS->getSourceRange() << RHS->getSourceRange()
11267         << LHSStripped->getType() << RHSStripped->getType();
11268     // Carry on to produce the tautological comparison warning, if this
11269     // expression is potentially-evaluated, we can resolve the array to a
11270     // non-weak declaration, and so on.
11271   }
11272 
11273   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11274     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11275       unsigned Result;
11276       switch (Opc) {
11277       case BO_EQ:
11278       case BO_LE:
11279       case BO_GE:
11280         Result = AlwaysTrue;
11281         break;
11282       case BO_NE:
11283       case BO_LT:
11284       case BO_GT:
11285         Result = AlwaysFalse;
11286         break;
11287       case BO_Cmp:
11288         Result = AlwaysEqual;
11289         break;
11290       default:
11291         Result = AlwaysConstant;
11292         break;
11293       }
11294       S.DiagRuntimeBehavior(Loc, nullptr,
11295                             S.PDiag(diag::warn_comparison_always)
11296                                 << 0 /*self-comparison*/
11297                                 << Result);
11298     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11299       // What is it always going to evaluate to?
11300       unsigned Result;
11301       switch (Opc) {
11302       case BO_EQ: // e.g. array1 == array2
11303         Result = AlwaysFalse;
11304         break;
11305       case BO_NE: // e.g. array1 != array2
11306         Result = AlwaysTrue;
11307         break;
11308       default: // e.g. array1 <= array2
11309         // The best we can say is 'a constant'
11310         Result = AlwaysConstant;
11311         break;
11312       }
11313       S.DiagRuntimeBehavior(Loc, nullptr,
11314                             S.PDiag(diag::warn_comparison_always)
11315                                 << 1 /*array comparison*/
11316                                 << Result);
11317     }
11318   }
11319 
11320   if (isa<CastExpr>(LHSStripped))
11321     LHSStripped = LHSStripped->IgnoreParenCasts();
11322   if (isa<CastExpr>(RHSStripped))
11323     RHSStripped = RHSStripped->IgnoreParenCasts();
11324 
11325   // Warn about comparisons against a string constant (unless the other
11326   // operand is null); the user probably wants string comparison function.
11327   Expr *LiteralString = nullptr;
11328   Expr *LiteralStringStripped = nullptr;
11329   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11330       !RHSStripped->isNullPointerConstant(S.Context,
11331                                           Expr::NPC_ValueDependentIsNull)) {
11332     LiteralString = LHS;
11333     LiteralStringStripped = LHSStripped;
11334   } else if ((isa<StringLiteral>(RHSStripped) ||
11335               isa<ObjCEncodeExpr>(RHSStripped)) &&
11336              !LHSStripped->isNullPointerConstant(S.Context,
11337                                           Expr::NPC_ValueDependentIsNull)) {
11338     LiteralString = RHS;
11339     LiteralStringStripped = RHSStripped;
11340   }
11341 
11342   if (LiteralString) {
11343     S.DiagRuntimeBehavior(Loc, nullptr,
11344                           S.PDiag(diag::warn_stringcompare)
11345                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
11346                               << LiteralString->getSourceRange());
11347   }
11348 }
11349 
castKindToImplicitConversionKind(CastKind CK)11350 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11351   switch (CK) {
11352   default: {
11353 #ifndef NDEBUG
11354     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11355                  << "\n";
11356 #endif
11357     llvm_unreachable("unhandled cast kind");
11358   }
11359   case CK_UserDefinedConversion:
11360     return ICK_Identity;
11361   case CK_LValueToRValue:
11362     return ICK_Lvalue_To_Rvalue;
11363   case CK_ArrayToPointerDecay:
11364     return ICK_Array_To_Pointer;
11365   case CK_FunctionToPointerDecay:
11366     return ICK_Function_To_Pointer;
11367   case CK_IntegralCast:
11368     return ICK_Integral_Conversion;
11369   case CK_FloatingCast:
11370     return ICK_Floating_Conversion;
11371   case CK_IntegralToFloating:
11372   case CK_FloatingToIntegral:
11373     return ICK_Floating_Integral;
11374   case CK_IntegralComplexCast:
11375   case CK_FloatingComplexCast:
11376   case CK_FloatingComplexToIntegralComplex:
11377   case CK_IntegralComplexToFloatingComplex:
11378     return ICK_Complex_Conversion;
11379   case CK_FloatingComplexToReal:
11380   case CK_FloatingRealToComplex:
11381   case CK_IntegralComplexToReal:
11382   case CK_IntegralRealToComplex:
11383     return ICK_Complex_Real;
11384   }
11385 }
11386 
checkThreeWayNarrowingConversion(Sema & S,QualType ToType,Expr * E,QualType FromType,SourceLocation Loc)11387 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11388                                              QualType FromType,
11389                                              SourceLocation Loc) {
11390   // Check for a narrowing implicit conversion.
11391   StandardConversionSequence SCS;
11392   SCS.setAsIdentityConversion();
11393   SCS.setToType(0, FromType);
11394   SCS.setToType(1, ToType);
11395   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11396     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11397 
11398   APValue PreNarrowingValue;
11399   QualType PreNarrowingType;
11400   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11401                                PreNarrowingType,
11402                                /*IgnoreFloatToIntegralConversion*/ true)) {
11403   case NK_Dependent_Narrowing:
11404     // Implicit conversion to a narrower type, but the expression is
11405     // value-dependent so we can't tell whether it's actually narrowing.
11406   case NK_Not_Narrowing:
11407     return false;
11408 
11409   case NK_Constant_Narrowing:
11410     // Implicit conversion to a narrower type, and the value is not a constant
11411     // expression.
11412     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11413         << /*Constant*/ 1
11414         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11415     return true;
11416 
11417   case NK_Variable_Narrowing:
11418     // Implicit conversion to a narrower type, and the value is not a constant
11419     // expression.
11420   case NK_Type_Narrowing:
11421     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11422         << /*Constant*/ 0 << FromType << ToType;
11423     // TODO: It's not a constant expression, but what if the user intended it
11424     // to be? Can we produce notes to help them figure out why it isn't?
11425     return true;
11426   }
11427   llvm_unreachable("unhandled case in switch");
11428 }
11429 
checkArithmeticOrEnumeralThreeWayCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)11430 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11431                                                          ExprResult &LHS,
11432                                                          ExprResult &RHS,
11433                                                          SourceLocation Loc) {
11434   QualType LHSType = LHS.get()->getType();
11435   QualType RHSType = RHS.get()->getType();
11436   // Dig out the original argument type and expression before implicit casts
11437   // were applied. These are the types/expressions we need to check the
11438   // [expr.spaceship] requirements against.
11439   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11440   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11441   QualType LHSStrippedType = LHSStripped.get()->getType();
11442   QualType RHSStrippedType = RHSStripped.get()->getType();
11443 
11444   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11445   // other is not, the program is ill-formed.
11446   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11447     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11448     return QualType();
11449   }
11450 
11451   // FIXME: Consider combining this with checkEnumArithmeticConversions.
11452   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11453                     RHSStrippedType->isEnumeralType();
11454   if (NumEnumArgs == 1) {
11455     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11456     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11457     if (OtherTy->hasFloatingRepresentation()) {
11458       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11459       return QualType();
11460     }
11461   }
11462   if (NumEnumArgs == 2) {
11463     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11464     // type E, the operator yields the result of converting the operands
11465     // to the underlying type of E and applying <=> to the converted operands.
11466     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11467       S.InvalidOperands(Loc, LHS, RHS);
11468       return QualType();
11469     }
11470     QualType IntType =
11471         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11472     assert(IntType->isArithmeticType());
11473 
11474     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11475     // promote the boolean type, and all other promotable integer types, to
11476     // avoid this.
11477     if (IntType->isPromotableIntegerType())
11478       IntType = S.Context.getPromotedIntegerType(IntType);
11479 
11480     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11481     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11482     LHSType = RHSType = IntType;
11483   }
11484 
11485   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11486   // usual arithmetic conversions are applied to the operands.
11487   QualType Type =
11488       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11489   if (LHS.isInvalid() || RHS.isInvalid())
11490     return QualType();
11491   if (Type.isNull())
11492     return S.InvalidOperands(Loc, LHS, RHS);
11493 
11494   Optional<ComparisonCategoryType> CCT =
11495       getComparisonCategoryForBuiltinCmp(Type);
11496   if (!CCT)
11497     return S.InvalidOperands(Loc, LHS, RHS);
11498 
11499   bool HasNarrowing = checkThreeWayNarrowingConversion(
11500       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11501   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11502                                                    RHS.get()->getBeginLoc());
11503   if (HasNarrowing)
11504     return QualType();
11505 
11506   assert(!Type.isNull() && "composite type for <=> has not been set");
11507 
11508   return S.CheckComparisonCategoryType(
11509       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11510 }
11511 
checkArithmeticOrEnumeralCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11512 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11513                                                  ExprResult &RHS,
11514                                                  SourceLocation Loc,
11515                                                  BinaryOperatorKind Opc) {
11516   if (Opc == BO_Cmp)
11517     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11518 
11519   // C99 6.5.8p3 / C99 6.5.9p4
11520   QualType Type =
11521       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11522   if (LHS.isInvalid() || RHS.isInvalid())
11523     return QualType();
11524   if (Type.isNull())
11525     return S.InvalidOperands(Loc, LHS, RHS);
11526   assert(Type->isArithmeticType() || Type->isEnumeralType());
11527 
11528   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11529     return S.InvalidOperands(Loc, LHS, RHS);
11530 
11531   // Check for comparisons of floating point operands using != and ==.
11532   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11533     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11534 
11535   // The result of comparisons is 'bool' in C++, 'int' in C.
11536   return S.Context.getLogicalOperationType();
11537 }
11538 
CheckPtrComparisonWithNullChar(ExprResult & E,ExprResult & NullE)11539 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11540   if (!NullE.get()->getType()->isAnyPointerType())
11541     return;
11542   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11543   if (!E.get()->getType()->isAnyPointerType() &&
11544       E.get()->isNullPointerConstant(Context,
11545                                      Expr::NPC_ValueDependentIsNotNull) ==
11546         Expr::NPCK_ZeroExpression) {
11547     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11548       if (CL->getValue() == 0)
11549         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11550             << NullValue
11551             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11552                                             NullValue ? "NULL" : "(void *)0");
11553     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11554         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11555         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11556         if (T == Context.CharTy)
11557           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11558               << NullValue
11559               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11560                                               NullValue ? "NULL" : "(void *)0");
11561       }
11562   }
11563 }
11564 
11565 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11566 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11567                                     SourceLocation Loc,
11568                                     BinaryOperatorKind Opc) {
11569   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11570   bool IsThreeWay = Opc == BO_Cmp;
11571   bool IsOrdered = IsRelational || IsThreeWay;
11572   auto IsAnyPointerType = [](ExprResult E) {
11573     QualType Ty = E.get()->getType();
11574     return Ty->isPointerType() || Ty->isMemberPointerType();
11575   };
11576 
11577   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11578   // type, array-to-pointer, ..., conversions are performed on both operands to
11579   // bring them to their composite type.
11580   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11581   // any type-related checks.
11582   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11583     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11584     if (LHS.isInvalid())
11585       return QualType();
11586     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11587     if (RHS.isInvalid())
11588       return QualType();
11589   } else {
11590     LHS = DefaultLvalueConversion(LHS.get());
11591     if (LHS.isInvalid())
11592       return QualType();
11593     RHS = DefaultLvalueConversion(RHS.get());
11594     if (RHS.isInvalid())
11595       return QualType();
11596   }
11597 
11598   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11599   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11600     CheckPtrComparisonWithNullChar(LHS, RHS);
11601     CheckPtrComparisonWithNullChar(RHS, LHS);
11602   }
11603 
11604   // Handle vector comparisons separately.
11605   if (LHS.get()->getType()->isVectorType() ||
11606       RHS.get()->getType()->isVectorType())
11607     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11608 
11609   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11610   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11611 
11612   QualType LHSType = LHS.get()->getType();
11613   QualType RHSType = RHS.get()->getType();
11614   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11615       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11616     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11617 
11618   const Expr::NullPointerConstantKind LHSNullKind =
11619       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11620   const Expr::NullPointerConstantKind RHSNullKind =
11621       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11622   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11623   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11624 
11625   auto computeResultTy = [&]() {
11626     if (Opc != BO_Cmp)
11627       return Context.getLogicalOperationType();
11628     assert(getLangOpts().CPlusPlus);
11629     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11630 
11631     QualType CompositeTy = LHS.get()->getType();
11632     assert(!CompositeTy->isReferenceType());
11633 
11634     Optional<ComparisonCategoryType> CCT =
11635         getComparisonCategoryForBuiltinCmp(CompositeTy);
11636     if (!CCT)
11637       return InvalidOperands(Loc, LHS, RHS);
11638 
11639     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11640       // P0946R0: Comparisons between a null pointer constant and an object
11641       // pointer result in std::strong_equality, which is ill-formed under
11642       // P1959R0.
11643       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11644           << (LHSIsNull ? LHS.get()->getSourceRange()
11645                         : RHS.get()->getSourceRange());
11646       return QualType();
11647     }
11648 
11649     return CheckComparisonCategoryType(
11650         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11651   };
11652 
11653   if (!IsOrdered && LHSIsNull != RHSIsNull) {
11654     bool IsEquality = Opc == BO_EQ;
11655     if (RHSIsNull)
11656       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11657                                    RHS.get()->getSourceRange());
11658     else
11659       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11660                                    LHS.get()->getSourceRange());
11661   }
11662 
11663   if ((LHSType->isIntegerType() && !LHSIsNull) ||
11664       (RHSType->isIntegerType() && !RHSIsNull)) {
11665     // Skip normal pointer conversion checks in this case; we have better
11666     // diagnostics for this below.
11667   } else if (getLangOpts().CPlusPlus) {
11668     // Equality comparison of a function pointer to a void pointer is invalid,
11669     // but we allow it as an extension.
11670     // FIXME: If we really want to allow this, should it be part of composite
11671     // pointer type computation so it works in conditionals too?
11672     if (!IsOrdered &&
11673         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11674          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11675       // This is a gcc extension compatibility comparison.
11676       // In a SFINAE context, we treat this as a hard error to maintain
11677       // conformance with the C++ standard.
11678       diagnoseFunctionPointerToVoidComparison(
11679           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11680 
11681       if (isSFINAEContext())
11682         return QualType();
11683 
11684       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11685       return computeResultTy();
11686     }
11687 
11688     // C++ [expr.eq]p2:
11689     //   If at least one operand is a pointer [...] bring them to their
11690     //   composite pointer type.
11691     // C++ [expr.spaceship]p6
11692     //  If at least one of the operands is of pointer type, [...] bring them
11693     //  to their composite pointer type.
11694     // C++ [expr.rel]p2:
11695     //   If both operands are pointers, [...] bring them to their composite
11696     //   pointer type.
11697     // For <=>, the only valid non-pointer types are arrays and functions, and
11698     // we already decayed those, so this is really the same as the relational
11699     // comparison rule.
11700     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11701             (IsOrdered ? 2 : 1) &&
11702         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11703                                          RHSType->isObjCObjectPointerType()))) {
11704       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11705         return QualType();
11706       return computeResultTy();
11707     }
11708   } else if (LHSType->isPointerType() &&
11709              RHSType->isPointerType()) { // C99 6.5.8p2
11710     bool LHSIsCap = LHSType->isCHERICapabilityType(Context);
11711     bool RHSIsCap = RHSType->isCHERICapabilityType(Context);
11712 
11713     // Binary operations between pointers and capabilities are errors
11714     if (LHSIsCap != RHSIsCap && !(LHSIsNull || RHSIsNull))
11715       Diag(Loc, diag::err_typecheck_comparison_of_pointer_capability)
11716         << LHSType << RHSType << LHS.get()->getSourceRange()
11717         << RHS.get()->getSourceRange();
11718 
11719     // We only implicitly cast the NULL constant to a memory capability
11720     if (LHSIsNull && !LHSIsCap && RHSIsCap)
11721       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11722     else if (RHSIsNull && !RHSIsCap && LHSIsCap)
11723       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11724 
11725     // All of the following pointer-related warnings are GCC extensions, except
11726     // when handling null pointer constants.
11727     QualType LCanPointeeTy =
11728       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11729     QualType RCanPointeeTy =
11730       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11731 
11732     // C99 6.5.9p2 and C99 6.5.8p2
11733     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11734                                    RCanPointeeTy.getUnqualifiedType())) {
11735       if (IsRelational) {
11736         // Pointers both need to point to complete or incomplete types
11737         if ((LCanPointeeTy->isIncompleteType() !=
11738              RCanPointeeTy->isIncompleteType()) &&
11739             !getLangOpts().C11) {
11740           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11741               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11742               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11743               << RCanPointeeTy->isIncompleteType();
11744         }
11745         if (LCanPointeeTy->isFunctionType()) {
11746           // Valid unless a relational comparison of function pointers
11747           Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11748               << LHSType << RHSType << LHS.get()->getSourceRange()
11749               << RHS.get()->getSourceRange();
11750         }
11751       }
11752     } else if (!IsRelational &&
11753                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11754       // Valid unless comparison between non-null pointer and function pointer
11755       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11756           && !LHSIsNull && !RHSIsNull)
11757         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11758                                                 /*isError*/false);
11759     } else {
11760       // Invalid
11761       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11762     }
11763     if (LCanPointeeTy != RCanPointeeTy) {
11764       // Treat NULL constant as a special case in OpenCL.
11765       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11766         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11767           Diag(Loc,
11768                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11769               << LHSType << RHSType << 0 /* comparison */
11770               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11771         }
11772       }
11773       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11774       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11775       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11776                                                : CK_BitCast;
11777       if (LHSIsNull && !RHSIsNull)
11778         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11779       else
11780         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11781     }
11782     return computeResultTy();
11783   }
11784 
11785   if (getLangOpts().CPlusPlus) {
11786     // C++ [expr.eq]p4:
11787     //   Two operands of type std::nullptr_t or one operand of type
11788     //   std::nullptr_t and the other a null pointer constant compare equal.
11789     if (!IsOrdered && LHSIsNull && RHSIsNull) {
11790       if (LHSType->isNullPtrType()) {
11791         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11792         return computeResultTy();
11793       }
11794       if (RHSType->isNullPtrType()) {
11795         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11796         return computeResultTy();
11797       }
11798     }
11799 
11800     // Comparison of Objective-C pointers and block pointers against nullptr_t.
11801     // These aren't covered by the composite pointer type rules.
11802     if (!IsOrdered && RHSType->isNullPtrType() &&
11803         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11804       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11805       return computeResultTy();
11806     }
11807     if (!IsOrdered && LHSType->isNullPtrType() &&
11808         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11809       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11810       return computeResultTy();
11811     }
11812 
11813     if (IsRelational &&
11814         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11815          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11816       // HACK: Relational comparison of nullptr_t against a pointer type is
11817       // invalid per DR583, but we allow it within std::less<> and friends,
11818       // since otherwise common uses of it break.
11819       // FIXME: Consider removing this hack once LWG fixes std::less<> and
11820       // friends to have std::nullptr_t overload candidates.
11821       DeclContext *DC = CurContext;
11822       if (isa<FunctionDecl>(DC))
11823         DC = DC->getParent();
11824       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11825         if (CTSD->isInStdNamespace() &&
11826             llvm::StringSwitch<bool>(CTSD->getName())
11827                 .Cases("less", "less_equal", "greater", "greater_equal", true)
11828                 .Default(false)) {
11829           if (RHSType->isNullPtrType())
11830             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11831           else
11832             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11833           return computeResultTy();
11834         }
11835       }
11836     }
11837 
11838     // C++ [expr.eq]p2:
11839     //   If at least one operand is a pointer to member, [...] bring them to
11840     //   their composite pointer type.
11841     if (!IsOrdered &&
11842         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11843       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11844         return QualType();
11845       else
11846         return computeResultTy();
11847     }
11848   }
11849 
11850   // Handle block pointer types.
11851   if (!IsOrdered && LHSType->isBlockPointerType() &&
11852       RHSType->isBlockPointerType()) {
11853     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11854     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11855 
11856     if (!LHSIsNull && !RHSIsNull &&
11857         !Context.typesAreCompatible(lpointee, rpointee)) {
11858       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11859         << LHSType << RHSType << LHS.get()->getSourceRange()
11860         << RHS.get()->getSourceRange();
11861     }
11862     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11863     return computeResultTy();
11864   }
11865 
11866   // Allow block pointers to be compared with null pointer constants.
11867   if (!IsOrdered
11868       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11869           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11870     if (!LHSIsNull && !RHSIsNull) {
11871       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11872              ->getPointeeType()->isVoidType())
11873             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11874                 ->getPointeeType()->isVoidType())))
11875         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11876           << LHSType << RHSType << LHS.get()->getSourceRange()
11877           << RHS.get()->getSourceRange();
11878     }
11879     if (LHSIsNull && !RHSIsNull)
11880       LHS = ImpCastExprToType(LHS.get(), RHSType,
11881                               RHSType->isPointerType() ? CK_BitCast
11882                                 : CK_AnyPointerToBlockPointerCast);
11883     else
11884       RHS = ImpCastExprToType(RHS.get(), LHSType,
11885                               LHSType->isPointerType() ? CK_BitCast
11886                                 : CK_AnyPointerToBlockPointerCast);
11887     return computeResultTy();
11888   }
11889 
11890   if (LHSType->isObjCObjectPointerType() ||
11891       RHSType->isObjCObjectPointerType()) {
11892     const PointerType *LPT = LHSType->getAs<PointerType>();
11893     const PointerType *RPT = RHSType->getAs<PointerType>();
11894     if (LPT || RPT) {
11895       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11896       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11897 
11898       if (!LPtrToVoid && !RPtrToVoid &&
11899           !Context.typesAreCompatible(LHSType, RHSType)) {
11900         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11901                                           /*isError*/false);
11902       }
11903       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11904       // the RHS, but we have test coverage for this behavior.
11905       // FIXME: Consider using convertPointersToCompositeType in C++.
11906       if (LHSIsNull && !RHSIsNull) {
11907         Expr *E = LHS.get();
11908         if (getLangOpts().ObjCAutoRefCount)
11909           CheckObjCConversion(SourceRange(), RHSType, E,
11910                               CCK_ImplicitConversion);
11911         LHS = ImpCastExprToType(E, RHSType,
11912                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11913       }
11914       else {
11915         Expr *E = RHS.get();
11916         if (getLangOpts().ObjCAutoRefCount)
11917           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11918                               /*Diagnose=*/true,
11919                               /*DiagnoseCFAudited=*/false, Opc);
11920         RHS = ImpCastExprToType(E, LHSType,
11921                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11922       }
11923       return computeResultTy();
11924     }
11925     if (LHSType->isObjCObjectPointerType() &&
11926         RHSType->isObjCObjectPointerType()) {
11927       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11928         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11929                                           /*isError*/false);
11930       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11931         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11932 
11933       if (LHSIsNull && !RHSIsNull)
11934         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11935       else
11936         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11937       return computeResultTy();
11938     }
11939 
11940     if (!IsOrdered && LHSType->isBlockPointerType() &&
11941         RHSType->isBlockCompatibleObjCPointerType(Context)) {
11942       LHS = ImpCastExprToType(LHS.get(), RHSType,
11943                               CK_BlockPointerToObjCPointerCast);
11944       return computeResultTy();
11945     } else if (!IsOrdered &&
11946                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11947                RHSType->isBlockPointerType()) {
11948       RHS = ImpCastExprToType(RHS.get(), LHSType,
11949                               CK_BlockPointerToObjCPointerCast);
11950       return computeResultTy();
11951     }
11952   }
11953   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11954       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11955     unsigned DiagID = 0;
11956     bool isError = false;
11957     if (LangOpts.DebuggerSupport) {
11958       // Under a debugger, allow the comparison of pointers to integers,
11959       // since users tend to want to compare addresses.
11960     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11961                (RHSIsNull && RHSType->isIntegerType())) {
11962       if (IsOrdered) {
11963         isError = getLangOpts().CPlusPlus;
11964         DiagID =
11965           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11966                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11967       }
11968     } else if (getLangOpts().CPlusPlus) {
11969       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11970       isError = true;
11971     } else if (IsOrdered)
11972       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11973     else
11974       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11975 
11976     if (DiagID) {
11977       Diag(Loc, DiagID)
11978         << LHSType << RHSType << LHS.get()->getSourceRange()
11979         << RHS.get()->getSourceRange();
11980       if (isError)
11981         return QualType();
11982     }
11983 
11984     if (LHSType->isIntegerType())
11985       LHS = ImpCastExprToType(LHS.get(), RHSType,
11986                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11987     else
11988       RHS = ImpCastExprToType(RHS.get(), LHSType,
11989                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11990     return computeResultTy();
11991   }
11992 
11993   // Handle block pointers.
11994   if (!IsOrdered && RHSIsNull
11995       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11996     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11997     return computeResultTy();
11998   }
11999   if (!IsOrdered && LHSIsNull
12000       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12001     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12002     return computeResultTy();
12003   }
12004 
12005   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12006     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12007       return computeResultTy();
12008     }
12009 
12010     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12011       return computeResultTy();
12012     }
12013 
12014     if (LHSIsNull && RHSType->isQueueT()) {
12015       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12016       return computeResultTy();
12017     }
12018 
12019     if (LHSType->isQueueT() && RHSIsNull) {
12020       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12021       return computeResultTy();
12022     }
12023   }
12024 
12025   return InvalidOperands(Loc, LHS, RHS);
12026 }
12027 
12028 // Return a signed ext_vector_type that is of identical size and number of
12029 // elements. For floating point vectors, return an integer type of identical
12030 // size and number of elements. In the non ext_vector_type case, search from
12031 // the largest type to the smallest type to avoid cases where long long == long,
12032 // where long gets picked over long long.
GetSignedVectorType(QualType V)12033 QualType Sema::GetSignedVectorType(QualType V) {
12034   const VectorType *VTy = V->castAs<VectorType>();
12035   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12036 
12037   if (isa<ExtVectorType>(VTy)) {
12038     if (TypeSize == Context.getTypeSize(Context.CharTy))
12039       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12040     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12041       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12042     else if (TypeSize == Context.getTypeSize(Context.IntTy))
12043       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12044     else if (TypeSize == Context.getTypeSize(Context.LongTy))
12045       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12046     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12047            "Unhandled vector element size in vector compare");
12048     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12049   }
12050 
12051   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12052     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12053                                  VectorType::GenericVector);
12054   else if (TypeSize == Context.getTypeSize(Context.LongTy))
12055     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12056                                  VectorType::GenericVector);
12057   else if (TypeSize == Context.getTypeSize(Context.IntTy))
12058     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12059                                  VectorType::GenericVector);
12060   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12061     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12062                                  VectorType::GenericVector);
12063   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12064          "Unhandled vector element size in vector compare");
12065   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12066                                VectorType::GenericVector);
12067 }
12068 
12069 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12070 /// operates on extended vector types.  Instead of producing an IntTy result,
12071 /// like a scalar comparison, a vector comparison produces a vector of integer
12072 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12073 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12074                                           SourceLocation Loc,
12075                                           BinaryOperatorKind Opc) {
12076   if (Opc == BO_Cmp) {
12077     Diag(Loc, diag::err_three_way_vector_comparison);
12078     return QualType();
12079   }
12080 
12081   // Check to make sure we're operating on vectors of the same type and width,
12082   // Allowing one side to be a scalar of element type.
12083   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12084                               /*AllowBothBool*/true,
12085                               /*AllowBoolConversions*/getLangOpts().ZVector);
12086   if (vType.isNull())
12087     return vType;
12088 
12089   QualType LHSType = LHS.get()->getType();
12090 
12091   // If AltiVec, the comparison results in a numeric type, i.e.
12092   // bool for C++, int for C
12093   if (getLangOpts().AltiVec &&
12094       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12095     return Context.getLogicalOperationType();
12096 
12097   // For non-floating point types, check for self-comparisons of the form
12098   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12099   // often indicate logic errors in the program.
12100   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12101 
12102   // Check for comparisons of floating point operands using != and ==.
12103   if (BinaryOperator::isEqualityOp(Opc) &&
12104       LHSType->hasFloatingRepresentation()) {
12105     assert(RHS.get()->getType()->hasFloatingRepresentation());
12106     CheckFloatComparison(Loc, LHS.get(), RHS.get());
12107   }
12108 
12109   // Return a signed type for the vector.
12110   return GetSignedVectorType(vType);
12111 }
12112 
diagnoseXorMisusedAsPow(Sema & S,const ExprResult & XorLHS,const ExprResult & XorRHS,const SourceLocation Loc)12113 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12114                                     const ExprResult &XorRHS,
12115                                     const SourceLocation Loc) {
12116   // Do not diagnose macros.
12117   if (Loc.isMacroID())
12118     return;
12119 
12120   bool Negative = false;
12121   bool ExplicitPlus = false;
12122   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12123   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12124 
12125   if (!LHSInt)
12126     return;
12127   if (!RHSInt) {
12128     // Check negative literals.
12129     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12130       UnaryOperatorKind Opc = UO->getOpcode();
12131       if (Opc != UO_Minus && Opc != UO_Plus)
12132         return;
12133       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12134       if (!RHSInt)
12135         return;
12136       Negative = (Opc == UO_Minus);
12137       ExplicitPlus = !Negative;
12138     } else {
12139       return;
12140     }
12141   }
12142 
12143   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12144   llvm::APInt RightSideValue = RHSInt->getValue();
12145   if (LeftSideValue != 2 && LeftSideValue != 10)
12146     return;
12147 
12148   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12149     return;
12150 
12151   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12152       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12153   llvm::StringRef ExprStr =
12154       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12155 
12156   CharSourceRange XorRange =
12157       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12158   llvm::StringRef XorStr =
12159       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12160   // Do not diagnose if xor keyword/macro is used.
12161   if (XorStr == "xor")
12162     return;
12163 
12164   std::string LHSStr = std::string(Lexer::getSourceText(
12165       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12166       S.getSourceManager(), S.getLangOpts()));
12167   std::string RHSStr = std::string(Lexer::getSourceText(
12168       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12169       S.getSourceManager(), S.getLangOpts()));
12170 
12171   if (Negative) {
12172     RightSideValue = -RightSideValue;
12173     RHSStr = "-" + RHSStr;
12174   } else if (ExplicitPlus) {
12175     RHSStr = "+" + RHSStr;
12176   }
12177 
12178   StringRef LHSStrRef = LHSStr;
12179   StringRef RHSStrRef = RHSStr;
12180   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12181   // literals.
12182   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12183       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12184       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12185       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12186       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12187       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12188       LHSStrRef.find('\'') != StringRef::npos ||
12189       RHSStrRef.find('\'') != StringRef::npos)
12190     return;
12191 
12192   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12193   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12194   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12195   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12196     std::string SuggestedExpr = "1 << " + RHSStr;
12197     bool Overflow = false;
12198     llvm::APInt One = (LeftSideValue - 1);
12199     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12200     if (Overflow) {
12201       if (RightSideIntValue < 64)
12202         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12203             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12204             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12205       else if (RightSideIntValue == 64)
12206         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12207       else
12208         return;
12209     } else {
12210       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12211           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12212           << PowValue.toString(10, true)
12213           << FixItHint::CreateReplacement(
12214                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12215     }
12216 
12217     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12218   } else if (LeftSideValue == 10) {
12219     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12220     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12221         << ExprStr << XorValue.toString(10, true) << SuggestedValue
12222         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12223     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12224   }
12225 }
12226 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)12227 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12228                                           SourceLocation Loc) {
12229   // Ensure that either both operands are of the same vector type, or
12230   // one operand is of a vector type and the other is of its element type.
12231   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12232                                        /*AllowBothBool*/true,
12233                                        /*AllowBoolConversions*/false);
12234   if (vType.isNull())
12235     return InvalidOperands(Loc, LHS, RHS);
12236   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12237       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12238     return InvalidOperands(Loc, LHS, RHS);
12239   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12240   //        usage of the logical operators && and || with vectors in C. This
12241   //        check could be notionally dropped.
12242   if (!getLangOpts().CPlusPlus &&
12243       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12244     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12245 
12246   return GetSignedVectorType(LHS.get()->getType());
12247 }
12248 
CheckMatrixElementwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12249 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12250                                               SourceLocation Loc,
12251                                               bool IsCompAssign) {
12252   if (!IsCompAssign) {
12253     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12254     if (LHS.isInvalid())
12255       return QualType();
12256   }
12257   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12258   if (RHS.isInvalid())
12259     return QualType();
12260 
12261   // For conversion purposes, we ignore any qualifiers.
12262   // For example, "const float" and "float" are equivalent.
12263   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12264   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12265 
12266   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12267   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12268   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12269 
12270   if (Context.hasSameType(LHSType, RHSType))
12271     return LHSType;
12272 
12273   // Type conversion may change LHS/RHS. Keep copies to the original results, in
12274   // case we have to return InvalidOperands.
12275   ExprResult OriginalLHS = LHS;
12276   ExprResult OriginalRHS = RHS;
12277   if (LHSMatType && !RHSMatType) {
12278     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12279     if (!RHS.isInvalid())
12280       return LHSType;
12281 
12282     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12283   }
12284 
12285   if (!LHSMatType && RHSMatType) {
12286     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12287     if (!LHS.isInvalid())
12288       return RHSType;
12289     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12290   }
12291 
12292   return InvalidOperands(Loc, LHS, RHS);
12293 }
12294 
CheckMatrixMultiplyOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12295 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12296                                            SourceLocation Loc,
12297                                            bool IsCompAssign) {
12298   if (!IsCompAssign) {
12299     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12300     if (LHS.isInvalid())
12301       return QualType();
12302   }
12303   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12304   if (RHS.isInvalid())
12305     return QualType();
12306 
12307   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12308   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12309   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12310 
12311   if (LHSMatType && RHSMatType) {
12312     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12313       return InvalidOperands(Loc, LHS, RHS);
12314 
12315     if (!Context.hasSameType(LHSMatType->getElementType(),
12316                              RHSMatType->getElementType()))
12317       return InvalidOperands(Loc, LHS, RHS);
12318 
12319     return Context.getConstantMatrixType(LHSMatType->getElementType(),
12320                                          LHSMatType->getNumRows(),
12321                                          RHSMatType->getNumColumns());
12322   }
12323   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12324 }
12325 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12326 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12327                                            SourceLocation Loc,
12328                                            BinaryOperatorKind Opc) {
12329   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12330 
12331   bool IsCompAssign =
12332       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12333 
12334   if (LHS.get()->getType()->isVectorType() ||
12335       RHS.get()->getType()->isVectorType()) {
12336     if (LHS.get()->getType()->hasIntegerRepresentation() &&
12337         RHS.get()->getType()->hasIntegerRepresentation())
12338       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12339                         /*AllowBothBool*/true,
12340                         /*AllowBoolConversions*/getLangOpts().ZVector);
12341     return InvalidOperands(Loc, LHS, RHS);
12342   }
12343 
12344   if (Opc == BO_And)
12345     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12346 
12347   if (LHS.get()->getType()->hasFloatingRepresentation() ||
12348       RHS.get()->getType()->hasFloatingRepresentation())
12349     return InvalidOperands(Loc, LHS, RHS);
12350 
12351   ExprResult LHSResult = LHS, RHSResult = RHS;
12352   QualType compType = UsualArithmeticConversions(
12353       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12354   if (LHSResult.isInvalid() || RHSResult.isInvalid())
12355     return QualType();
12356   LHS = LHSResult.get();
12357   RHS = RHSResult.get();
12358 
12359   if (Opc == BO_Xor)
12360     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12361 
12362   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) {
12363     const bool UsingUIntCapOffset = getLangOpts().cheriUIntCapUsesOffset();
12364     diagnoseAmbiguousProvenance(*this, LHS, RHS, Loc, IsCompAssign);
12365     const bool isLHSCap = LHS.get()->getType()->isCHERICapabilityType(Context);
12366     if (isLHSCap && (Opc == BO_And || Opc == BO_AndAssign)) {
12367       // Bitwise and can cause checking low pointer bits to be compiled to
12368       // and always false condition (see CTSRD-CHERI/clang#189) unless we
12369       // have CheriDataDependentProvenance enabled. It also gives surprising
12370       // behaviour if we are compiling in uintcap=offset mode so warn if either
12371       // of these conditions are met.
12372       //
12373       // This is purely an efficiency problem in address mode, since we have
12374       // changed the definition of capability to no longer include the tag bit.
12375       // However, it is a problem even in address mode when using exact equals
12376       // and are not using data-dependent provenance.
12377       if (UsingUIntCapOffset || (getLangOpts().CheriCompareExact &&
12378                                  !getLangOpts().CheriDataDependentProvenance)) {
12379         DiagRuntimeBehavior(Loc, RHS.get(),
12380                             PDiag(diag::warn_uintcap_bitwise_and)
12381                                 << LHS.get()->getSourceRange()
12382                                 << RHS.get()->getSourceRange());
12383       }
12384     } else if (UsingUIntCapOffset && isLHSCap &&
12385                (Opc == BO_Xor || Opc == BO_XorAssign)) {
12386       // XOR is highly dubious when in offset mode (except when using on plain
12387       // integer values, but then the user should be using size_t/vaddr_t and
12388       // not uintcap_t. Don't warn in address mode since that works just fine
12389       // (only slightly less efficiently)
12390       // FIXME: should warn in address mode (but as a pedantic warning)
12391       DiagRuntimeBehavior(Loc, RHS.get(),
12392                           PDiag(diag::warn_uintcap_bad_bitwise_op)
12393                               << 0 /*=xor*/ << 0 /* usecase is hashing */
12394                               << LHS.get()->getSourceRange()
12395                               << RHS.get()->getSourceRange());
12396     }
12397     return compType;
12398   }
12399   return InvalidOperands(Loc, LHS, RHS);
12400 }
12401 
12402 // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12403 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12404                                            SourceLocation Loc,
12405                                            BinaryOperatorKind Opc) {
12406   // Check vector operands differently.
12407   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12408     return CheckVectorLogicalOperands(LHS, RHS, Loc);
12409 
12410   bool EnumConstantInBoolContext = false;
12411   for (const ExprResult &HS : {LHS, RHS}) {
12412     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12413       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12414       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12415         EnumConstantInBoolContext = true;
12416     }
12417   }
12418 
12419   if (EnumConstantInBoolContext)
12420     Diag(Loc, diag::warn_enum_constant_in_bool_context);
12421 
12422   // Diagnose cases where the user write a logical and/or but probably meant a
12423   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
12424   // is a constant.
12425   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12426       !LHS.get()->getType()->isBooleanType() &&
12427       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12428       // Don't warn in macros or template instantiations.
12429       !Loc.isMacroID() && !inTemplateInstantiation()) {
12430     // If the RHS can be constant folded, and if it constant folds to something
12431     // that isn't 0 or 1 (which indicate a potential logical operation that
12432     // happened to fold to true/false) then warn.
12433     // Parens on the RHS are ignored.
12434     Expr::EvalResult EVResult;
12435     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12436       llvm::APSInt Result = EVResult.Val.getInt();
12437       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12438            !RHS.get()->getExprLoc().isMacroID()) ||
12439           (Result != 0 && Result != 1)) {
12440         Diag(Loc, diag::warn_logical_instead_of_bitwise)
12441           << RHS.get()->getSourceRange()
12442           << (Opc == BO_LAnd ? "&&" : "||");
12443         // Suggest replacing the logical operator with the bitwise version
12444         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12445             << (Opc == BO_LAnd ? "&" : "|")
12446             << FixItHint::CreateReplacement(SourceRange(
12447                                                  Loc, getLocForEndOfToken(Loc)),
12448                                             Opc == BO_LAnd ? "&" : "|");
12449         if (Opc == BO_LAnd)
12450           // Suggest replacing "Foo() && kNonZero" with "Foo()"
12451           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12452               << FixItHint::CreateRemoval(
12453                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12454                                  RHS.get()->getEndLoc()));
12455       }
12456     }
12457   }
12458 
12459   if (!Context.getLangOpts().CPlusPlus) {
12460     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12461     // not operate on the built-in scalar and vector float types.
12462     if (Context.getLangOpts().OpenCL &&
12463         Context.getLangOpts().OpenCLVersion < 120) {
12464       if (LHS.get()->getType()->isFloatingType() ||
12465           RHS.get()->getType()->isFloatingType())
12466         return InvalidOperands(Loc, LHS, RHS);
12467     }
12468 
12469     LHS = UsualUnaryConversions(LHS.get());
12470     if (LHS.isInvalid())
12471       return QualType();
12472 
12473     RHS = UsualUnaryConversions(RHS.get());
12474     if (RHS.isInvalid())
12475       return QualType();
12476 
12477     if (!LHS.get()->getType()->isScalarType() ||
12478         !RHS.get()->getType()->isScalarType())
12479       return InvalidOperands(Loc, LHS, RHS);
12480 
12481     return Context.IntTy;
12482   }
12483 
12484   // The following is safe because we only use this method for
12485   // non-overloadable operands.
12486 
12487   // C++ [expr.log.and]p1
12488   // C++ [expr.log.or]p1
12489   // The operands are both contextually converted to type bool.
12490   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12491   if (LHSRes.isInvalid())
12492     return InvalidOperands(Loc, LHS, RHS);
12493   LHS = LHSRes;
12494 
12495   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12496   if (RHSRes.isInvalid())
12497     return InvalidOperands(Loc, LHS, RHS);
12498   RHS = RHSRes;
12499 
12500   // C++ [expr.log.and]p2
12501   // C++ [expr.log.or]p2
12502   // The result is a bool.
12503   return Context.BoolTy;
12504 }
12505 
IsReadonlyMessage(Expr * E,Sema & S)12506 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12507   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12508   if (!ME) return false;
12509   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12510   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12511       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12512   if (!Base) return false;
12513   return Base->getMethodDecl() != nullptr;
12514 }
12515 
12516 /// Is the given expression (which must be 'const') a reference to a
12517 /// variable which was originally non-const, but which has become
12518 /// 'const' due to being captured within a block?
12519 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)12520 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12521   assert(E->isLValue() && E->getType().isConstQualified());
12522   E = E->IgnoreParens();
12523 
12524   // Must be a reference to a declaration from an enclosing scope.
12525   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12526   if (!DRE) return NCCK_None;
12527   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12528 
12529   // The declaration must be a variable which is not declared 'const'.
12530   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12531   if (!var) return NCCK_None;
12532   if (var->getType().isConstQualified()) return NCCK_None;
12533   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12534 
12535   // Decide whether the first capture was for a block or a lambda.
12536   DeclContext *DC = S.CurContext, *Prev = nullptr;
12537   // Decide whether the first capture was for a block or a lambda.
12538   while (DC) {
12539     // For init-capture, it is possible that the variable belongs to the
12540     // template pattern of the current context.
12541     if (auto *FD = dyn_cast<FunctionDecl>(DC))
12542       if (var->isInitCapture() &&
12543           FD->getTemplateInstantiationPattern() == var->getDeclContext())
12544         break;
12545     if (DC == var->getDeclContext())
12546       break;
12547     Prev = DC;
12548     DC = DC->getParent();
12549   }
12550   // Unless we have an init-capture, we've gone one step too far.
12551   if (!var->isInitCapture())
12552     DC = Prev;
12553   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12554 }
12555 
IsTypeModifiable(QualType Ty,bool IsDereference)12556 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12557   Ty = Ty.getNonReferenceType();
12558   if (IsDereference && Ty->isPointerType())
12559     Ty = Ty->getPointeeType();
12560   return !Ty.isConstQualified();
12561 }
12562 
12563 // Update err_typecheck_assign_const and note_typecheck_assign_const
12564 // when this enum is changed.
12565 enum {
12566   ConstFunction,
12567   ConstVariable,
12568   ConstMember,
12569   ConstMethod,
12570   NestedConstMember,
12571   ConstUnknown,  // Keep as last element
12572 };
12573 
12574 /// Emit the "read-only variable not assignable" error and print notes to give
12575 /// more information about why the variable is not assignable, such as pointing
12576 /// to the declaration of a const variable, showing that a method is const, or
12577 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)12578 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12579                                     SourceLocation Loc) {
12580   SourceRange ExprRange = E->getSourceRange();
12581 
12582   // Only emit one error on the first const found.  All other consts will emit
12583   // a note to the error.
12584   bool DiagnosticEmitted = false;
12585 
12586   // Track if the current expression is the result of a dereference, and if the
12587   // next checked expression is the result of a dereference.
12588   bool IsDereference = false;
12589   bool NextIsDereference = false;
12590 
12591   // Loop to process MemberExpr chains.
12592   while (true) {
12593     IsDereference = NextIsDereference;
12594 
12595     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12596     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12597       NextIsDereference = ME->isArrow();
12598       const ValueDecl *VD = ME->getMemberDecl();
12599       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12600         // Mutable fields can be modified even if the class is const.
12601         if (Field->isMutable()) {
12602           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12603           break;
12604         }
12605 
12606         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12607           if (!DiagnosticEmitted) {
12608             S.Diag(Loc, diag::err_typecheck_assign_const)
12609                 << ExprRange << ConstMember << false /*static*/ << Field
12610                 << Field->getType();
12611             DiagnosticEmitted = true;
12612           }
12613           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12614               << ConstMember << false /*static*/ << Field << Field->getType()
12615               << Field->getSourceRange();
12616         }
12617         E = ME->getBase();
12618         continue;
12619       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12620         if (VDecl->getType().isConstQualified()) {
12621           if (!DiagnosticEmitted) {
12622             S.Diag(Loc, diag::err_typecheck_assign_const)
12623                 << ExprRange << ConstMember << true /*static*/ << VDecl
12624                 << VDecl->getType();
12625             DiagnosticEmitted = true;
12626           }
12627           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12628               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12629               << VDecl->getSourceRange();
12630         }
12631         // Static fields do not inherit constness from parents.
12632         break;
12633       }
12634       break; // End MemberExpr
12635     } else if (const ArraySubscriptExpr *ASE =
12636                    dyn_cast<ArraySubscriptExpr>(E)) {
12637       E = ASE->getBase()->IgnoreParenImpCasts();
12638       continue;
12639     } else if (const ExtVectorElementExpr *EVE =
12640                    dyn_cast<ExtVectorElementExpr>(E)) {
12641       E = EVE->getBase()->IgnoreParenImpCasts();
12642       continue;
12643     }
12644     break;
12645   }
12646 
12647   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12648     // Function calls
12649     const FunctionDecl *FD = CE->getDirectCallee();
12650     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12651       if (!DiagnosticEmitted) {
12652         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12653                                                       << ConstFunction << FD;
12654         DiagnosticEmitted = true;
12655       }
12656       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12657              diag::note_typecheck_assign_const)
12658           << ConstFunction << FD << FD->getReturnType()
12659           << FD->getReturnTypeSourceRange();
12660     }
12661   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12662     // Point to variable declaration.
12663     if (const ValueDecl *VD = DRE->getDecl()) {
12664       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12665         if (!DiagnosticEmitted) {
12666           S.Diag(Loc, diag::err_typecheck_assign_const)
12667               << ExprRange << ConstVariable << VD << VD->getType();
12668           DiagnosticEmitted = true;
12669         }
12670         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12671             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12672       }
12673     }
12674   } else if (isa<CXXThisExpr>(E)) {
12675     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12676       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12677         if (MD->isConst()) {
12678           if (!DiagnosticEmitted) {
12679             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12680                                                           << ConstMethod << MD;
12681             DiagnosticEmitted = true;
12682           }
12683           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12684               << ConstMethod << MD << MD->getSourceRange();
12685         }
12686       }
12687     }
12688   }
12689 
12690   if (DiagnosticEmitted)
12691     return;
12692 
12693   // Can't determine a more specific message, so display the generic error.
12694   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12695 }
12696 
12697 enum OriginalExprKind {
12698   OEK_Variable,
12699   OEK_Member,
12700   OEK_LValue
12701 };
12702 
DiagnoseRecursiveConstFields(Sema & S,const ValueDecl * VD,const RecordType * Ty,SourceLocation Loc,SourceRange Range,OriginalExprKind OEK,bool & DiagnosticEmitted)12703 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12704                                          const RecordType *Ty,
12705                                          SourceLocation Loc, SourceRange Range,
12706                                          OriginalExprKind OEK,
12707                                          bool &DiagnosticEmitted) {
12708   std::vector<const RecordType *> RecordTypeList;
12709   RecordTypeList.push_back(Ty);
12710   unsigned NextToCheckIndex = 0;
12711   // We walk the record hierarchy breadth-first to ensure that we print
12712   // diagnostics in field nesting order.
12713   while (RecordTypeList.size() > NextToCheckIndex) {
12714     bool IsNested = NextToCheckIndex > 0;
12715     for (const FieldDecl *Field :
12716          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12717       // First, check every field for constness.
12718       QualType FieldTy = Field->getType();
12719       if (FieldTy.isConstQualified()) {
12720         if (!DiagnosticEmitted) {
12721           S.Diag(Loc, diag::err_typecheck_assign_const)
12722               << Range << NestedConstMember << OEK << VD
12723               << IsNested << Field;
12724           DiagnosticEmitted = true;
12725         }
12726         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12727             << NestedConstMember << IsNested << Field
12728             << FieldTy << Field->getSourceRange();
12729       }
12730 
12731       // Then we append it to the list to check next in order.
12732       FieldTy = FieldTy.getCanonicalType();
12733       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12734         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12735           RecordTypeList.push_back(FieldRecTy);
12736       }
12737     }
12738     ++NextToCheckIndex;
12739   }
12740 }
12741 
12742 /// Emit an error for the case where a record we are trying to assign to has a
12743 /// const-qualified field somewhere in its hierarchy.
DiagnoseRecursiveConstFields(Sema & S,const Expr * E,SourceLocation Loc)12744 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12745                                          SourceLocation Loc) {
12746   QualType Ty = E->getType();
12747   assert(Ty->isRecordType() && "lvalue was not record?");
12748   SourceRange Range = E->getSourceRange();
12749   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12750   bool DiagEmitted = false;
12751 
12752   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12753     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12754             Range, OEK_Member, DiagEmitted);
12755   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12756     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12757             Range, OEK_Variable, DiagEmitted);
12758   else
12759     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12760             Range, OEK_LValue, DiagEmitted);
12761   if (!DiagEmitted)
12762     DiagnoseConstAssignment(S, E, Loc);
12763 }
12764 
12765 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
12766 /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)12767 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12768   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12769 
12770   S.CheckShadowingDeclModification(E, Loc);
12771 
12772   SourceLocation OrigLoc = Loc;
12773   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12774                                                               &Loc);
12775   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12776     IsLV = Expr::MLV_InvalidMessageExpression;
12777   if (IsLV == Expr::MLV_Valid)
12778     return false;
12779 
12780   unsigned DiagID = 0;
12781   bool NeedType = false;
12782   switch (IsLV) { // C99 6.5.16p2
12783   case Expr::MLV_ConstQualified:
12784     // Use a specialized diagnostic when we're assigning to an object
12785     // from an enclosing function or block.
12786     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12787       if (NCCK == NCCK_Block)
12788         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12789       else
12790         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12791       break;
12792     }
12793 
12794     // In ARC, use some specialized diagnostics for occasions where we
12795     // infer 'const'.  These are always pseudo-strong variables.
12796     if (S.getLangOpts().ObjCAutoRefCount) {
12797       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12798       if (declRef && isa<VarDecl>(declRef->getDecl())) {
12799         VarDecl *var = cast<VarDecl>(declRef->getDecl());
12800 
12801         // Use the normal diagnostic if it's pseudo-__strong but the
12802         // user actually wrote 'const'.
12803         if (var->isARCPseudoStrong() &&
12804             (!var->getTypeSourceInfo() ||
12805              !var->getTypeSourceInfo()->getType().isConstQualified())) {
12806           // There are three pseudo-strong cases:
12807           //  - self
12808           ObjCMethodDecl *method = S.getCurMethodDecl();
12809           if (method && var == method->getSelfDecl()) {
12810             DiagID = method->isClassMethod()
12811               ? diag::err_typecheck_arc_assign_self_class_method
12812               : diag::err_typecheck_arc_assign_self;
12813 
12814           //  - Objective-C externally_retained attribute.
12815           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12816                      isa<ParmVarDecl>(var)) {
12817             DiagID = diag::err_typecheck_arc_assign_externally_retained;
12818 
12819           //  - fast enumeration variables
12820           } else {
12821             DiagID = diag::err_typecheck_arr_assign_enumeration;
12822           }
12823 
12824           SourceRange Assign;
12825           if (Loc != OrigLoc)
12826             Assign = SourceRange(OrigLoc, OrigLoc);
12827           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12828           // We need to preserve the AST regardless, so migration tool
12829           // can do its job.
12830           return false;
12831         }
12832       }
12833     }
12834 
12835     // If none of the special cases above are triggered, then this is a
12836     // simple const assignment.
12837     if (DiagID == 0) {
12838       DiagnoseConstAssignment(S, E, Loc);
12839       return true;
12840     }
12841 
12842     break;
12843   case Expr::MLV_ConstAddrSpace:
12844     DiagnoseConstAssignment(S, E, Loc);
12845     return true;
12846   case Expr::MLV_ConstQualifiedField:
12847     DiagnoseRecursiveConstFields(S, E, Loc);
12848     return true;
12849   case Expr::MLV_ArrayType:
12850   case Expr::MLV_ArrayTemporary:
12851     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12852     NeedType = true;
12853     break;
12854   case Expr::MLV_NotObjectType:
12855     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12856     NeedType = true;
12857     break;
12858   case Expr::MLV_LValueCast:
12859     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12860     break;
12861   case Expr::MLV_Valid:
12862     llvm_unreachable("did not take early return for MLV_Valid");
12863   case Expr::MLV_InvalidExpression:
12864   case Expr::MLV_MemberFunction:
12865   case Expr::MLV_ClassTemporary:
12866     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12867     break;
12868   case Expr::MLV_IncompleteType:
12869   case Expr::MLV_IncompleteVoidType:
12870     return S.RequireCompleteType(Loc, E->getType(),
12871              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12872   case Expr::MLV_DuplicateVectorComponents:
12873     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12874     break;
12875   case Expr::MLV_NoSetterProperty:
12876     llvm_unreachable("readonly properties should be processed differently");
12877   case Expr::MLV_InvalidMessageExpression:
12878     DiagID = diag::err_readonly_message_assignment;
12879     break;
12880   case Expr::MLV_SubObjCPropertySetting:
12881     DiagID = diag::err_no_subobject_property_setting;
12882     break;
12883   }
12884 
12885   SourceRange Assign;
12886   if (Loc != OrigLoc)
12887     Assign = SourceRange(OrigLoc, OrigLoc);
12888   if (NeedType)
12889     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12890   else
12891     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12892   return true;
12893 }
12894 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)12895 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12896                                          SourceLocation Loc,
12897                                          Sema &Sema) {
12898   if (Sema.inTemplateInstantiation())
12899     return;
12900   if (Sema.isUnevaluatedContext())
12901     return;
12902   if (Loc.isInvalid() || Loc.isMacroID())
12903     return;
12904   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12905     return;
12906 
12907   // C / C++ fields
12908   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12909   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12910   if (ML && MR) {
12911     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12912       return;
12913     const ValueDecl *LHSDecl =
12914         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12915     const ValueDecl *RHSDecl =
12916         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12917     if (LHSDecl != RHSDecl)
12918       return;
12919     if (LHSDecl->getType().isVolatileQualified())
12920       return;
12921     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12922       if (RefTy->getPointeeType().isVolatileQualified())
12923         return;
12924 
12925     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12926   }
12927 
12928   // Objective-C instance variables
12929   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12930   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12931   if (OL && OR && OL->getDecl() == OR->getDecl()) {
12932     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12933     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12934     if (RL && RR && RL->getDecl() == RR->getDecl())
12935       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12936   }
12937 }
12938 
12939 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)12940 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12941                                        SourceLocation Loc,
12942                                        QualType CompoundType) {
12943   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12944 
12945   // Verify that LHS is a modifiable lvalue, and emit error if not.
12946   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12947     return QualType();
12948 
12949   QualType LHSType = LHSExpr->getType();
12950   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12951                                              CompoundType;
12952   // OpenCL v1.2 s6.1.1.1 p2:
12953   // The half data type can only be used to declare a pointer to a buffer that
12954   // contains half values
12955   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12956     LHSType->isHalfType()) {
12957     Diag(Loc, diag::err_opencl_half_load_store) << 1
12958         << LHSType.getUnqualifiedType();
12959     return QualType();
12960   }
12961 
12962   AssignConvertType ConvTy;
12963   if (CompoundType.isNull()) {
12964     Expr *RHSCheck = RHS.get();
12965 
12966     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12967 
12968     QualType LHSTy(LHSType);
12969     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12970     if (RHS.isInvalid())
12971       return QualType();
12972     // Special case of NSObject attributes on c-style pointer types.
12973     if (ConvTy == IncompatiblePointer &&
12974         ((Context.isObjCNSObjectType(LHSType) &&
12975           RHSType->isObjCObjectPointerType()) ||
12976          (Context.isObjCNSObjectType(RHSType) &&
12977           LHSType->isObjCObjectPointerType())))
12978       ConvTy = Compatible;
12979 
12980     if (ConvTy == Compatible &&
12981         LHSType->isObjCObjectType())
12982         Diag(Loc, diag::err_objc_object_assignment)
12983           << LHSType;
12984 
12985     // If the RHS is a unary plus or minus, check to see if they = and + are
12986     // right next to each other.  If so, the user may have typo'd "x =+ 4"
12987     // instead of "x += 4".
12988     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12989       RHSCheck = ICE->getSubExpr();
12990     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12991       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12992           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12993           // Only if the two operators are exactly adjacent.
12994           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12995           // And there is a space or other character before the subexpr of the
12996           // unary +/-.  We don't want to warn on "x=-1".
12997           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12998           UO->getSubExpr()->getBeginLoc().isFileID()) {
12999         Diag(Loc, diag::warn_not_compound_assign)
13000           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13001           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13002       }
13003     }
13004 
13005     if (ConvTy == Compatible) {
13006       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13007         // Warn about retain cycles where a block captures the LHS, but
13008         // not if the LHS is a simple variable into which the block is
13009         // being stored...unless that variable can be captured by reference!
13010         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13011         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13012         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13013           checkRetainCycles(LHSExpr, RHS.get());
13014       }
13015 
13016       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13017           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13018         // It is safe to assign a weak reference into a strong variable.
13019         // Although this code can still have problems:
13020         //   id x = self.weakProp;
13021         //   id y = self.weakProp;
13022         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13023         // paths through the function. This should be revisited if
13024         // -Wrepeated-use-of-weak is made flow-sensitive.
13025         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13026         // variable, which will be valid for the current autorelease scope.
13027         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13028                              RHS.get()->getBeginLoc()))
13029           getCurFunction()->markSafeWeakUse(RHS.get());
13030 
13031       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13032         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13033       }
13034     }
13035   } else {
13036     // Compound assignment "x += y"
13037     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13038   }
13039 
13040   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13041                                RHS.get(), AA_Assigning))
13042     return QualType();
13043 
13044   CheckForNullPointerDereference(*this, LHSExpr);
13045 
13046   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13047     if (CompoundType.isNull()) {
13048       // C++2a [expr.ass]p5:
13049       //   A simple-assignment whose left operand is of a volatile-qualified
13050       //   type is deprecated unless the assignment is either a discarded-value
13051       //   expression or an unevaluated operand
13052       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13053     } else {
13054       // C++2a [expr.ass]p6:
13055       //   [Compound-assignment] expressions are deprecated if E1 has
13056       //   volatile-qualified type
13057       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13058     }
13059   }
13060 
13061   // C99 6.5.16p3: The type of an assignment expression is the type of the
13062   // left operand unless the left operand has qualified type, in which case
13063   // it is the unqualified version of the type of the left operand.
13064   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13065   // is converted to the type of the assignment expression (above).
13066   // C++ 5.17p1: the type of the assignment expression is that of its left
13067   // operand.
13068   return (getLangOpts().CPlusPlus
13069           ? LHSType : LHSType.getUnqualifiedType());
13070 }
13071 
13072 // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)13073 static bool IgnoreCommaOperand(const Expr *E) {
13074   E = E->IgnoreParens();
13075 
13076   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13077     if (CE->getCastKind() == CK_ToVoid) {
13078       return true;
13079     }
13080 
13081     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13082     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13083         CE->getSubExpr()->getType()->isDependentType()) {
13084       return true;
13085     }
13086   }
13087 
13088   return false;
13089 }
13090 
13091 // Look for instances where it is likely the comma operator is confused with
13092 // another operator.  There is an explicit list of acceptable expressions for
13093 // the left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)13094 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13095   // No warnings in macros
13096   if (Loc.isMacroID())
13097     return;
13098 
13099   // Don't warn in template instantiations.
13100   if (inTemplateInstantiation())
13101     return;
13102 
13103   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13104   // instead, skip more than needed, then call back into here with the
13105   // CommaVisitor in SemaStmt.cpp.
13106   // The listed locations are the initialization and increment portions
13107   // of a for loop.  The additional checks are on the condition of
13108   // if statements, do/while loops, and for loops.
13109   // Differences in scope flags for C89 mode requires the extra logic.
13110   const unsigned ForIncrementFlags =
13111       getLangOpts().C99 || getLangOpts().CPlusPlus
13112           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13113           : Scope::ContinueScope | Scope::BreakScope;
13114   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13115   const unsigned ScopeFlags = getCurScope()->getFlags();
13116   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13117       (ScopeFlags & ForInitFlags) == ForInitFlags)
13118     return;
13119 
13120   // If there are multiple comma operators used together, get the RHS of the
13121   // of the comma operator as the LHS.
13122   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13123     if (BO->getOpcode() != BO_Comma)
13124       break;
13125     LHS = BO->getRHS();
13126   }
13127 
13128   // Only allow some expressions on LHS to not warn.
13129   if (IgnoreCommaOperand(LHS))
13130     return;
13131 
13132   Diag(Loc, diag::warn_comma_operator);
13133   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13134       << LHS->getSourceRange()
13135       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13136                                     LangOpts.CPlusPlus ? "static_cast<void>("
13137                                                        : "(void)(")
13138       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13139                                     ")");
13140 }
13141 
13142 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)13143 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13144                                    SourceLocation Loc) {
13145   LHS = S.CheckPlaceholderExpr(LHS.get());
13146   RHS = S.CheckPlaceholderExpr(RHS.get());
13147   if (LHS.isInvalid() || RHS.isInvalid())
13148     return QualType();
13149 
13150   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13151   // operands, but not unary promotions.
13152   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13153 
13154   // So we treat the LHS as a ignored value, and in C++ we allow the
13155   // containing site to determine what should be done with the RHS.
13156   LHS = S.IgnoredValueConversions(LHS.get());
13157   if (LHS.isInvalid())
13158     return QualType();
13159 
13160   S.DiagnoseUnusedExprResult(LHS.get());
13161 
13162   if (!S.getLangOpts().CPlusPlus) {
13163     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13164     if (RHS.isInvalid())
13165       return QualType();
13166     if (!RHS.get()->getType()->isVoidType())
13167       S.RequireCompleteType(Loc, RHS.get()->getType(),
13168                             diag::err_incomplete_type);
13169   }
13170 
13171   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13172     S.DiagnoseCommaOperator(LHS.get(), Loc);
13173 
13174   return RHS.get()->getType();
13175 }
13176 
13177 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13178 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)13179 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13180                                                ExprValueKind &VK,
13181                                                ExprObjectKind &OK,
13182                                                SourceLocation OpLoc,
13183                                                bool IsInc, bool IsPrefix) {
13184   if (Op->isTypeDependent())
13185     return S.Context.DependentTy;
13186 
13187   QualType ResType = Op->getType();
13188   // Atomic types can be used for increment / decrement where the non-atomic
13189   // versions can, so ignore the _Atomic() specifier for the purpose of
13190   // checking.
13191   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13192     ResType = ResAtomicType->getValueType();
13193 
13194   assert(!ResType.isNull() && "no type for increment/decrement expression");
13195 
13196   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13197     // Decrement of bool is not allowed.
13198     if (!IsInc) {
13199       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13200       return QualType();
13201     }
13202     // Increment of bool sets it to true, but is deprecated.
13203     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13204                                               : diag::warn_increment_bool)
13205       << Op->getSourceRange();
13206   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13207     // Error on enum increments and decrements in C++ mode
13208     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13209     return QualType();
13210   } else if (ResType->isRealType()) {
13211     // OK!
13212   } else if (ResType->isPointerType()) {
13213     // C99 6.5.2.4p2, 6.5.6p2
13214     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13215       return QualType();
13216   } else if (ResType->isObjCObjectPointerType()) {
13217     // On modern runtimes, ObjC pointer arithmetic is forbidden.
13218     // Otherwise, we just need a complete type.
13219     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13220         checkArithmeticOnObjCPointer(S, OpLoc, Op))
13221       return QualType();
13222   } else if (ResType->isAnyComplexType()) {
13223     // C99 does not support ++/-- on complex types, we allow as an extension.
13224     S.Diag(OpLoc, diag::ext_integer_increment_complex)
13225       << ResType << Op->getSourceRange();
13226   } else if (ResType->isPlaceholderType()) {
13227     ExprResult PR = S.CheckPlaceholderExpr(Op);
13228     if (PR.isInvalid()) return QualType();
13229     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13230                                           IsInc, IsPrefix);
13231   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13232     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13233   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13234              (ResType->castAs<VectorType>()->getVectorKind() !=
13235               VectorType::AltiVecBool)) {
13236     // The z vector extensions allow ++ and -- for non-bool vectors.
13237   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13238             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13239     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13240   } else {
13241     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13242       << ResType << int(IsInc) << Op->getSourceRange();
13243     return QualType();
13244   }
13245   // At this point, we know we have a real, complex or pointer type.
13246   // Now make sure the operand is a modifiable lvalue.
13247   if (CheckForModifiableLvalue(Op, OpLoc, S))
13248     return QualType();
13249   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13250     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13251     //   An operand with volatile-qualified type is deprecated
13252     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13253         << IsInc << ResType;
13254   }
13255   // In C++, a prefix increment is the same type as the operand. Otherwise
13256   // (in C or with postfix), the increment is the unqualified type of the
13257   // operand.
13258   if (IsPrefix && S.getLangOpts().CPlusPlus) {
13259     VK = VK_LValue;
13260     OK = Op->getObjectKind();
13261     return ResType;
13262   } else {
13263     VK = VK_RValue;
13264     return ResType.getUnqualifiedType();
13265   }
13266 }
13267 
13268 
13269 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13270 /// This routine allows us to typecheck complex/recursive expressions
13271 /// where the declaration is needed for type checking. We only need to
13272 /// handle cases when the expression references a function designator
13273 /// or is an lvalue. Here are some examples:
13274 ///  - &(x) => x
13275 ///  - &*****f => f for f a function designator.
13276 ///  - &s.xx => s
13277 ///  - &s.zz[1].yy -> s, if zz is an array
13278 ///  - *(x + 1) -> x, if x is an array
13279 ///  - &"123"[2] -> 0
13280 ///  - & __real__ x -> x
13281 ///
13282 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13283 /// members.
getPrimaryDecl(Expr * E)13284 static ValueDecl *getPrimaryDecl(Expr *E) {
13285   switch (E->getStmtClass()) {
13286   case Stmt::DeclRefExprClass:
13287     return cast<DeclRefExpr>(E)->getDecl();
13288   case Stmt::MemberExprClass:
13289     // If this is an arrow operator, the address is an offset from
13290     // the base's value, so the object the base refers to is
13291     // irrelevant.
13292     if (cast<MemberExpr>(E)->isArrow())
13293       return nullptr;
13294     // Otherwise, the expression refers to a part of the base
13295     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13296   case Stmt::ArraySubscriptExprClass: {
13297     // FIXME: This code shouldn't be necessary!  We should catch the implicit
13298     // promotion of register arrays earlier.
13299     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13300     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13301       if (ICE->getSubExpr()->getType()->isArrayType())
13302         return getPrimaryDecl(ICE->getSubExpr());
13303     }
13304     return nullptr;
13305   }
13306   case Stmt::UnaryOperatorClass: {
13307     UnaryOperator *UO = cast<UnaryOperator>(E);
13308 
13309     switch(UO->getOpcode()) {
13310     case UO_Real:
13311     case UO_Imag:
13312     case UO_Extension:
13313       return getPrimaryDecl(UO->getSubExpr());
13314     default:
13315       return nullptr;
13316     }
13317   }
13318   case Stmt::ParenExprClass:
13319     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13320   case Stmt::ImplicitCastExprClass:
13321     // If the result of an implicit cast is an l-value, we care about
13322     // the sub-expression; otherwise, the result here doesn't matter.
13323     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13324   case Stmt::CXXUuidofExprClass:
13325     return cast<CXXUuidofExpr>(E)->getGuidDecl();
13326   default:
13327     return nullptr;
13328   }
13329 }
13330 
13331 namespace {
13332 enum {
13333   AO_Bit_Field = 0,
13334   AO_Vector_Element = 1,
13335   AO_Property_Expansion = 2,
13336   AO_Register_Variable = 3,
13337   AO_Matrix_Element = 4,
13338   AO_No_Error = 5
13339 };
13340 }
13341 /// Diagnose invalid operand for address of operations.
13342 ///
13343 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)13344 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13345                                          Expr *E, unsigned Type) {
13346   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13347 }
13348 
13349 static PointerInterpretationKind
pointerKindForBaseExpr(const ASTContext & Context,const Expr * Base,bool WasMemberExpr=false)13350 pointerKindForBaseExpr(const ASTContext &Context, const Expr *Base, bool WasMemberExpr = false) {
13351   if (auto *mr = dyn_cast<MemberExpr>(Base))
13352     return pointerKindForBaseExpr(Context, mr->getBase(), true);
13353   else if (auto *as = dyn_cast<ArraySubscriptExpr>(Base))
13354     // We need IgnoreImpCasts() here to strip the ArrayToPointerDecay
13355     return pointerKindForBaseExpr(Context, as->getBase()->IgnoreImpCasts(), true);
13356 
13357   // If we are just taking the address of something that happens to be a
13358   // capability we should not infer that the result is a capability. This only
13359   // applies if there is a least one level of MemberExpr/ArraySubscriptExpr
13360   // For example the following should be an error in the hybrid ABI:
13361   // void * __capability b;
13362   // void *__capability *__capability c = &b;
13363   if (!WasMemberExpr)
13364     return Context.getDefaultPointerInterpretation();
13365   // If the basetype is __uintcap_t we don't want to treat the result as a
13366   // capability (such as in uintcap_t foo; return &foo;)
13367   if (Base->getType()->isCHERICapabilityType(Context, /*IncludeIntCap=*/false))
13368     return PIK_Capability;
13369   return Context.getDefaultPointerInterpretation();
13370 }
13371 
13372 /// CheckAddressOfOperand - The operand of & must be either a function
13373 /// designator or an lvalue designating an object. If it is an lvalue, the
13374 /// object cannot be declared with storage class register or be a bit field.
13375 /// Note: The usual conversions are *not* applied to the operand of the &
13376 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13377 /// In C++, the operand might be an overloaded function name, in which case
13378 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)13379 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13380   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13381     if (PTy->getKind() == BuiltinType::Overload) {
13382       Expr *E = OrigOp.get()->IgnoreParens();
13383       if (!isa<OverloadExpr>(E)) {
13384         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13385         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13386           << OrigOp.get()->getSourceRange();
13387         return QualType();
13388       }
13389 
13390       OverloadExpr *Ovl = cast<OverloadExpr>(E);
13391       if (isa<UnresolvedMemberExpr>(Ovl))
13392         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13393           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13394             << OrigOp.get()->getSourceRange();
13395           return QualType();
13396         }
13397 
13398       return Context.OverloadTy;
13399     }
13400 
13401     if (PTy->getKind() == BuiltinType::UnknownAny)
13402       return Context.UnknownAnyTy;
13403 
13404     if (PTy->getKind() == BuiltinType::BoundMember) {
13405       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13406         << OrigOp.get()->getSourceRange();
13407       return QualType();
13408     }
13409 
13410     OrigOp = CheckPlaceholderExpr(OrigOp.get());
13411     if (OrigOp.isInvalid()) return QualType();
13412   }
13413 
13414   if (OrigOp.get()->isTypeDependent())
13415     return Context.DependentTy;
13416 
13417   assert(!OrigOp.get()->getType()->isPlaceholderType());
13418 
13419   // Make sure to ignore parentheses in subsequent checks
13420   Expr *op = OrigOp.get()->IgnoreParens();
13421 
13422   // In OpenCL captures for blocks called as lambda functions
13423   // are located in the private address space. Blocks used in
13424   // enqueue_kernel can be located in a different address space
13425   // depending on a vendor implementation. Thus preventing
13426   // taking an address of the capture to avoid invalid AS casts.
13427   if (LangOpts.OpenCL) {
13428     auto* VarRef = dyn_cast<DeclRefExpr>(op);
13429     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13430       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13431       return QualType();
13432     }
13433   }
13434 
13435   if (getLangOpts().C99) {
13436     // Implement C99-only parts of addressof rules.
13437     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13438       if (uOp->getOpcode() == UO_Deref)
13439         // Per C99 6.5.3.2, the address of a deref always returns a valid result
13440         // (assuming the deref expression is valid).
13441         return uOp->getSubExpr()->getType();
13442     }
13443     // Technically, there should be a check for array subscript
13444     // expressions here, but the result of one is always an lvalue anyway.
13445   }
13446   ValueDecl *dcl = getPrimaryDecl(op);
13447 
13448   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13449     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13450                                            op->getBeginLoc()))
13451       return QualType();
13452 
13453   Expr::LValueClassification lval = op->ClassifyLValue(Context);
13454   unsigned AddressOfError = AO_No_Error;
13455 
13456   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13457     bool sfinae = (bool)isSFINAEContext();
13458     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13459                                   : diag::ext_typecheck_addrof_temporary)
13460       << op->getType() << op->getSourceRange();
13461     if (sfinae)
13462       return QualType();
13463     // Materialize the temporary as an lvalue so that we can take its address.
13464     OrigOp = op =
13465         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13466   } else if (isa<ObjCSelectorExpr>(op)) {
13467     return Context.getPointerType(op->getType());
13468   } else if (lval == Expr::LV_MemberFunction) {
13469     // If it's an instance method, make a member pointer.
13470     // The expression must have exactly the form &A::foo.
13471 
13472     // If the underlying expression isn't a decl ref, give up.
13473     if (!isa<DeclRefExpr>(op)) {
13474       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13475         << OrigOp.get()->getSourceRange();
13476       return QualType();
13477     }
13478     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13479     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13480 
13481     // The id-expression was parenthesized.
13482     if (OrigOp.get() != DRE) {
13483       Diag(OpLoc, diag::err_parens_pointer_member_function)
13484         << OrigOp.get()->getSourceRange();
13485 
13486     // The method was named without a qualifier.
13487     } else if (!DRE->getQualifier()) {
13488       if (MD->getParent()->getName().empty())
13489         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13490           << op->getSourceRange();
13491       else {
13492         SmallString<32> Str;
13493         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13494         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13495           << op->getSourceRange()
13496           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13497       }
13498     }
13499 
13500     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13501     if (isa<CXXDestructorDecl>(MD))
13502       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13503 
13504     QualType MPTy = Context.getMemberPointerType(
13505         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13506     // Under the MS ABI, lock down the inheritance model now.
13507     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13508       (void)isCompleteType(OpLoc, MPTy);
13509     return MPTy;
13510   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13511     // C99 6.5.3.2p1
13512     // The operand must be either an l-value or a function designator
13513     if (!op->getType()->isFunctionType()) {
13514       // Use a special diagnostic for loads from property references.
13515       if (isa<PseudoObjectExpr>(op)) {
13516         AddressOfError = AO_Property_Expansion;
13517       } else {
13518         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13519           << op->getType() << op->getSourceRange();
13520         return QualType();
13521       }
13522     }
13523   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13524     // The operand cannot be a bit-field
13525     AddressOfError = AO_Bit_Field;
13526   } else if (op->getObjectKind() == OK_VectorComponent) {
13527     // The operand cannot be an element of a vector
13528     AddressOfError = AO_Vector_Element;
13529   } else if (op->getObjectKind() == OK_MatrixComponent) {
13530     // The operand cannot be an element of a matrix.
13531     AddressOfError = AO_Matrix_Element;
13532   } else if (dcl) { // C99 6.5.3.2p1
13533     // We have an lvalue with a decl. Make sure the decl is not declared
13534     // with the register storage-class specifier.
13535     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13536       // in C++ it is not error to take address of a register
13537       // variable (c++03 7.1.1P3)
13538       if (vd->getStorageClass() == SC_Register &&
13539           !getLangOpts().CPlusPlus) {
13540         AddressOfError = AO_Register_Variable;
13541       }
13542     } else if (isa<MSPropertyDecl>(dcl)) {
13543       AddressOfError = AO_Property_Expansion;
13544     } else if (isa<FunctionTemplateDecl>(dcl)) {
13545       return Context.OverloadTy;
13546     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13547       // Okay: we can take the address of a field.
13548       // Could be a pointer to member, though, if there is an explicit
13549       // scope qualifier for the class.
13550       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13551         DeclContext *Ctx = dcl->getDeclContext();
13552         if (Ctx && Ctx->isRecord()) {
13553           if (dcl->getType()->isReferenceType()) {
13554             Diag(OpLoc,
13555                  diag::err_cannot_form_pointer_to_member_of_reference_type)
13556               << dcl->getDeclName() << dcl->getType();
13557             return QualType();
13558           }
13559 
13560           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13561             Ctx = Ctx->getParent();
13562 
13563           QualType MPTy = Context.getMemberPointerType(
13564               op->getType(),
13565               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13566           // Under the MS ABI, lock down the inheritance model now.
13567           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13568             (void)isCompleteType(OpLoc, MPTy);
13569           return MPTy;
13570         }
13571       }
13572     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13573                !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13574       llvm_unreachable("Unknown/unexpected decl type");
13575   }
13576 
13577   if (AddressOfError != AO_No_Error) {
13578     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13579     return QualType();
13580   }
13581 
13582   if (lval == Expr::LV_IncompleteVoidType) {
13583     // Taking the address of a void variable is technically illegal, but we
13584     // allow it in cases which are otherwise valid.
13585     // Example: "extern void x; void* y = &x;".
13586     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13587   }
13588 
13589   // If the operand has type "type", the result has type "pointer to type".
13590   if (op->getType()->isObjCObjectType())
13591     return Context.getObjCObjectPointerType(op->getType());
13592 
13593   CheckAddressOfPackedMember(op);
13594 
13595   PointerInterpretationKind PIK = pointerKindForBaseExpr(Context, op);
13596   return Context.getPointerType(op->getType(), PIK);
13597 }
13598 
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)13599 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13600   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13601   if (!DRE)
13602     return;
13603   const Decl *D = DRE->getDecl();
13604   if (!D)
13605     return;
13606   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13607   if (!Param)
13608     return;
13609   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13610     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13611       return;
13612   if (FunctionScopeInfo *FD = S.getCurFunction())
13613     if (!FD->ModifiedNonNullParams.count(Param))
13614       FD->ModifiedNonNullParams.insert(Param);
13615 }
13616 
13617 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)13618 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13619                                         SourceLocation OpLoc) {
13620   if (Op->isTypeDependent())
13621     return S.Context.DependentTy;
13622 
13623   ExprResult ConvResult = S.UsualUnaryConversions(Op);
13624   if (ConvResult.isInvalid())
13625     return QualType();
13626   Op = ConvResult.get();
13627   QualType OpTy = Op->getType();
13628   QualType Result;
13629 
13630   if (isa<CXXReinterpretCastExpr>(Op)) {
13631     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13632     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13633                                      Op->getSourceRange());
13634   }
13635 
13636   if (const PointerType *PT = OpTy->getAs<PointerType>())
13637   {
13638     Result = PT->getPointeeType();
13639   }
13640   else if (const ObjCObjectPointerType *OPT =
13641              OpTy->getAs<ObjCObjectPointerType>())
13642     Result = OPT->getPointeeType();
13643   else {
13644     ExprResult PR = S.CheckPlaceholderExpr(Op);
13645     if (PR.isInvalid()) return QualType();
13646     if (PR.get() != Op)
13647       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13648   }
13649 
13650   if (Result.isNull()) {
13651     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13652       << OpTy << Op->getSourceRange();
13653     return QualType();
13654   }
13655 
13656   // Note that per both C89 and C99, indirection is always legal, even if Result
13657   // is an incomplete type or void.  It would be possible to warn about
13658   // dereferencing a void pointer, but it's completely well-defined, and such a
13659   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13660   // for pointers to 'void' but is fine for any other pointer type:
13661   //
13662   // C++ [expr.unary.op]p1:
13663   //   [...] the expression to which [the unary * operator] is applied shall
13664   //   be a pointer to an object type, or a pointer to a function type
13665   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13666     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13667       << OpTy << Op->getSourceRange();
13668 
13669   // Dereferences are usually l-values...
13670   VK = VK_LValue;
13671 
13672   // ...except that certain expressions are never l-values in C.
13673   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13674     VK = VK_RValue;
13675 
13676   return Result;
13677 }
13678 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)13679 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13680   BinaryOperatorKind Opc;
13681   switch (Kind) {
13682   default: llvm_unreachable("Unknown binop!");
13683   case tok::periodstar:           Opc = BO_PtrMemD; break;
13684   case tok::arrowstar:            Opc = BO_PtrMemI; break;
13685   case tok::star:                 Opc = BO_Mul; break;
13686   case tok::slash:                Opc = BO_Div; break;
13687   case tok::percent:              Opc = BO_Rem; break;
13688   case tok::plus:                 Opc = BO_Add; break;
13689   case tok::minus:                Opc = BO_Sub; break;
13690   case tok::lessless:             Opc = BO_Shl; break;
13691   case tok::greatergreater:       Opc = BO_Shr; break;
13692   case tok::lessequal:            Opc = BO_LE; break;
13693   case tok::less:                 Opc = BO_LT; break;
13694   case tok::greaterequal:         Opc = BO_GE; break;
13695   case tok::greater:              Opc = BO_GT; break;
13696   case tok::exclaimequal:         Opc = BO_NE; break;
13697   case tok::equalequal:           Opc = BO_EQ; break;
13698   case tok::spaceship:            Opc = BO_Cmp; break;
13699   case tok::amp:                  Opc = BO_And; break;
13700   case tok::caret:                Opc = BO_Xor; break;
13701   case tok::pipe:                 Opc = BO_Or; break;
13702   case tok::ampamp:               Opc = BO_LAnd; break;
13703   case tok::pipepipe:             Opc = BO_LOr; break;
13704   case tok::equal:                Opc = BO_Assign; break;
13705   case tok::starequal:            Opc = BO_MulAssign; break;
13706   case tok::slashequal:           Opc = BO_DivAssign; break;
13707   case tok::percentequal:         Opc = BO_RemAssign; break;
13708   case tok::plusequal:            Opc = BO_AddAssign; break;
13709   case tok::minusequal:           Opc = BO_SubAssign; break;
13710   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
13711   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
13712   case tok::ampequal:             Opc = BO_AndAssign; break;
13713   case tok::caretequal:           Opc = BO_XorAssign; break;
13714   case tok::pipeequal:            Opc = BO_OrAssign; break;
13715   case tok::comma:                Opc = BO_Comma; break;
13716   }
13717   return Opc;
13718 }
13719 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)13720 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13721   tok::TokenKind Kind) {
13722   UnaryOperatorKind Opc;
13723   switch (Kind) {
13724   default: llvm_unreachable("Unknown unary op!");
13725   case tok::plusplus:     Opc = UO_PreInc; break;
13726   case tok::minusminus:   Opc = UO_PreDec; break;
13727   case tok::amp:          Opc = UO_AddrOf; break;
13728   case tok::star:         Opc = UO_Deref; break;
13729   case tok::plus:         Opc = UO_Plus; break;
13730   case tok::minus:        Opc = UO_Minus; break;
13731   case tok::tilde:        Opc = UO_Not; break;
13732   case tok::exclaim:      Opc = UO_LNot; break;
13733   case tok::kw___real:    Opc = UO_Real; break;
13734   case tok::kw___imag:    Opc = UO_Imag; break;
13735   case tok::kw___extension__: Opc = UO_Extension; break;
13736   }
13737   return Opc;
13738 }
13739 
13740 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13741 /// This warning suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc,bool IsBuiltin)13742 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13743                                    SourceLocation OpLoc, bool IsBuiltin) {
13744   if (S.inTemplateInstantiation())
13745     return;
13746   if (S.isUnevaluatedContext())
13747     return;
13748   if (OpLoc.isInvalid() || OpLoc.isMacroID())
13749     return;
13750   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13751   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13752   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13753   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13754   if (!LHSDeclRef || !RHSDeclRef ||
13755       LHSDeclRef->getLocation().isMacroID() ||
13756       RHSDeclRef->getLocation().isMacroID())
13757     return;
13758   const ValueDecl *LHSDecl =
13759     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13760   const ValueDecl *RHSDecl =
13761     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13762   if (LHSDecl != RHSDecl)
13763     return;
13764   if (LHSDecl->getType().isVolatileQualified())
13765     return;
13766   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13767     if (RefTy->getPointeeType().isVolatileQualified())
13768       return;
13769 
13770   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13771                           : diag::warn_self_assignment_overloaded)
13772       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13773       << RHSExpr->getSourceRange();
13774 }
13775 
13776 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
13777 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)13778 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13779                                           SourceLocation OpLoc) {
13780   if (!S.getLangOpts().ObjC)
13781     return;
13782 
13783   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13784   const Expr *LHS = L.get();
13785   const Expr *RHS = R.get();
13786 
13787   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13788     ObjCPointerExpr = LHS;
13789     OtherExpr = RHS;
13790   }
13791   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13792     ObjCPointerExpr = RHS;
13793     OtherExpr = LHS;
13794   }
13795 
13796   // This warning is deliberately made very specific to reduce false
13797   // positives with logic that uses '&' for hashing.  This logic mainly
13798   // looks for code trying to introspect into tagged pointers, which
13799   // code should generally never do.
13800   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13801     unsigned Diag = diag::warn_objc_pointer_masking;
13802     // Determine if we are introspecting the result of performSelectorXXX.
13803     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13804     // Special case messages to -performSelector and friends, which
13805     // can return non-pointer values boxed in a pointer value.
13806     // Some clients may wish to silence warnings in this subcase.
13807     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13808       Selector S = ME->getSelector();
13809       StringRef SelArg0 = S.getNameForSlot(0);
13810       if (SelArg0.startswith("performSelector"))
13811         Diag = diag::warn_objc_pointer_masking_performSelector;
13812     }
13813 
13814     S.Diag(OpLoc, Diag)
13815       << ObjCPointerExpr->getSourceRange();
13816   }
13817 }
13818 
getDeclFromExpr(Expr * E)13819 static NamedDecl *getDeclFromExpr(Expr *E) {
13820   if (!E)
13821     return nullptr;
13822   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13823     return DRE->getDecl();
13824   if (auto *ME = dyn_cast<MemberExpr>(E))
13825     return ME->getMemberDecl();
13826   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13827     return IRE->getDecl();
13828   return nullptr;
13829 }
13830 
13831 // This helper function promotes a binary operator's operands (which are of a
13832 // half vector type) to a vector of floats and then truncates the result to
13833 // a vector of either half or short.
convertHalfVecBinOp(Sema & S,ExprResult LHS,ExprResult RHS,BinaryOperatorKind Opc,QualType ResultTy,ExprValueKind VK,ExprObjectKind OK,bool IsCompAssign,SourceLocation OpLoc,FPOptionsOverride FPFeatures)13834 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13835                                       BinaryOperatorKind Opc, QualType ResultTy,
13836                                       ExprValueKind VK, ExprObjectKind OK,
13837                                       bool IsCompAssign, SourceLocation OpLoc,
13838                                       FPOptionsOverride FPFeatures) {
13839   auto &Context = S.getASTContext();
13840   assert((isVector(ResultTy, Context.HalfTy) ||
13841           isVector(ResultTy, Context.ShortTy)) &&
13842          "Result must be a vector of half or short");
13843   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13844          isVector(RHS.get()->getType(), Context.HalfTy) &&
13845          "both operands expected to be a half vector");
13846 
13847   RHS = convertVector(RHS.get(), Context.FloatTy, S);
13848   QualType BinOpResTy = RHS.get()->getType();
13849 
13850   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13851   // change BinOpResTy to a vector of ints.
13852   if (isVector(ResultTy, Context.ShortTy))
13853     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13854 
13855   if (IsCompAssign)
13856     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13857                                           ResultTy, VK, OK, OpLoc, FPFeatures,
13858                                           BinOpResTy, BinOpResTy);
13859 
13860   LHS = convertVector(LHS.get(), Context.FloatTy, S);
13861   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13862                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
13863   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13864 }
13865 
13866 static std::pair<ExprResult, ExprResult>
CorrectDelayedTyposInBinOp(Sema & S,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13867 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13868                            Expr *RHSExpr) {
13869   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13870   if (!S.getLangOpts().CPlusPlus) {
13871     // C cannot handle TypoExpr nodes on either side of a binop because it
13872     // doesn't handle dependent types properly, so make sure any TypoExprs have
13873     // been dealt with before checking the operands.
13874     LHS = S.CorrectDelayedTyposInExpr(LHS);
13875     RHS = S.CorrectDelayedTyposInExpr(
13876         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13877         [Opc, LHS](Expr *E) {
13878           if (Opc != BO_Assign)
13879             return ExprResult(E);
13880           // Avoid correcting the RHS to the same Expr as the LHS.
13881           Decl *D = getDeclFromExpr(E);
13882           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13883         });
13884   }
13885   return std::make_pair(LHS, RHS);
13886 }
13887 
13888 /// Returns true if conversion between vectors of halfs and vectors of floats
13889 /// is needed.
needsConversionOfHalfVec(bool OpRequiresConversion,ASTContext & Ctx,Expr * E0,Expr * E1=nullptr)13890 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13891                                      Expr *E0, Expr *E1 = nullptr) {
13892   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13893       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13894     return false;
13895 
13896   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13897     QualType Ty = E->IgnoreImplicit()->getType();
13898 
13899     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13900     // to vectors of floats. Although the element type of the vectors is __fp16,
13901     // the vectors shouldn't be treated as storage-only types. See the
13902     // discussion here: https://reviews.llvm.org/rG825235c140e7
13903     if (const VectorType *VT = Ty->getAs<VectorType>()) {
13904       if (VT->getVectorKind() == VectorType::NeonVector)
13905         return false;
13906       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13907     }
13908     return false;
13909   };
13910 
13911   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13912 }
13913 
13914 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13915 /// operator @p Opc at location @c TokLoc. This routine only supports
13916 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13917 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13918                                     BinaryOperatorKind Opc,
13919                                     Expr *LHSExpr, Expr *RHSExpr) {
13920   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13921     // The syntax only allows initializer lists on the RHS of assignment,
13922     // so we don't need to worry about accepting invalid code for
13923     // non-assignment operators.
13924     // C++11 5.17p9:
13925     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13926     //   of x = {} is x = T().
13927     InitializationKind Kind = InitializationKind::CreateDirectList(
13928         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13929     InitializedEntity Entity =
13930         InitializedEntity::InitializeTemporary(LHSExpr->getType());
13931     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13932     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13933     if (Init.isInvalid())
13934       return Init;
13935     RHSExpr = Init.get();
13936   }
13937 
13938   ExprResult LHS = LHSExpr, RHS = RHSExpr;
13939   QualType ResultTy;     // Result type of the binary operator.
13940   // The following two variables are used for compound assignment operators
13941   QualType CompLHSTy;    // Type of LHS after promotions for computation
13942   QualType CompResultTy; // Type of computation result
13943   ExprValueKind VK = VK_RValue;
13944   ExprObjectKind OK = OK_Ordinary;
13945   bool ConvertHalfVec = false;
13946 
13947   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13948   if (!LHS.isUsable() || !RHS.isUsable())
13949     return ExprError();
13950 
13951   if (getLangOpts().OpenCL) {
13952     QualType LHSTy = LHSExpr->getType();
13953     QualType RHSTy = RHSExpr->getType();
13954     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13955     // the ATOMIC_VAR_INIT macro.
13956     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13957       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13958       if (BO_Assign == Opc)
13959         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13960       else
13961         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13962       return ExprError();
13963     }
13964 
13965     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13966     // only with a builtin functions and therefore should be disallowed here.
13967     if (LHSTy->isImageType() || RHSTy->isImageType() ||
13968         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13969         LHSTy->isPipeType() || RHSTy->isPipeType() ||
13970         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13971       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13972       return ExprError();
13973     }
13974   }
13975 
13976   switch (Opc) {
13977   case BO_Assign:
13978     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13979     if (getLangOpts().CPlusPlus &&
13980         LHS.get()->getObjectKind() != OK_ObjCProperty) {
13981       VK = LHS.get()->getValueKind();
13982       OK = LHS.get()->getObjectKind();
13983     }
13984     if (!ResultTy.isNull()) {
13985       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13986       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13987 
13988       // Avoid copying a block to the heap if the block is assigned to a local
13989       // auto variable that is declared in the same scope as the block. This
13990       // optimization is unsafe if the local variable is declared in an outer
13991       // scope. For example:
13992       //
13993       // BlockTy b;
13994       // {
13995       //   b = ^{...};
13996       // }
13997       // // It is unsafe to invoke the block here if it wasn't copied to the
13998       // // heap.
13999       // b();
14000 
14001       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14002         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14003           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14004             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14005               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14006 
14007       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14008         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14009                               NTCUC_Assignment, NTCUK_Copy);
14010     }
14011     RecordModifiableNonNullParam(*this, LHS.get());
14012     break;
14013   case BO_PtrMemD:
14014   case BO_PtrMemI:
14015     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14016                                             Opc == BO_PtrMemI);
14017     break;
14018   case BO_Mul:
14019   case BO_Div:
14020     ConvertHalfVec = true;
14021     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14022                                            Opc == BO_Div);
14023     break;
14024   case BO_Rem:
14025     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14026     break;
14027   case BO_Add:
14028     ConvertHalfVec = true;
14029     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14030     break;
14031   case BO_Sub:
14032     ConvertHalfVec = true;
14033     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14034     break;
14035   case BO_Shl:
14036   case BO_Shr:
14037     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14038     break;
14039   case BO_LE:
14040   case BO_LT:
14041   case BO_GE:
14042   case BO_GT:
14043     ConvertHalfVec = true;
14044     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14045     break;
14046   case BO_EQ:
14047   case BO_NE:
14048     ConvertHalfVec = true;
14049     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14050     break;
14051   case BO_Cmp:
14052     ConvertHalfVec = true;
14053     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14054     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14055     break;
14056   case BO_And:
14057     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14058     LLVM_FALLTHROUGH;
14059   case BO_Xor:
14060   case BO_Or:
14061     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14062     break;
14063   case BO_LAnd:
14064   case BO_LOr:
14065     ConvertHalfVec = true;
14066     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14067     break;
14068   case BO_MulAssign:
14069   case BO_DivAssign:
14070     ConvertHalfVec = true;
14071     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14072                                                Opc == BO_DivAssign);
14073     CompLHSTy = CompResultTy;
14074     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14075       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14076     break;
14077   case BO_RemAssign:
14078     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14079     CompLHSTy = CompResultTy;
14080     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14081       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14082     break;
14083   case BO_AddAssign:
14084     ConvertHalfVec = true;
14085     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14086     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14087       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14088     break;
14089   case BO_SubAssign:
14090     ConvertHalfVec = true;
14091     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14092     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14093       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14094     break;
14095   case BO_ShlAssign:
14096   case BO_ShrAssign:
14097     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14098     CompLHSTy = CompResultTy;
14099     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14100       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14101     break;
14102   case BO_AndAssign:
14103   case BO_OrAssign: // fallthrough
14104     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14105     LLVM_FALLTHROUGH;
14106   case BO_XorAssign:
14107     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14108     CompLHSTy = CompResultTy;
14109     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14110       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14111     break;
14112   case BO_Comma:
14113     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14114     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14115       VK = RHS.get()->getValueKind();
14116       OK = RHS.get()->getObjectKind();
14117     }
14118     break;
14119   }
14120   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14121     return ExprError();
14122 
14123   // Some of the binary operations require promoting operands of half vector to
14124   // float vectors and truncating the result back to half vector. For now, we do
14125   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14126   // arm64).
14127   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
14128          isVector(LHS.get()->getType(), Context.HalfTy) &&
14129          "both sides are half vectors or neither sides are");
14130   ConvertHalfVec =
14131       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14132 
14133   // Check for array bounds violations for both sides of the BinaryOperator
14134   CheckArrayAccess(LHS.get());
14135   CheckArrayAccess(RHS.get());
14136 
14137   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14138     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14139                                                  &Context.Idents.get("object_setClass"),
14140                                                  SourceLocation(), LookupOrdinaryName);
14141     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14142       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14143       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14144           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14145                                         "object_setClass(")
14146           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14147                                           ",")
14148           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14149     }
14150     else
14151       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14152   }
14153   else if (const ObjCIvarRefExpr *OIRE =
14154            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14155     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14156 
14157   // Opc is not a compound assignment if CompResultTy is null.
14158   if (CompResultTy.isNull()) {
14159     if (ConvertHalfVec)
14160       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14161                                  OpLoc, CurFPFeatureOverrides());
14162     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14163                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14164   }
14165 
14166   // Handle compound assignments.
14167   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14168       OK_ObjCProperty) {
14169     VK = VK_LValue;
14170     OK = LHS.get()->getObjectKind();
14171   }
14172 
14173   // The LHS is not converted to the result type for fixed-point compound
14174   // assignment as the common type is computed on demand. Reset the CompLHSTy
14175   // to the LHS type we would have gotten after unary conversions.
14176   if (CompResultTy->isFixedPointType())
14177     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14178 
14179   if (ConvertHalfVec)
14180     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14181                                OpLoc, CurFPFeatureOverrides());
14182 
14183   return CompoundAssignOperator::Create(
14184       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14185       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14186 }
14187 
14188 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14189 /// operators are mixed in a way that suggests that the programmer forgot that
14190 /// comparison operators have higher precedence. The most typical example of
14191 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14192 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14193                                       SourceLocation OpLoc, Expr *LHSExpr,
14194                                       Expr *RHSExpr) {
14195   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14196   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14197 
14198   // Check that one of the sides is a comparison operator and the other isn't.
14199   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14200   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14201   if (isLeftComp == isRightComp)
14202     return;
14203 
14204   // Bitwise operations are sometimes used as eager logical ops.
14205   // Don't diagnose this.
14206   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14207   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14208   if (isLeftBitwise || isRightBitwise)
14209     return;
14210 
14211   SourceRange DiagRange = isLeftComp
14212                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14213                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14214   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14215   SourceRange ParensRange =
14216       isLeftComp
14217           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14218           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14219 
14220   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14221     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14222   SuggestParentheses(Self, OpLoc,
14223     Self.PDiag(diag::note_precedence_silence) << OpStr,
14224     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14225   SuggestParentheses(Self, OpLoc,
14226     Self.PDiag(diag::note_precedence_bitwise_first)
14227       << BinaryOperator::getOpcodeStr(Opc),
14228     ParensRange);
14229 }
14230 
14231 /// It accepts a '&&' expr that is inside a '||' one.
14232 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14233 /// in parentheses.
14234 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)14235 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14236                                        BinaryOperator *Bop) {
14237   assert(Bop->getOpcode() == BO_LAnd);
14238   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14239       << Bop->getSourceRange() << OpLoc;
14240   SuggestParentheses(Self, Bop->getOperatorLoc(),
14241     Self.PDiag(diag::note_precedence_silence)
14242       << Bop->getOpcodeStr(),
14243     Bop->getSourceRange());
14244 }
14245 
14246 /// Returns true if the given expression can be evaluated as a constant
14247 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)14248 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14249   bool Res;
14250   return !E->isValueDependent() &&
14251          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14252 }
14253 
14254 /// Returns true if the given expression can be evaluated as a constant
14255 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)14256 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14257   bool Res;
14258   return !E->isValueDependent() &&
14259          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14260 }
14261 
14262 /// Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14263 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14264                                              Expr *LHSExpr, Expr *RHSExpr) {
14265   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14266     if (Bop->getOpcode() == BO_LAnd) {
14267       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14268       if (EvaluatesAsFalse(S, RHSExpr))
14269         return;
14270       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14271       if (!EvaluatesAsTrue(S, Bop->getLHS()))
14272         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14273     } else if (Bop->getOpcode() == BO_LOr) {
14274       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14275         // If it's "a || b && 1 || c" we didn't warn earlier for
14276         // "a || b && 1", but warn now.
14277         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14278           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14279       }
14280     }
14281   }
14282 }
14283 
14284 /// Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14285 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14286                                              Expr *LHSExpr, Expr *RHSExpr) {
14287   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14288     if (Bop->getOpcode() == BO_LAnd) {
14289       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14290       if (EvaluatesAsFalse(S, LHSExpr))
14291         return;
14292       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14293       if (!EvaluatesAsTrue(S, Bop->getRHS()))
14294         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14295     }
14296   }
14297 }
14298 
14299 /// Look for bitwise op in the left or right hand of a bitwise op with
14300 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14301 /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)14302 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14303                                          SourceLocation OpLoc, Expr *SubExpr) {
14304   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14305     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14306       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14307         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14308         << Bop->getSourceRange() << OpLoc;
14309       SuggestParentheses(S, Bop->getOperatorLoc(),
14310         S.PDiag(diag::note_precedence_silence)
14311           << Bop->getOpcodeStr(),
14312         Bop->getSourceRange());
14313     }
14314   }
14315 }
14316 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)14317 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14318                                     Expr *SubExpr, StringRef Shift) {
14319   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14320     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14321       StringRef Op = Bop->getOpcodeStr();
14322       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14323           << Bop->getSourceRange() << OpLoc << Shift << Op;
14324       SuggestParentheses(S, Bop->getOperatorLoc(),
14325           S.PDiag(diag::note_precedence_silence) << Op,
14326           Bop->getSourceRange());
14327     }
14328   }
14329 }
14330 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14331 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14332                                  Expr *LHSExpr, Expr *RHSExpr) {
14333   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14334   if (!OCE)
14335     return;
14336 
14337   FunctionDecl *FD = OCE->getDirectCallee();
14338   if (!FD || !FD->isOverloadedOperator())
14339     return;
14340 
14341   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14342   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14343     return;
14344 
14345   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14346       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14347       << (Kind == OO_LessLess);
14348   SuggestParentheses(S, OCE->getOperatorLoc(),
14349                      S.PDiag(diag::note_precedence_silence)
14350                          << (Kind == OO_LessLess ? "<<" : ">>"),
14351                      OCE->getSourceRange());
14352   SuggestParentheses(
14353       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14354       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14355 }
14356 
14357 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14358 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14359 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14360                                     SourceLocation OpLoc, Expr *LHSExpr,
14361                                     Expr *RHSExpr){
14362   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14363   if (BinaryOperator::isBitwiseOp(Opc))
14364     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14365 
14366   // Diagnose "arg1 & arg2 | arg3"
14367   if ((Opc == BO_Or || Opc == BO_Xor) &&
14368       !OpLoc.isMacroID()/* Don't warn in macros. */) {
14369     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14370     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14371   }
14372 
14373   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14374   // We don't warn for 'assert(a || b && "bad")' since this is safe.
14375   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14376     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14377     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14378   }
14379 
14380   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14381       || Opc == BO_Shr) {
14382     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14383     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14384     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14385   }
14386 
14387   // Warn on overloaded shift operators and comparisons, such as:
14388   // cout << 5 == 4;
14389   if (BinaryOperator::isComparisonOp(Opc))
14390     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14391 }
14392 
14393 // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)14394 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14395                             tok::TokenKind Kind,
14396                             Expr *LHSExpr, Expr *RHSExpr) {
14397   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14398   assert(LHSExpr && "ActOnBinOp(): missing left expression");
14399   assert(RHSExpr && "ActOnBinOp(): missing right expression");
14400 
14401   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14402   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14403 
14404   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14405 }
14406 
14407 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)14408 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14409                                        BinaryOperatorKind Opc,
14410                                        Expr *LHS, Expr *RHS) {
14411   switch (Opc) {
14412   case BO_Assign:
14413   case BO_DivAssign:
14414   case BO_RemAssign:
14415   case BO_SubAssign:
14416   case BO_AndAssign:
14417   case BO_OrAssign:
14418   case BO_XorAssign:
14419     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14420     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14421     break;
14422   default:
14423     break;
14424   }
14425 
14426   // Find all of the overloaded operators visible from this
14427   // point. We perform both an operator-name lookup from the local
14428   // scope and an argument-dependent lookup based on the types of
14429   // the arguments.
14430   UnresolvedSet<16> Functions;
14431   OverloadedOperatorKind OverOp
14432     = BinaryOperator::getOverloadedOperator(Opc);
14433   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14434     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14435                                    RHS->getType(), Functions);
14436 
14437   // In C++20 onwards, we may have a second operator to look up.
14438   if (S.getLangOpts().CPlusPlus20) {
14439     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14440       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14441                                      RHS->getType(), Functions);
14442   }
14443 
14444   // Build the (potentially-overloaded, potentially-dependent)
14445   // binary operation.
14446   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14447 }
14448 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14449 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14450                             BinaryOperatorKind Opc,
14451                             Expr *LHSExpr, Expr *RHSExpr) {
14452   ExprResult LHS, RHS;
14453   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14454   if (!LHS.isUsable() || !RHS.isUsable())
14455     return ExprError();
14456   LHSExpr = LHS.get();
14457   RHSExpr = RHS.get();
14458 
14459   // We want to end up calling one of checkPseudoObjectAssignment
14460   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14461   // both expressions are overloadable or either is type-dependent),
14462   // or CreateBuiltinBinOp (in any other case).  We also want to get
14463   // any placeholder types out of the way.
14464 
14465   // Handle pseudo-objects in the LHS.
14466   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14467     // Assignments with a pseudo-object l-value need special analysis.
14468     if (pty->getKind() == BuiltinType::PseudoObject &&
14469         BinaryOperator::isAssignmentOp(Opc))
14470       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14471 
14472     // Don't resolve overloads if the other type is overloadable.
14473     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14474       // We can't actually test that if we still have a placeholder,
14475       // though.  Fortunately, none of the exceptions we see in that
14476       // code below are valid when the LHS is an overload set.  Note
14477       // that an overload set can be dependently-typed, but it never
14478       // instantiates to having an overloadable type.
14479       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14480       if (resolvedRHS.isInvalid()) return ExprError();
14481       RHSExpr = resolvedRHS.get();
14482 
14483       if (RHSExpr->isTypeDependent() ||
14484           RHSExpr->getType()->isOverloadableType())
14485         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14486     }
14487 
14488     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14489     // template, diagnose the missing 'template' keyword instead of diagnosing
14490     // an invalid use of a bound member function.
14491     //
14492     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14493     // to C++1z [over.over]/1.4, but we already checked for that case above.
14494     if (Opc == BO_LT && inTemplateInstantiation() &&
14495         (pty->getKind() == BuiltinType::BoundMember ||
14496          pty->getKind() == BuiltinType::Overload)) {
14497       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14498       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14499           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14500             return isa<FunctionTemplateDecl>(ND);
14501           })) {
14502         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14503                                 : OE->getNameLoc(),
14504              diag::err_template_kw_missing)
14505           << OE->getName().getAsString() << "";
14506         return ExprError();
14507       }
14508     }
14509 
14510     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14511     if (LHS.isInvalid()) return ExprError();
14512     LHSExpr = LHS.get();
14513   }
14514 
14515   // Handle pseudo-objects in the RHS.
14516   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14517     // An overload in the RHS can potentially be resolved by the type
14518     // being assigned to.
14519     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14520       if (getLangOpts().CPlusPlus &&
14521           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14522            LHSExpr->getType()->isOverloadableType()))
14523         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14524 
14525       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14526     }
14527 
14528     // Don't resolve overloads if the other type is overloadable.
14529     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14530         LHSExpr->getType()->isOverloadableType())
14531       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14532 
14533     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14534     if (!resolvedRHS.isUsable()) return ExprError();
14535     RHSExpr = resolvedRHS.get();
14536   }
14537 
14538   if (getLangOpts().CPlusPlus) {
14539     // If either expression is type-dependent, always build an
14540     // overloaded op.
14541     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14542       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14543 
14544     // Otherwise, build an overloaded op if either expression has an
14545     // overloadable type.
14546     if (LHSExpr->getType()->isOverloadableType() ||
14547         RHSExpr->getType()->isOverloadableType())
14548       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14549   }
14550 
14551   // Build a built-in binary operation.
14552   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14553 }
14554 
isOverflowingIntegerType(ASTContext & Ctx,QualType T)14555 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14556   if (T.isNull() || T->isDependentType())
14557     return false;
14558 
14559   if (!T->isPromotableIntegerType())
14560     return true;
14561 
14562   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14563 }
14564 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)14565 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14566                                       UnaryOperatorKind Opc,
14567                                       Expr *InputExpr) {
14568   if (InputExpr->getType().getQualifiers().hasOutput()) {
14569     return ExprError(Diag(InputExpr->getExprLoc(), diag::err_typecheck_read_output)
14570       << InputExpr->getSourceRange());
14571   }
14572 
14573 
14574   ExprResult Input = InputExpr;
14575   ExprValueKind VK = VK_RValue;
14576   ExprObjectKind OK = OK_Ordinary;
14577   QualType resultType;
14578   bool CanOverflow = false;
14579 
14580   bool ConvertHalfVec = false;
14581   if (getLangOpts().OpenCL) {
14582     QualType Ty = InputExpr->getType();
14583     // The only legal unary operation for atomics is '&'.
14584     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14585     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14586     // only with a builtin functions and therefore should be disallowed here.
14587         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14588         || Ty->isBlockPointerType())) {
14589       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14590                        << InputExpr->getType()
14591                        << Input.get()->getSourceRange());
14592     }
14593   }
14594 
14595   switch (Opc) {
14596   case UO_PreInc:
14597   case UO_PreDec:
14598   case UO_PostInc:
14599   case UO_PostDec:
14600     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14601                                                 OpLoc,
14602                                                 Opc == UO_PreInc ||
14603                                                 Opc == UO_PostInc,
14604                                                 Opc == UO_PreInc ||
14605                                                 Opc == UO_PreDec);
14606     CanOverflow = isOverflowingIntegerType(Context, resultType);
14607     break;
14608   case UO_AddrOf:
14609     resultType = CheckAddressOfOperand(Input, OpLoc);
14610     CheckAddressOfNoDeref(InputExpr);
14611     RecordModifiableNonNullParam(*this, InputExpr);
14612     break;
14613   case UO_Deref: {
14614     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14615     if (Input.isInvalid()) return ExprError();
14616     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14617     break;
14618   }
14619   case UO_Plus:
14620   case UO_Minus:
14621     CanOverflow = Opc == UO_Minus &&
14622                   isOverflowingIntegerType(Context, Input.get()->getType());
14623     Input = UsualUnaryConversions(Input.get());
14624     if (Input.isInvalid()) return ExprError();
14625     // Unary plus and minus require promoting an operand of half vector to a
14626     // float vector and truncating the result back to a half vector. For now, we
14627     // do this only when HalfArgsAndReturns is set (that is, when the target is
14628     // arm or arm64).
14629     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14630 
14631     // If the operand is a half vector, promote it to a float vector.
14632     if (ConvertHalfVec)
14633       Input = convertVector(Input.get(), Context.FloatTy, *this);
14634     resultType = Input.get()->getType();
14635     if (resultType->isDependentType())
14636       break;
14637     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14638       break;
14639     else if (resultType->isVectorType() &&
14640              // The z vector extensions don't allow + or - with bool vectors.
14641              (!Context.getLangOpts().ZVector ||
14642               resultType->castAs<VectorType>()->getVectorKind() !=
14643               VectorType::AltiVecBool))
14644       break;
14645     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14646              Opc == UO_Plus &&
14647              resultType->isPointerType())
14648       break;
14649 
14650     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14651       << resultType << Input.get()->getSourceRange());
14652 
14653   case UO_Not: // bitwise complement
14654     Input = UsualUnaryConversions(Input.get());
14655     if (Input.isInvalid())
14656       return ExprError();
14657     resultType = Input.get()->getType();
14658     if (resultType->isDependentType())
14659       break;
14660     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14661     if (resultType->isComplexType() || resultType->isComplexIntegerType())
14662       // C99 does not support '~' for complex conjugation.
14663       Diag(OpLoc, diag::ext_integer_complement_complex)
14664           << resultType << Input.get()->getSourceRange();
14665     else if (resultType->hasIntegerRepresentation())
14666       break;
14667     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14668       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14669       // on vector float types.
14670       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14671       if (!T->isIntegerType())
14672         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14673                           << resultType << Input.get()->getSourceRange());
14674     } else {
14675       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14676                        << resultType << Input.get()->getSourceRange());
14677     }
14678     break;
14679 
14680   case UO_LNot: // logical negation
14681     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14682     Input = DefaultFunctionArrayLvalueConversion(Input.get());
14683     if (Input.isInvalid()) return ExprError();
14684     resultType = Input.get()->getType();
14685 
14686     // Though we still have to promote half FP to float...
14687     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14688       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14689       resultType = Context.FloatTy;
14690     }
14691 
14692     if (resultType->isDependentType())
14693       break;
14694     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14695       // C99 6.5.3.3p1: ok, fallthrough;
14696       if (Context.getLangOpts().CPlusPlus) {
14697         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14698         // operand contextually converted to bool.
14699         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14700                                   ScalarTypeToBooleanCastKind(resultType));
14701       } else if (Context.getLangOpts().OpenCL &&
14702                  Context.getLangOpts().OpenCLVersion < 120) {
14703         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14704         // operate on scalar float types.
14705         if (!resultType->isIntegerType() && !resultType->isPointerType())
14706           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14707                            << resultType << Input.get()->getSourceRange());
14708       }
14709     } else if (resultType->isExtVectorType()) {
14710       if (Context.getLangOpts().OpenCL &&
14711           Context.getLangOpts().OpenCLVersion < 120 &&
14712           !Context.getLangOpts().OpenCLCPlusPlus) {
14713         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14714         // operate on vector float types.
14715         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14716         if (!T->isIntegerType())
14717           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14718                            << resultType << Input.get()->getSourceRange());
14719       }
14720       // Vector logical not returns the signed variant of the operand type.
14721       resultType = GetSignedVectorType(resultType);
14722       break;
14723     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14724       const VectorType *VTy = resultType->castAs<VectorType>();
14725       if (VTy->getVectorKind() != VectorType::GenericVector)
14726         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14727                          << resultType << Input.get()->getSourceRange());
14728 
14729       // Vector logical not returns the signed variant of the operand type.
14730       resultType = GetSignedVectorType(resultType);
14731       break;
14732     } else {
14733       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14734         << resultType << Input.get()->getSourceRange());
14735     }
14736 
14737     // LNot always has type int. C99 6.5.3.3p5.
14738     // In C++, it's bool. C++ 5.3.1p8
14739     resultType = Context.getLogicalOperationType();
14740     break;
14741   case UO_Real:
14742   case UO_Imag:
14743     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14744     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14745     // complex l-values to ordinary l-values and all other values to r-values.
14746     if (Input.isInvalid()) return ExprError();
14747     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14748       if (Input.get()->getValueKind() != VK_RValue &&
14749           Input.get()->getObjectKind() == OK_Ordinary)
14750         VK = Input.get()->getValueKind();
14751     } else if (!getLangOpts().CPlusPlus) {
14752       // In C, a volatile scalar is read by __imag. In C++, it is not.
14753       Input = DefaultLvalueConversion(Input.get());
14754     }
14755     break;
14756   case UO_Extension:
14757     resultType = Input.get()->getType();
14758     VK = Input.get()->getValueKind();
14759     OK = Input.get()->getObjectKind();
14760     break;
14761   case UO_Coawait:
14762     // It's unnecessary to represent the pass-through operator co_await in the
14763     // AST; just return the input expression instead.
14764     assert(!Input.get()->getType()->isDependentType() &&
14765                    "the co_await expression must be non-dependant before "
14766                    "building operator co_await");
14767     return Input;
14768   }
14769   if (resultType.isNull() || Input.isInvalid())
14770     return ExprError();
14771 
14772   // Check for array bounds violations in the operand of the UnaryOperator,
14773   // except for the '*' and '&' operators that have to be handled specially
14774   // by CheckArrayAccess (as there are special cases like &array[arraysize]
14775   // that are explicitly defined as valid by the standard).
14776   if (Opc != UO_AddrOf && Opc != UO_Deref)
14777     CheckArrayAccess(Input.get());
14778 
14779   auto *UO =
14780       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14781                             OpLoc, CanOverflow, CurFPFeatureOverrides());
14782 
14783   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14784       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14785     ExprEvalContexts.back().PossibleDerefs.insert(UO);
14786 
14787   // Convert the result back to a half vector.
14788   if (ConvertHalfVec)
14789     return convertVector(UO, Context.HalfTy, *this);
14790   return UO;
14791 }
14792 
14793 /// Determine whether the given expression is a qualified member
14794 /// access expression, of a form that could be turned into a pointer to member
14795 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)14796 bool Sema::isQualifiedMemberAccess(Expr *E) {
14797   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14798     if (!DRE->getQualifier())
14799       return false;
14800 
14801     ValueDecl *VD = DRE->getDecl();
14802     if (!VD->isCXXClassMember())
14803       return false;
14804 
14805     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14806       return true;
14807     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14808       return Method->isInstance();
14809 
14810     return false;
14811   }
14812 
14813   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14814     if (!ULE->getQualifier())
14815       return false;
14816 
14817     for (NamedDecl *D : ULE->decls()) {
14818       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14819         if (Method->isInstance())
14820           return true;
14821       } else {
14822         // Overload set does not contain methods.
14823         break;
14824       }
14825     }
14826 
14827     return false;
14828   }
14829 
14830   return false;
14831 }
14832 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)14833 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14834                               UnaryOperatorKind Opc, Expr *Input) {
14835   // First things first: handle placeholders so that the
14836   // overloaded-operator check considers the right type.
14837   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14838     // Increment and decrement of pseudo-object references.
14839     if (pty->getKind() == BuiltinType::PseudoObject &&
14840         UnaryOperator::isIncrementDecrementOp(Opc))
14841       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14842 
14843     // extension is always a builtin operator.
14844     if (Opc == UO_Extension)
14845       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14846 
14847     // & gets special logic for several kinds of placeholder.
14848     // The builtin code knows what to do.
14849     if (Opc == UO_AddrOf &&
14850         (pty->getKind() == BuiltinType::Overload ||
14851          pty->getKind() == BuiltinType::UnknownAny ||
14852          pty->getKind() == BuiltinType::BoundMember))
14853       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14854 
14855     // Anything else needs to be handled now.
14856     ExprResult Result = CheckPlaceholderExpr(Input);
14857     if (Result.isInvalid()) return ExprError();
14858     Input = Result.get();
14859   }
14860 
14861   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14862       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14863       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14864     // Find all of the overloaded operators visible from this
14865     // point. We perform both an operator-name lookup from the local
14866     // scope and an argument-dependent lookup based on the types of
14867     // the arguments.
14868     UnresolvedSet<16> Functions;
14869     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14870     if (S && OverOp != OO_None)
14871       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14872                                    Functions);
14873 
14874     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14875   }
14876 
14877   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14878 }
14879 
14880 // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)14881 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14882                               tok::TokenKind Op, Expr *Input) {
14883   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14884 }
14885 
14886 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)14887 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14888                                 LabelDecl *TheDecl) {
14889   TheDecl->markUsed(Context);
14890   // Create the AST node.  The address of a label always has type 'void*'.
14891   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14892                                      Context.getPointerType(Context.VoidTy));
14893 }
14894 
ActOnStartStmtExpr()14895 void Sema::ActOnStartStmtExpr() {
14896   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14897 }
14898 
ActOnStmtExprError()14899 void Sema::ActOnStmtExprError() {
14900   // Note that function is also called by TreeTransform when leaving a
14901   // StmtExpr scope without rebuilding anything.
14902 
14903   DiscardCleanupsInEvaluationContext();
14904   PopExpressionEvaluationContext();
14905 }
14906 
ActOnStmtExpr(Scope * S,SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)14907 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14908                                SourceLocation RPLoc) {
14909   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14910 }
14911 
BuildStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc,unsigned TemplateDepth)14912 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14913                                SourceLocation RPLoc, unsigned TemplateDepth) {
14914   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14915   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14916 
14917   if (hasAnyUnrecoverableErrorsInThisFunction())
14918     DiscardCleanupsInEvaluationContext();
14919   assert(!Cleanup.exprNeedsCleanups() &&
14920          "cleanups within StmtExpr not correctly bound!");
14921   PopExpressionEvaluationContext();
14922 
14923   // FIXME: there are a variety of strange constraints to enforce here, for
14924   // example, it is not possible to goto into a stmt expression apparently.
14925   // More semantic analysis is needed.
14926 
14927   // If there are sub-stmts in the compound stmt, take the type of the last one
14928   // as the type of the stmtexpr.
14929   QualType Ty = Context.VoidTy;
14930   bool StmtExprMayBindToTemp = false;
14931   if (!Compound->body_empty()) {
14932     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14933     if (const auto *LastStmt =
14934             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14935       if (const Expr *Value = LastStmt->getExprStmt()) {
14936         StmtExprMayBindToTemp = true;
14937         Ty = Value->getType();
14938       }
14939     }
14940   }
14941 
14942   // FIXME: Check that expression type is complete/non-abstract; statement
14943   // expressions are not lvalues.
14944   Expr *ResStmtExpr =
14945       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14946   if (StmtExprMayBindToTemp)
14947     return MaybeBindToTemporary(ResStmtExpr);
14948   return ResStmtExpr;
14949 }
14950 
ActOnStmtExprResult(ExprResult ER)14951 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14952   if (ER.isInvalid())
14953     return ExprError();
14954 
14955   // Do function/array conversion on the last expression, but not
14956   // lvalue-to-rvalue.  However, initialize an unqualified type.
14957   ER = DefaultFunctionArrayConversion(ER.get());
14958   if (ER.isInvalid())
14959     return ExprError();
14960   Expr *E = ER.get();
14961 
14962   if (E->isTypeDependent())
14963     return E;
14964 
14965   // In ARC, if the final expression ends in a consume, splice
14966   // the consume out and bind it later.  In the alternate case
14967   // (when dealing with a retainable type), the result
14968   // initialization will create a produce.  In both cases the
14969   // result will be +1, and we'll need to balance that out with
14970   // a bind.
14971   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14972   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14973     return Cast->getSubExpr();
14974 
14975   // FIXME: Provide a better location for the initialization.
14976   return PerformCopyInitialization(
14977       InitializedEntity::InitializeStmtExprResult(
14978           E->getBeginLoc(), E->getType().getUnqualifiedType()),
14979       SourceLocation(), E);
14980 }
14981 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)14982 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14983                                       TypeSourceInfo *TInfo,
14984                                       ArrayRef<OffsetOfComponent> Components,
14985                                       SourceLocation RParenLoc) {
14986   QualType ArgTy = TInfo->getType();
14987   bool Dependent = ArgTy->isDependentType();
14988   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14989 
14990   // We must have at least one component that refers to the type, and the first
14991   // one is known to be a field designator.  Verify that the ArgTy represents
14992   // a struct/union/class.
14993   if (!Dependent && !ArgTy->isRecordType())
14994     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14995                        << ArgTy << TypeRange);
14996 
14997   // Type must be complete per C99 7.17p3 because a declaring a variable
14998   // with an incomplete type would be ill-formed.
14999   if (!Dependent
15000       && RequireCompleteType(BuiltinLoc, ArgTy,
15001                              diag::err_offsetof_incomplete_type, TypeRange))
15002     return ExprError();
15003 
15004   bool DidWarnAboutNonPOD = false;
15005   QualType CurrentType = ArgTy;
15006   SmallVector<OffsetOfNode, 4> Comps;
15007   SmallVector<Expr*, 4> Exprs;
15008   for (const OffsetOfComponent &OC : Components) {
15009     if (OC.isBrackets) {
15010       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15011       if (!CurrentType->isDependentType()) {
15012         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15013         if(!AT)
15014           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15015                            << CurrentType);
15016         CurrentType = AT->getElementType();
15017       } else
15018         CurrentType = Context.DependentTy;
15019 
15020       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15021       if (IdxRval.isInvalid())
15022         return ExprError();
15023       Expr *Idx = IdxRval.get();
15024 
15025       // The expression must be an integral expression.
15026       // FIXME: An integral constant expression?
15027       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15028           !Idx->getType()->isIntegerType())
15029         return ExprError(
15030             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15031             << Idx->getSourceRange());
15032 
15033       // Record this array index.
15034       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15035       Exprs.push_back(Idx);
15036       continue;
15037     }
15038 
15039     // Offset of a field.
15040     if (CurrentType->isDependentType()) {
15041       // We have the offset of a field, but we can't look into the dependent
15042       // type. Just record the identifier of the field.
15043       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15044       CurrentType = Context.DependentTy;
15045       continue;
15046     }
15047 
15048     // We need to have a complete type to look into.
15049     if (RequireCompleteType(OC.LocStart, CurrentType,
15050                             diag::err_offsetof_incomplete_type))
15051       return ExprError();
15052 
15053     // Look for the designated field.
15054     const RecordType *RC = CurrentType->getAs<RecordType>();
15055     if (!RC)
15056       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15057                        << CurrentType);
15058     RecordDecl *RD = RC->getDecl();
15059 
15060     // C++ [lib.support.types]p5:
15061     //   The macro offsetof accepts a restricted set of type arguments in this
15062     //   International Standard. type shall be a POD structure or a POD union
15063     //   (clause 9).
15064     // C++11 [support.types]p4:
15065     //   If type is not a standard-layout class (Clause 9), the results are
15066     //   undefined.
15067     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15068       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15069       unsigned DiagID =
15070         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15071                             : diag::ext_offsetof_non_pod_type;
15072 
15073       if (!IsSafe && !DidWarnAboutNonPOD &&
15074           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15075                               PDiag(DiagID)
15076                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15077                               << CurrentType))
15078         DidWarnAboutNonPOD = true;
15079     }
15080 
15081     // Look for the field.
15082     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15083     LookupQualifiedName(R, RD);
15084     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15085     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15086     if (!MemberDecl) {
15087       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15088         MemberDecl = IndirectMemberDecl->getAnonField();
15089     }
15090 
15091     if (!MemberDecl)
15092       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15093                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15094                                                               OC.LocEnd));
15095 
15096     // C99 7.17p3:
15097     //   (If the specified member is a bit-field, the behavior is undefined.)
15098     //
15099     // We diagnose this as an error.
15100     if (MemberDecl->isBitField()) {
15101       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15102         << MemberDecl->getDeclName()
15103         << SourceRange(BuiltinLoc, RParenLoc);
15104       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15105       return ExprError();
15106     }
15107 
15108     RecordDecl *Parent = MemberDecl->getParent();
15109     if (IndirectMemberDecl)
15110       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15111 
15112     // If the member was found in a base class, introduce OffsetOfNodes for
15113     // the base class indirections.
15114     CXXBasePaths Paths;
15115     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15116                       Paths)) {
15117       if (Paths.getDetectedVirtual()) {
15118         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15119           << MemberDecl->getDeclName()
15120           << SourceRange(BuiltinLoc, RParenLoc);
15121         return ExprError();
15122       }
15123 
15124       CXXBasePath &Path = Paths.front();
15125       for (const CXXBasePathElement &B : Path)
15126         Comps.push_back(OffsetOfNode(B.Base));
15127     }
15128 
15129     if (IndirectMemberDecl) {
15130       for (auto *FI : IndirectMemberDecl->chain()) {
15131         assert(isa<FieldDecl>(FI));
15132         Comps.push_back(OffsetOfNode(OC.LocStart,
15133                                      cast<FieldDecl>(FI), OC.LocEnd));
15134       }
15135     } else
15136       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15137 
15138     CurrentType = MemberDecl->getType().getNonReferenceType();
15139   }
15140 
15141   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15142                               Comps, Exprs, RParenLoc);
15143 }
15144 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15145 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15146                                       SourceLocation BuiltinLoc,
15147                                       SourceLocation TypeLoc,
15148                                       ParsedType ParsedArgTy,
15149                                       ArrayRef<OffsetOfComponent> Components,
15150                                       SourceLocation RParenLoc) {
15151 
15152   TypeSourceInfo *ArgTInfo;
15153   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15154   if (ArgTy.isNull())
15155     return ExprError();
15156 
15157   if (!ArgTInfo)
15158     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15159 
15160   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15161 }
15162 
15163 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)15164 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15165                                  Expr *CondExpr,
15166                                  Expr *LHSExpr, Expr *RHSExpr,
15167                                  SourceLocation RPLoc) {
15168   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15169 
15170   ExprValueKind VK = VK_RValue;
15171   ExprObjectKind OK = OK_Ordinary;
15172   QualType resType;
15173   bool CondIsTrue = false;
15174   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15175     resType = Context.DependentTy;
15176   } else {
15177     // The conditional expression is required to be a constant expression.
15178     llvm::APSInt condEval(32);
15179     ExprResult CondICE
15180       = VerifyIntegerConstantExpression(CondExpr, &condEval,
15181           diag::err_typecheck_choose_expr_requires_constant, false);
15182     if (CondICE.isInvalid())
15183       return ExprError();
15184     CondExpr = CondICE.get();
15185     CondIsTrue = condEval.getZExtValue();
15186 
15187     // If the condition is > zero, then the AST type is the same as the LHSExpr.
15188     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15189 
15190     resType = ActiveExpr->getType();
15191     VK = ActiveExpr->getValueKind();
15192     OK = ActiveExpr->getObjectKind();
15193   }
15194 
15195   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15196                                   resType, VK, OK, RPLoc, CondIsTrue);
15197 }
15198 
15199 //===----------------------------------------------------------------------===//
15200 // Clang Extensions.
15201 //===----------------------------------------------------------------------===//
15202 
15203 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)15204 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15205   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15206 
15207   if (LangOpts.CPlusPlus) {
15208     MangleNumberingContext *MCtx;
15209     Decl *ManglingContextDecl;
15210     std::tie(MCtx, ManglingContextDecl) =
15211         getCurrentMangleNumberContext(Block->getDeclContext());
15212     if (MCtx) {
15213       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15214       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15215     }
15216   }
15217 
15218   PushBlockScope(CurScope, Block);
15219   CurContext->addDecl(Block);
15220   if (CurScope)
15221     PushDeclContext(CurScope, Block);
15222   else
15223     CurContext = Block;
15224 
15225   getCurBlock()->HasImplicitReturnType = true;
15226 
15227   // Enter a new evaluation context to insulate the block from any
15228   // cleanups from the enclosing full-expression.
15229   PushExpressionEvaluationContext(
15230       ExpressionEvaluationContext::PotentiallyEvaluated);
15231 }
15232 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)15233 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15234                                Scope *CurScope) {
15235   assert(ParamInfo.getIdentifier() == nullptr &&
15236          "block-id should have no identifier!");
15237   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
15238   BlockScopeInfo *CurBlock = getCurBlock();
15239 
15240   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15241   QualType T = Sig->getType();
15242 
15243   // FIXME: We should allow unexpanded parameter packs here, but that would,
15244   // in turn, make the block expression contain unexpanded parameter packs.
15245   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15246     // Drop the parameters.
15247     FunctionProtoType::ExtProtoInfo EPI;
15248     EPI.HasTrailingReturn = false;
15249     EPI.TypeQuals.addConst();
15250     T = Context.getFunctionType(Context.DependentTy, None, EPI);
15251     Sig = Context.getTrivialTypeSourceInfo(T);
15252   }
15253 
15254   // GetTypeForDeclarator always produces a function type for a block
15255   // literal signature.  Furthermore, it is always a FunctionProtoType
15256   // unless the function was written with a typedef.
15257   assert(T->isFunctionType() &&
15258          "GetTypeForDeclarator made a non-function block signature");
15259 
15260   // Look for an explicit signature in that function type.
15261   FunctionProtoTypeLoc ExplicitSignature;
15262 
15263   if ((ExplicitSignature = Sig->getTypeLoc()
15264                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
15265 
15266     // Check whether that explicit signature was synthesized by
15267     // GetTypeForDeclarator.  If so, don't save that as part of the
15268     // written signature.
15269     if (ExplicitSignature.getLocalRangeBegin() ==
15270         ExplicitSignature.getLocalRangeEnd()) {
15271       // This would be much cheaper if we stored TypeLocs instead of
15272       // TypeSourceInfos.
15273       TypeLoc Result = ExplicitSignature.getReturnLoc();
15274       unsigned Size = Result.getFullDataSize();
15275       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15276       Sig->getTypeLoc().initializeFullCopy(Result, Size);
15277 
15278       ExplicitSignature = FunctionProtoTypeLoc();
15279     }
15280   }
15281 
15282   CurBlock->TheDecl->setSignatureAsWritten(Sig);
15283   CurBlock->FunctionType = T;
15284 
15285   const FunctionType *Fn = T->getAs<FunctionType>();
15286   QualType RetTy = Fn->getReturnType();
15287   bool isVariadic =
15288     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15289 
15290   CurBlock->TheDecl->setIsVariadic(isVariadic);
15291 
15292   // Context.DependentTy is used as a placeholder for a missing block
15293   // return type.  TODO:  what should we do with declarators like:
15294   //   ^ * { ... }
15295   // If the answer is "apply template argument deduction"....
15296   if (RetTy != Context.DependentTy) {
15297     CurBlock->ReturnType = RetTy;
15298     CurBlock->TheDecl->setBlockMissingReturnType(false);
15299     CurBlock->HasImplicitReturnType = false;
15300   }
15301 
15302   // Push block parameters from the declarator if we had them.
15303   SmallVector<ParmVarDecl*, 8> Params;
15304   if (ExplicitSignature) {
15305     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15306       ParmVarDecl *Param = ExplicitSignature.getParam(I);
15307       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15308           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15309         // Diagnose this as an extension in C17 and earlier.
15310         if (!getLangOpts().C2x)
15311           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15312       }
15313       Params.push_back(Param);
15314     }
15315 
15316   // Fake up parameter variables if we have a typedef, like
15317   //   ^ fntype { ... }
15318   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15319     for (const auto &I : Fn->param_types()) {
15320       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15321           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15322       Params.push_back(Param);
15323     }
15324   }
15325 
15326   // Set the parameters on the block decl.
15327   if (!Params.empty()) {
15328     CurBlock->TheDecl->setParams(Params);
15329     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15330                              /*CheckParameterNames=*/false);
15331   }
15332 
15333   // Finally we can process decl attributes.
15334   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15335 
15336   // Put the parameter variables in scope.
15337   for (auto AI : CurBlock->TheDecl->parameters()) {
15338     AI->setOwningFunction(CurBlock->TheDecl);
15339 
15340     // If this has an identifier, add it to the scope stack.
15341     if (AI->getIdentifier()) {
15342       CheckShadow(CurBlock->TheScope, AI);
15343 
15344       PushOnScopeChains(AI, CurBlock->TheScope);
15345     }
15346   }
15347 }
15348 
15349 /// ActOnBlockError - If there is an error parsing a block, this callback
15350 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)15351 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15352   // Leave the expression-evaluation context.
15353   DiscardCleanupsInEvaluationContext();
15354   PopExpressionEvaluationContext();
15355 
15356   // Pop off CurBlock, handle nested blocks.
15357   PopDeclContext();
15358   PopFunctionScopeInfo();
15359 }
15360 
15361 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15362 /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)15363 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15364                                     Stmt *Body, Scope *CurScope) {
15365   // If blocks are disabled, emit an error.
15366   if (!LangOpts.Blocks)
15367     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15368 
15369   // Leave the expression-evaluation context.
15370   if (hasAnyUnrecoverableErrorsInThisFunction())
15371     DiscardCleanupsInEvaluationContext();
15372   assert(!Cleanup.exprNeedsCleanups() &&
15373          "cleanups within block not correctly bound!");
15374   PopExpressionEvaluationContext();
15375 
15376   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15377   BlockDecl *BD = BSI->TheDecl;
15378 
15379   if (BSI->HasImplicitReturnType)
15380     deduceClosureReturnType(*BSI);
15381 
15382   QualType RetTy = Context.VoidTy;
15383   if (!BSI->ReturnType.isNull())
15384     RetTy = BSI->ReturnType;
15385 
15386   bool NoReturn = BD->hasAttr<NoReturnAttr>();
15387   QualType BlockTy;
15388 
15389   // If the user wrote a function type in some form, try to use that.
15390   if (!BSI->FunctionType.isNull()) {
15391     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15392 
15393     FunctionType::ExtInfo Ext = FTy->getExtInfo();
15394     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15395 
15396     // Turn protoless block types into nullary block types.
15397     if (isa<FunctionNoProtoType>(FTy)) {
15398       FunctionProtoType::ExtProtoInfo EPI;
15399       EPI.ExtInfo = Ext;
15400       BlockTy = Context.getFunctionType(RetTy, None, EPI);
15401 
15402     // Otherwise, if we don't need to change anything about the function type,
15403     // preserve its sugar structure.
15404     } else if (FTy->getReturnType() == RetTy &&
15405                (!NoReturn || FTy->getNoReturnAttr())) {
15406       BlockTy = BSI->FunctionType;
15407 
15408     // Otherwise, make the minimal modifications to the function type.
15409     } else {
15410       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15411       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15412       EPI.TypeQuals = Qualifiers();
15413       EPI.ExtInfo = Ext;
15414       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15415     }
15416 
15417   // If we don't have a function type, just build one from nothing.
15418   } else {
15419     FunctionProtoType::ExtProtoInfo EPI;
15420     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15421     BlockTy = Context.getFunctionType(RetTy, None, EPI);
15422   }
15423 
15424   DiagnoseUnusedParameters(BD->parameters());
15425   BlockTy = Context.getBlockPointerType(BlockTy);
15426 
15427   // If needed, diagnose invalid gotos and switches in the block.
15428   if (getCurFunction()->NeedsScopeChecking() &&
15429       !PP.isCodeCompletionEnabled())
15430     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15431 
15432   BD->setBody(cast<CompoundStmt>(Body));
15433 
15434   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15435     DiagnoseUnguardedAvailabilityViolations(BD);
15436 
15437   // Try to apply the named return value optimization. We have to check again
15438   // if we can do this, though, because blocks keep return statements around
15439   // to deduce an implicit return type.
15440   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15441       !BD->isDependentContext())
15442     computeNRVO(Body, BSI);
15443 
15444   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15445       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15446     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15447                           NTCUK_Destruct|NTCUK_Copy);
15448 
15449   PopDeclContext();
15450 
15451   // Pop the block scope now but keep it alive to the end of this function.
15452   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15453   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15454 
15455   // Set the captured variables on the block.
15456   SmallVector<BlockDecl::Capture, 4> Captures;
15457   for (Capture &Cap : BSI->Captures) {
15458     if (Cap.isInvalid() || Cap.isThisCapture())
15459       continue;
15460 
15461     VarDecl *Var = Cap.getVariable();
15462     Expr *CopyExpr = nullptr;
15463     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15464       if (const RecordType *Record =
15465               Cap.getCaptureType()->getAs<RecordType>()) {
15466         // The capture logic needs the destructor, so make sure we mark it.
15467         // Usually this is unnecessary because most local variables have
15468         // their destructors marked at declaration time, but parameters are
15469         // an exception because it's technically only the call site that
15470         // actually requires the destructor.
15471         if (isa<ParmVarDecl>(Var))
15472           FinalizeVarWithDestructor(Var, Record);
15473 
15474         // Enter a separate potentially-evaluated context while building block
15475         // initializers to isolate their cleanups from those of the block
15476         // itself.
15477         // FIXME: Is this appropriate even when the block itself occurs in an
15478         // unevaluated operand?
15479         EnterExpressionEvaluationContext EvalContext(
15480             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15481 
15482         SourceLocation Loc = Cap.getLocation();
15483 
15484         ExprResult Result = BuildDeclarationNameExpr(
15485             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15486 
15487         // According to the blocks spec, the capture of a variable from
15488         // the stack requires a const copy constructor.  This is not true
15489         // of the copy/move done to move a __block variable to the heap.
15490         if (!Result.isInvalid() &&
15491             !Result.get()->getType().isConstQualified()) {
15492           Result = ImpCastExprToType(Result.get(),
15493                                      Result.get()->getType().withConst(),
15494                                      CK_NoOp, VK_LValue);
15495         }
15496 
15497         if (!Result.isInvalid()) {
15498           Result = PerformCopyInitialization(
15499               InitializedEntity::InitializeBlock(Var->getLocation(),
15500                                                  Cap.getCaptureType(), false),
15501               Loc, Result.get());
15502         }
15503 
15504         // Build a full-expression copy expression if initialization
15505         // succeeded and used a non-trivial constructor.  Recover from
15506         // errors by pretending that the copy isn't necessary.
15507         if (!Result.isInvalid() &&
15508             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15509                 ->isTrivial()) {
15510           Result = MaybeCreateExprWithCleanups(Result);
15511           CopyExpr = Result.get();
15512         }
15513       }
15514     }
15515 
15516     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15517                               CopyExpr);
15518     Captures.push_back(NewCap);
15519   }
15520   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15521 
15522   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15523 
15524   // If the block isn't obviously global, i.e. it captures anything at
15525   // all, then we need to do a few things in the surrounding context:
15526   if (Result->getBlockDecl()->hasCaptures()) {
15527     // First, this expression has a new cleanup object.
15528     ExprCleanupObjects.push_back(Result->getBlockDecl());
15529     Cleanup.setExprNeedsCleanups(true);
15530 
15531     // It also gets a branch-protected scope if any of the captured
15532     // variables needs destruction.
15533     for (const auto &CI : Result->getBlockDecl()->captures()) {
15534       const VarDecl *var = CI.getVariable();
15535       if (var->getType().isDestructedType() != QualType::DK_none) {
15536         setFunctionHasBranchProtectedScope();
15537         break;
15538       }
15539     }
15540   }
15541 
15542   if (getCurFunction())
15543     getCurFunction()->addBlock(BD);
15544 
15545   return Result;
15546 }
15547 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)15548 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15549                             SourceLocation RPLoc) {
15550   TypeSourceInfo *TInfo;
15551   GetTypeFromParser(Ty, &TInfo);
15552   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15553 }
15554 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)15555 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15556                                 Expr *E, TypeSourceInfo *TInfo,
15557                                 SourceLocation RPLoc) {
15558   Expr *OrigExpr = E;
15559   bool IsMS = false;
15560 
15561   // CUDA device code does not support varargs.
15562   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15563     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15564       CUDAFunctionTarget T = IdentifyCUDATarget(F);
15565       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15566         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15567     }
15568   }
15569 
15570   // NVPTX does not support va_arg expression.
15571   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15572       Context.getTargetInfo().getTriple().isNVPTX())
15573     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15574 
15575   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15576   // as Microsoft ABI on an actual Microsoft platform, where
15577   // __builtin_ms_va_list and __builtin_va_list are the same.)
15578   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15579       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15580     QualType MSVaListType = Context.getBuiltinMSVaListType();
15581     if (Context.hasSameType(MSVaListType, E->getType())) {
15582       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15583         return ExprError();
15584       IsMS = true;
15585     }
15586   }
15587 
15588   // Get the va_list type
15589   QualType VaListType = Context.getBuiltinVaListType();
15590   if (!IsMS) {
15591     if (VaListType->isArrayType()) {
15592       // Deal with implicit array decay; for example, on x86-64,
15593       // va_list is an array, but it's supposed to decay to
15594       // a pointer for va_arg.
15595       VaListType = Context.getArrayDecayedType(VaListType);
15596       // Make sure the input expression also decays appropriately.
15597       ExprResult Result = UsualUnaryConversions(E);
15598       if (Result.isInvalid())
15599         return ExprError();
15600       E = Result.get();
15601     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15602       // If va_list is a record type and we are compiling in C++ mode,
15603       // check the argument using reference binding.
15604       InitializedEntity Entity = InitializedEntity::InitializeParameter(
15605           Context, Context.getLValueReferenceType(VaListType), false);
15606       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15607       if (Init.isInvalid())
15608         return ExprError();
15609       E = Init.getAs<Expr>();
15610     } else {
15611       // Otherwise, the va_list argument must be an l-value because
15612       // it is modified by va_arg.
15613       if (!E->isTypeDependent() &&
15614           CheckForModifiableLvalue(E, BuiltinLoc, *this))
15615         return ExprError();
15616     }
15617   }
15618 
15619   if (!IsMS && !E->isTypeDependent() &&
15620       !Context.hasSameType(VaListType, E->getType()))
15621     return ExprError(
15622         Diag(E->getBeginLoc(),
15623              diag::err_first_argument_to_va_arg_not_of_type_va_list)
15624         << OrigExpr->getType() << E->getSourceRange());
15625 
15626   if (!TInfo->getType()->isDependentType()) {
15627     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15628                             diag::err_second_parameter_to_va_arg_incomplete,
15629                             TInfo->getTypeLoc()))
15630       return ExprError();
15631 
15632     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15633                                TInfo->getType(),
15634                                diag::err_second_parameter_to_va_arg_abstract,
15635                                TInfo->getTypeLoc()))
15636       return ExprError();
15637 
15638     if (!TInfo->getType().isPODType(Context)) {
15639       Diag(TInfo->getTypeLoc().getBeginLoc(),
15640            TInfo->getType()->isObjCLifetimeType()
15641              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15642              : diag::warn_second_parameter_to_va_arg_not_pod)
15643         << TInfo->getType()
15644         << TInfo->getTypeLoc().getSourceRange();
15645     }
15646 
15647     // Check for va_arg where arguments of the given type will be promoted
15648     // (i.e. this va_arg is guaranteed to have undefined behavior).
15649     QualType PromoteType;
15650     if (TInfo->getType()->isPromotableIntegerType()) {
15651       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15652       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15653         PromoteType = QualType();
15654     }
15655     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15656       PromoteType = Context.DoubleTy;
15657     if (!PromoteType.isNull())
15658       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15659                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15660                           << TInfo->getType()
15661                           << PromoteType
15662                           << TInfo->getTypeLoc().getSourceRange());
15663   }
15664 
15665   QualType T = TInfo->getType().getNonLValueExprType(Context);
15666   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15667 }
15668 
ActOnGNUNullExpr(SourceLocation TokenLoc)15669 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15670   // The type of __null will be int or long, depending on the size of
15671   // pointers on the target.
15672   QualType Ty;
15673   const auto& TI = Context.getTargetInfo();
15674   unsigned pw = TI.getPointerWidth(0);
15675   if (TI.areAllPointersCapabilities() && pw == TI.getIntCapWidth())
15676     Ty = Context.IntCapTy;
15677   else if (pw == TI.getIntWidth())
15678     Ty = Context.IntTy;
15679   else if (pw == TI.getLongWidth())
15680     Ty = Context.LongTy;
15681   else if (pw == TI.getLongLongWidth())
15682     Ty = Context.LongLongTy;
15683   else {
15684     llvm_unreachable("I don't know size of pointer!");
15685   }
15686 
15687   return new (Context) GNUNullExpr(Ty, TokenLoc);
15688 }
15689 
ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc)15690 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15691                                     SourceLocation BuiltinLoc,
15692                                     SourceLocation RPLoc) {
15693   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15694 }
15695 
BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc,DeclContext * ParentContext)15696 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15697                                     SourceLocation BuiltinLoc,
15698                                     SourceLocation RPLoc,
15699                                     DeclContext *ParentContext) {
15700   return new (Context)
15701       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15702 }
15703 
CheckConversionToObjCLiteral(QualType DstType,Expr * & Exp,bool Diagnose)15704 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15705                                         bool Diagnose) {
15706   if (!getLangOpts().ObjC)
15707     return false;
15708 
15709   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15710   if (!PT)
15711     return false;
15712   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15713 
15714   // Ignore any parens, implicit casts (should only be
15715   // array-to-pointer decays), and not-so-opaque values.  The last is
15716   // important for making this trigger for property assignments.
15717   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15718   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15719     if (OV->getSourceExpr())
15720       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15721 
15722   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15723     if (!PT->isObjCIdType() &&
15724         !(ID && ID->getIdentifier()->isStr("NSString")))
15725       return false;
15726     if (!SL->isAscii())
15727       return false;
15728 
15729     if (Diagnose) {
15730       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15731           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15732       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15733     }
15734     return true;
15735   }
15736 
15737   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15738       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15739       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15740       !SrcExpr->isNullPointerConstant(
15741           getASTContext(), Expr::NPC_NeverValueDependent)) {
15742     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15743       return false;
15744     if (Diagnose) {
15745       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15746           << /*number*/1
15747           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15748       Expr *NumLit =
15749           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15750       if (NumLit)
15751         Exp = NumLit;
15752     }
15753     return true;
15754   }
15755 
15756   return false;
15757 }
15758 
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)15759 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15760                                               const Expr *SrcExpr) {
15761   if (!DstType->isFunctionPointerType() ||
15762       !SrcExpr->getType()->isFunctionType())
15763     return false;
15764 
15765   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15766   if (!DRE)
15767     return false;
15768 
15769   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15770   if (!FD)
15771     return false;
15772 
15773   return !S.checkAddressOfFunctionIsAvailable(FD,
15774                                               /*Complain=*/true,
15775                                               SrcExpr->getBeginLoc());
15776 }
15777 
diagnoseBadVariadicFunctionPointerAssignment(Sema & S,SourceLocation Loc,QualType SrcType,QualType DstType,Expr * SrcExpr)15778 static void diagnoseBadVariadicFunctionPointerAssignment(Sema &S,
15779                                                          SourceLocation Loc,
15780                                                          QualType SrcType,
15781                                                          QualType DstType,
15782                                                          Expr* SrcExpr) {
15783   const FunctionType *DstFnTy =
15784       DstType->getPointeeType()->getAs<FunctionType>();
15785 
15786   const FunctionType *SrcFnTy = nullptr;
15787   if (SrcType->isFunctionPointerType())
15788     SrcFnTy = SrcType->getPointeeType()->getAs<FunctionType>();
15789   else
15790     SrcFnTy = SrcType->getAs<FunctionType>();
15791   // TODO: also diagnose any variadic to non-variadic
15792   // TODO: don't warn about zero-arg function
15793   if (!SrcFnTy)
15794     return; // Should give an invalid pointer to function warning anyway
15795 
15796   FunctionDecl* FuncDecl = nullptr;
15797   // Avoid warnings for K&R functions where we actually know the prototype:
15798   if (auto *UO = dyn_cast<UnaryOperator>(SrcExpr->IgnoreImplicit())) {
15799     // look through &foo to find the actual function
15800     if (UO->getOpcode() == UO_AddrOf)
15801       SrcExpr = UO->getSubExpr();
15802   }
15803   if (auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreImplicit())) {
15804     FuncDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
15805   }
15806 
15807   enum class CCType { NoProto, Variadic, FixedArg, Invalid };
15808   CCType SrcCCType = CCType::Invalid;
15809   if (SrcFnTy->isFunctionNoProtoType()) {
15810     // Type is noproto but we might have a decl with the real prototype:
15811     if (FuncDecl)
15812       SrcFnTy = FuncDecl->getType()->getAs<FunctionType>();
15813     // Now check again to see if it is still a noproto type
15814     if (SrcFnTy->isFunctionNoProtoType())
15815       SrcCCType = CCType::NoProto;
15816   }
15817   if (auto *SrcProto = SrcFnTy->getAs<FunctionProtoType>()) {
15818     // assigning a function without parameters is fine since there will never be
15819     // any confusion between on-stack and in-register arguments
15820     if (SrcProto->getNumParams() == 0)
15821       return;
15822     SrcCCType = SrcProto->isVariadic() ? CCType::Variadic : CCType::FixedArg;
15823   }
15824   CCType DstCCType = CCType::Invalid;
15825   if (DstFnTy->isFunctionNoProtoType())
15826     DstCCType = CCType::NoProto;
15827   else if (auto *DstProto = DstFnTy->getAs<FunctionProtoType>()) {
15828     DstCCType = DstProto->isVariadic() ? CCType::Variadic : CCType::FixedArg;
15829   }
15830   assert(SrcCCType != CCType::Invalid);
15831   assert(DstCCType != CCType::Invalid);
15832 
15833   if (SrcCCType != DstCCType) {
15834     // converting variadic to non-variadic is an error by default, the other is
15835     // a pedantic warning that is often a false positive
15836     unsigned DiagID = diag::warn_cheri_fnptr_proto_noproto_conversion;
15837     unsigned ExplainID = diag::note_cheri_func_noproto_explanation;
15838     if (SrcCCType == CCType::Variadic || DstCCType == CCType::Variadic) {
15839       DiagID = diag::warn_cheri_fnptr_variadic_nonvariadic_conversion;
15840       ExplainID = diag::note_cheri_func_variadic_explanation;
15841     }
15842     S.Diag(Loc, DiagID) << (int)SrcCCType << SrcType << (int)DstCCType
15843                         << DstType;
15844     S.Diag(Loc, ExplainID);
15845     if (FuncDecl)
15846       S.Diag(FuncDecl->getBeginLoc(), diag::note_callee_decl) << FuncDecl;
15847   }
15848 }
15849 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)15850 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15851                                     SourceLocation Loc,
15852                                     QualType DstType, QualType SrcType,
15853                                     Expr *SrcExpr, AssignmentAction Action,
15854                                     bool *Complained) {
15855   if (Complained)
15856     *Complained = false;
15857 
15858   // Decode the result (notice that AST's are still created for extensions).
15859   bool CheckInferredResultType = false;
15860   bool isInvalid = false;
15861   unsigned DiagKind = 0;
15862   FixItHint Hint;
15863   ConversionFixItGenerator ConvHints;
15864   bool MayHaveConvFixit = false;
15865   bool MayHaveFunctionDiff = false;
15866   const ObjCInterfaceDecl *IFace = nullptr;
15867   const ObjCProtocolDecl *PDecl = nullptr;
15868 
15869   // Warn when assigning non-variadic functions to variadic function pointers
15870   // and the other way around
15871   // TODO: this should probably be upstreamed as it is not CHERI specific
15872   // TODO: only for Context.getTargetInfo().areAllPointersCapabilities()?
15873   // Note: we need to do this even if ConvTy == compatible since pointers without
15874   // prototypes can be assigned to from any function pointer type
15875   if (DstType->isFunctionPointerType())
15876     diagnoseBadVariadicFunctionPointerAssignment(*this, Loc, SrcType, DstType, SrcExpr);
15877 
15878   switch (ConvTy) {
15879   case Compatible:
15880       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15881       return false;
15882 
15883   case PointerToInt:
15884     if (getLangOpts().CPlusPlus) {
15885       DiagKind = diag::err_typecheck_convert_pointer_int;
15886       isInvalid = true;
15887     } else {
15888       DiagKind = diag::ext_typecheck_convert_pointer_int;
15889     }
15890     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15891     MayHaveConvFixit = true;
15892     break;
15893   case IntToPointer:
15894     if (getLangOpts().CPlusPlus) {
15895       DiagKind = diag::err_typecheck_convert_int_pointer;
15896       isInvalid = true;
15897     } else {
15898       DiagKind = diag::ext_typecheck_convert_int_pointer;
15899     }
15900     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15901     MayHaveConvFixit = true;
15902     break;
15903   case IncompatibleFunctionPointer:
15904     if (getLangOpts().CPlusPlus) {
15905       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15906       isInvalid = true;
15907     } else {
15908       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15909     }
15910     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15911     MayHaveConvFixit = true;
15912     break;
15913   case IncompatiblePointer:
15914     if (Action == AA_Passing_CFAudited) {
15915       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15916     } else if (getLangOpts().CPlusPlus) {
15917       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15918       isInvalid = true;
15919     } else {
15920       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15921     }
15922     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15923       SrcType->isObjCObjectPointerType();
15924     if (Hint.isNull() && !CheckInferredResultType) {
15925       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15926     }
15927     else if (CheckInferredResultType) {
15928       SrcType = SrcType.getUnqualifiedType();
15929       DstType = DstType.getUnqualifiedType();
15930     }
15931     MayHaveConvFixit = true;
15932     break;
15933   case IncompatiblePointerSign:
15934     if (getLangOpts().CPlusPlus) {
15935       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15936       isInvalid = true;
15937     } else {
15938       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15939     }
15940     break;
15941   case FunctionVoidPointer:
15942     if (getLangOpts().CPlusPlus) {
15943       DiagKind = diag::err_typecheck_convert_pointer_void_func;
15944       isInvalid = true;
15945     } else {
15946       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15947     }
15948     break;
15949   case IncompatiblePointerDiscardsQualifiers: {
15950     // Perform array-to-pointer decay if necessary.
15951     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15952 
15953     isInvalid = true;
15954 
15955     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15956     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15957     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15958       DiagKind = diag::err_typecheck_incompatible_address_space;
15959       break;
15960 
15961     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15962       DiagKind = diag::err_typecheck_incompatible_ownership;
15963       break;
15964     }
15965 
15966     llvm_unreachable("unknown error case for discarding qualifiers!");
15967     // fallthrough
15968   }
15969   case CompatiblePointerDiscardsQualifiers:
15970     // If the qualifiers lost were because we were applying the
15971     // (deprecated) C++ conversion from a string literal to a char*
15972     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
15973     // Ideally, this check would be performed in
15974     // checkPointerTypesForAssignment. However, that would require a
15975     // bit of refactoring (so that the second argument is an
15976     // expression, rather than a type), which should be done as part
15977     // of a larger effort to fix checkPointerTypesForAssignment for
15978     // C++ semantics.
15979     if (getLangOpts().CPlusPlus &&
15980         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15981       return false;
15982     if (getLangOpts().CPlusPlus) {
15983       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
15984       isInvalid = true;
15985     } else {
15986       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
15987     }
15988 
15989     break;
15990   case IncompatibleNestedPointerQualifiers:
15991     if (getLangOpts().CPlusPlus) {
15992       isInvalid = true;
15993       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15994     } else {
15995       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15996     }
15997     break;
15998   case IncompatibleNestedPointerAddressSpaceMismatch:
15999     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16000     isInvalid = true;
16001     break;
16002   case IntToBlockPointer:
16003     DiagKind = diag::err_int_to_block_pointer;
16004     isInvalid = true;
16005     break;
16006   case IncompatibleBlockPointer:
16007     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16008     isInvalid = true;
16009     break;
16010   case IncompatibleObjCQualifiedId: {
16011     if (SrcType->isObjCQualifiedIdType()) {
16012       const ObjCObjectPointerType *srcOPT =
16013                 SrcType->castAs<ObjCObjectPointerType>();
16014       for (auto *srcProto : srcOPT->quals()) {
16015         PDecl = srcProto;
16016         break;
16017       }
16018       if (const ObjCInterfaceType *IFaceT =
16019             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16020         IFace = IFaceT->getDecl();
16021     }
16022     else if (DstType->isObjCQualifiedIdType()) {
16023       const ObjCObjectPointerType *dstOPT =
16024         DstType->castAs<ObjCObjectPointerType>();
16025       for (auto *dstProto : dstOPT->quals()) {
16026         PDecl = dstProto;
16027         break;
16028       }
16029       if (const ObjCInterfaceType *IFaceT =
16030             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16031         IFace = IFaceT->getDecl();
16032     }
16033     if (getLangOpts().CPlusPlus) {
16034       DiagKind = diag::err_incompatible_qualified_id;
16035       isInvalid = true;
16036     } else {
16037       DiagKind = diag::warn_incompatible_qualified_id;
16038     }
16039     break;
16040   }
16041   case IncompatibleVectors:
16042     if (getLangOpts().CPlusPlus) {
16043       DiagKind = diag::err_incompatible_vectors;
16044       isInvalid = true;
16045     } else {
16046       DiagKind = diag::warn_incompatible_vectors;
16047     }
16048     break;
16049   case IncompatibleObjCWeakRef:
16050     DiagKind = diag::err_arc_weak_unavailable_assign;
16051     isInvalid = true;
16052     break;
16053   case CHERICapabilityToPointer:
16054   case PointerToCHERICapability: {
16055     bool PtrToCap = ConvTy == PointerToCHERICapability;
16056     if (PtrToCap) {
16057       // Some implicit conversions are permitted for pointer -> cap
16058       if (ImpCastPointerToCHERICapability(SrcType, DstType, SrcExpr, false))
16059         return false;
16060     }
16061 
16062     // If we reach here, output an error
16063     DiagKind = PtrToCap ? diag::err_typecheck_convert_ptr_to_cap
16064                         : diag::err_typecheck_convert_cap_to_ptr;
16065     MayHaveConvFixit = true;
16066     isInvalid = true;
16067     Hint = FixItHint::CreateInsertion(
16068         SrcExpr->getBeginLoc(), "(__cheri_" +
16069                                     std::string(PtrToCap ? "to" : "from") +
16070                                     "cap " + DstType.getAsString() + ")");
16071     Diag(Loc, DiagKind) << SrcType << DstType << false << Hint;
16072     if (Complained)
16073       *Complained = true;
16074     return true;
16075   }
16076   case Incompatible:
16077     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16078       if (Complained)
16079         *Complained = true;
16080       return true;
16081     }
16082 
16083     DiagKind = diag::err_typecheck_convert_incompatible;
16084     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16085     MayHaveConvFixit = true;
16086     isInvalid = true;
16087     MayHaveFunctionDiff = true;
16088     break;
16089   }
16090 
16091   QualType FirstType, SecondType;
16092   switch (Action) {
16093   case AA_Assigning:
16094   case AA_Initializing:
16095     // The destination type comes first.
16096     FirstType = DstType;
16097     SecondType = SrcType;
16098     break;
16099 
16100   case AA_Returning:
16101   case AA_Passing:
16102   case AA_Passing_CFAudited:
16103   case AA_Converting:
16104   case AA_Sending:
16105   case AA_Casting:
16106     // The source type comes first.
16107     FirstType = SrcType;
16108     SecondType = DstType;
16109     break;
16110   }
16111 
16112   PartialDiagnostic FDiag = PDiag(DiagKind);
16113   if (Action == AA_Passing_CFAudited)
16114     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16115   else
16116     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16117 
16118   // If we can fix the conversion, suggest the FixIts.
16119   assert(ConvHints.isNull() || Hint.isNull());
16120   if (!ConvHints.isNull()) {
16121     for (FixItHint &H : ConvHints.Hints)
16122       FDiag << H;
16123   } else {
16124     FDiag << Hint;
16125   }
16126   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16127 
16128   if (MayHaveFunctionDiff)
16129     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16130 
16131   Diag(Loc, FDiag);
16132   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16133        DiagKind == diag::err_incompatible_qualified_id) &&
16134       PDecl && IFace && !IFace->hasDefinition())
16135     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16136         << IFace << PDecl;
16137 
16138   if (SecondType == Context.OverloadTy)
16139     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16140                               FirstType, /*TakingAddress=*/true);
16141 
16142   if (CheckInferredResultType)
16143     EmitRelatedResultTypeNote(SrcExpr);
16144 
16145   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16146     EmitRelatedResultTypeNoteForReturn(DstType);
16147 
16148   if (Complained)
16149     *Complained = true;
16150   return isInvalid;
16151 }
16152 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)16153 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16154                                                  llvm::APSInt *Result) {
16155   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16156   public:
16157     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
16158       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
16159     }
16160   } Diagnoser;
16161 
16162   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
16163 }
16164 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)16165 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16166                                                  llvm::APSInt *Result,
16167                                                  unsigned DiagID,
16168                                                  bool AllowFold) {
16169   class IDDiagnoser : public VerifyICEDiagnoser {
16170     unsigned DiagID;
16171 
16172   public:
16173     IDDiagnoser(unsigned DiagID)
16174       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16175 
16176     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
16177       S.Diag(Loc, DiagID) << SR;
16178     }
16179   } Diagnoser(DiagID);
16180 
16181   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
16182 }
16183 
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)16184 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
16185                                             SourceRange SR) {
16186   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
16187 }
16188 
16189 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)16190 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16191                                       VerifyICEDiagnoser &Diagnoser,
16192                                       bool AllowFold) {
16193   SourceLocation DiagLoc = E->getBeginLoc();
16194 
16195   if (getLangOpts().CPlusPlus11) {
16196     // C++11 [expr.const]p5:
16197     //   If an expression of literal class type is used in a context where an
16198     //   integral constant expression is required, then that class type shall
16199     //   have a single non-explicit conversion function to an integral or
16200     //   unscoped enumeration type
16201     ExprResult Converted;
16202     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16203     public:
16204       CXX11ConvertDiagnoser(bool Silent)
16205           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
16206                                 Silent, true) {}
16207 
16208       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16209                                            QualType T) override {
16210         return S.Diag(Loc, diag::err_ice_not_integral) << T;
16211       }
16212 
16213       SemaDiagnosticBuilder diagnoseIncomplete(
16214           Sema &S, SourceLocation Loc, QualType T) override {
16215         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16216       }
16217 
16218       SemaDiagnosticBuilder diagnoseExplicitConv(
16219           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16220         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16221       }
16222 
16223       SemaDiagnosticBuilder noteExplicitConv(
16224           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16225         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16226                  << ConvTy->isEnumeralType() << ConvTy;
16227       }
16228 
16229       SemaDiagnosticBuilder diagnoseAmbiguous(
16230           Sema &S, SourceLocation Loc, QualType T) override {
16231         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16232       }
16233 
16234       SemaDiagnosticBuilder noteAmbiguous(
16235           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16236         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16237                  << ConvTy->isEnumeralType() << ConvTy;
16238       }
16239 
16240       SemaDiagnosticBuilder diagnoseConversion(
16241           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16242         llvm_unreachable("conversion functions are permitted");
16243       }
16244     } ConvertDiagnoser(Diagnoser.Suppress);
16245 
16246     Converted = PerformContextualImplicitConversion(DiagLoc, E,
16247                                                     ConvertDiagnoser);
16248     if (Converted.isInvalid())
16249       return Converted;
16250     E = Converted.get();
16251     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16252       return ExprError();
16253   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16254     // An ICE must be of integral or unscoped enumeration type.
16255     if (!Diagnoser.Suppress)
16256       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
16257     return ExprError();
16258   }
16259 
16260   ExprResult RValueExpr = DefaultLvalueConversion(E);
16261   if (RValueExpr.isInvalid())
16262     return ExprError();
16263 
16264   E = RValueExpr.get();
16265 
16266   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16267   // in the non-ICE case.
16268   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16269     if (Result)
16270       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16271     if (!isa<ConstantExpr>(E))
16272       E = ConstantExpr::Create(Context, E);
16273     return E;
16274   }
16275 
16276   Expr::EvalResult EvalResult;
16277   SmallVector<PartialDiagnosticAt, 8> Notes;
16278   EvalResult.Diag = &Notes;
16279 
16280   // Try to evaluate the expression, and produce diagnostics explaining why it's
16281   // not a constant expression as a side-effect.
16282   bool Folded =
16283       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16284       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16285 
16286   if (!isa<ConstantExpr>(E))
16287     E = ConstantExpr::Create(Context, E, EvalResult.Val);
16288 
16289   // In C++11, we can rely on diagnostics being produced for any expression
16290   // which is not a constant expression. If no diagnostics were produced, then
16291   // this is a constant expression.
16292   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16293     if (Result)
16294       *Result = EvalResult.Val.getInt();
16295     return E;
16296   }
16297 
16298   // If our only note is the usual "invalid subexpression" note, just point
16299   // the caret at its location rather than producing an essentially
16300   // redundant note.
16301   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16302         diag::note_invalid_subexpr_in_const_expr) {
16303     DiagLoc = Notes[0].first;
16304     Notes.clear();
16305   }
16306 
16307   if (!Folded || !AllowFold) {
16308     if (!Diagnoser.Suppress) {
16309       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
16310       for (const PartialDiagnosticAt &Note : Notes)
16311         Diag(Note.first, Note.second);
16312     }
16313 
16314     return ExprError();
16315   }
16316 
16317   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
16318   for (const PartialDiagnosticAt &Note : Notes)
16319     Diag(Note.first, Note.second);
16320 
16321   if (Result)
16322     *Result = EvalResult.Val.getInt();
16323   return E;
16324 }
16325 
16326 namespace {
16327   // Handle the case where we conclude a expression which we speculatively
16328   // considered to be unevaluated is actually evaluated.
16329   class TransformToPE : public TreeTransform<TransformToPE> {
16330     typedef TreeTransform<TransformToPE> BaseTransform;
16331 
16332   public:
TransformToPE(Sema & SemaRef)16333     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16334 
16335     // Make sure we redo semantic analysis
AlwaysRebuild()16336     bool AlwaysRebuild() { return true; }
ReplacingOriginal()16337     bool ReplacingOriginal() { return true; }
16338 
16339     // We need to special-case DeclRefExprs referring to FieldDecls which
16340     // are not part of a member pointer formation; normal TreeTransforming
16341     // doesn't catch this case because of the way we represent them in the AST.
16342     // FIXME: This is a bit ugly; is it really the best way to handle this
16343     // case?
16344     //
16345     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)16346     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16347       if (isa<FieldDecl>(E->getDecl()) &&
16348           !SemaRef.isUnevaluatedContext())
16349         return SemaRef.Diag(E->getLocation(),
16350                             diag::err_invalid_non_static_member_use)
16351             << E->getDecl() << E->getSourceRange();
16352 
16353       return BaseTransform::TransformDeclRefExpr(E);
16354     }
16355 
16356     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)16357     ExprResult TransformUnaryOperator(UnaryOperator *E) {
16358       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16359         return E;
16360 
16361       return BaseTransform::TransformUnaryOperator(E);
16362     }
16363 
16364     // The body of a lambda-expression is in a separate expression evaluation
16365     // context so never needs to be transformed.
16366     // FIXME: Ideally we wouldn't transform the closure type either, and would
16367     // just recreate the capture expressions and lambda expression.
TransformLambdaBody(LambdaExpr * E,Stmt * Body)16368     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16369       return SkipLambdaBody(E, Body);
16370     }
16371   };
16372 }
16373 
TransformToPotentiallyEvaluated(Expr * E)16374 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16375   assert(isUnevaluatedContext() &&
16376          "Should only transform unevaluated expressions");
16377   ExprEvalContexts.back().Context =
16378       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16379   if (isUnevaluatedContext())
16380     return E;
16381   return TransformToPE(*this).TransformExpr(E);
16382 }
16383 
16384 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16385 Sema::PushExpressionEvaluationContext(
16386     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16387     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16388   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16389                                 LambdaContextDecl, ExprContext);
16390   Cleanup.reset();
16391   if (!MaybeODRUseExprs.empty())
16392     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16393 }
16394 
16395 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16396 Sema::PushExpressionEvaluationContext(
16397     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16398     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16399   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16400   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16401 }
16402 
16403 namespace {
16404 
CheckPossibleDeref(Sema & S,const Expr * PossibleDeref)16405 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16406   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16407   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16408     if (E->getOpcode() == UO_Deref)
16409       return CheckPossibleDeref(S, E->getSubExpr());
16410   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16411     return CheckPossibleDeref(S, E->getBase());
16412   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16413     return CheckPossibleDeref(S, E->getBase());
16414   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16415     QualType Inner;
16416     QualType Ty = E->getType();
16417     if (const auto *Ptr = Ty->getAs<PointerType>())
16418       Inner = Ptr->getPointeeType();
16419     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16420       Inner = Arr->getElementType();
16421     else
16422       return nullptr;
16423 
16424     if (Inner->hasAttr(attr::NoDeref))
16425       return E;
16426   }
16427   return nullptr;
16428 }
16429 
16430 } // namespace
16431 
WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord & Rec)16432 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16433   for (const Expr *E : Rec.PossibleDerefs) {
16434     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16435     if (DeclRef) {
16436       const ValueDecl *Decl = DeclRef->getDecl();
16437       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16438           << Decl->getName() << E->getSourceRange();
16439       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16440     } else {
16441       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16442           << E->getSourceRange();
16443     }
16444   }
16445   Rec.PossibleDerefs.clear();
16446 }
16447 
16448 /// Check whether E, which is either a discarded-value expression or an
16449 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16450 /// and if so, remove it from the list of volatile-qualified assignments that
16451 /// we are going to warn are deprecated.
CheckUnusedVolatileAssignment(Expr * E)16452 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16453   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16454     return;
16455 
16456   // Note: ignoring parens here is not justified by the standard rules, but
16457   // ignoring parentheses seems like a more reasonable approach, and this only
16458   // drives a deprecation warning so doesn't affect conformance.
16459   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16460     if (BO->getOpcode() == BO_Assign) {
16461       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16462       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16463                  LHSs.end());
16464     }
16465   }
16466 }
16467 
CheckForImmediateInvocation(ExprResult E,FunctionDecl * Decl)16468 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16469   if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16470       RebuildingImmediateInvocation)
16471     return E;
16472 
16473   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16474   /// It's OK if this fails; we'll also remove this in
16475   /// HandleImmediateInvocations, but catching it here allows us to avoid
16476   /// walking the AST looking for it in simple cases.
16477   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16478     if (auto *DeclRef =
16479             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16480       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16481 
16482   E = MaybeCreateExprWithCleanups(E);
16483 
16484   ConstantExpr *Res = ConstantExpr::Create(
16485       getASTContext(), E.get(),
16486       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16487                                    getASTContext()),
16488       /*IsImmediateInvocation*/ true);
16489   ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16490   return Res;
16491 }
16492 
EvaluateAndDiagnoseImmediateInvocation(Sema & SemaRef,Sema::ImmediateInvocationCandidate Candidate)16493 static void EvaluateAndDiagnoseImmediateInvocation(
16494     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16495   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16496   Expr::EvalResult Eval;
16497   Eval.Diag = &Notes;
16498   ConstantExpr *CE = Candidate.getPointer();
16499   bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16500                                            SemaRef.getASTContext(), true);
16501   if (!Result || !Notes.empty()) {
16502     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16503     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16504       InnerExpr = FunctionalCast->getSubExpr();
16505     FunctionDecl *FD = nullptr;
16506     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16507       FD = cast<FunctionDecl>(Call->getCalleeDecl());
16508     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16509       FD = Call->getConstructor();
16510     else
16511       llvm_unreachable("unhandled decl kind");
16512     assert(FD->isConsteval());
16513     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16514     for (auto &Note : Notes)
16515       SemaRef.Diag(Note.first, Note.second);
16516     return;
16517   }
16518   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16519 }
16520 
RemoveNestedImmediateInvocation(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec,SmallVector<Sema::ImmediateInvocationCandidate,4>::reverse_iterator It)16521 static void RemoveNestedImmediateInvocation(
16522     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16523     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16524   struct ComplexRemove : TreeTransform<ComplexRemove> {
16525     using Base = TreeTransform<ComplexRemove>;
16526     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16527     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16528     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16529         CurrentII;
16530     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16531                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16532                   SmallVector<Sema::ImmediateInvocationCandidate,
16533                               4>::reverse_iterator Current)
16534         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16535     void RemoveImmediateInvocation(ConstantExpr* E) {
16536       auto It = std::find_if(CurrentII, IISet.rend(),
16537                              [E](Sema::ImmediateInvocationCandidate Elem) {
16538                                return Elem.getPointer() == E;
16539                              });
16540       assert(It != IISet.rend() &&
16541              "ConstantExpr marked IsImmediateInvocation should "
16542              "be present");
16543       It->setInt(1); // Mark as deleted
16544     }
16545     ExprResult TransformConstantExpr(ConstantExpr *E) {
16546       if (!E->isImmediateInvocation())
16547         return Base::TransformConstantExpr(E);
16548       RemoveImmediateInvocation(E);
16549       return Base::TransformExpr(E->getSubExpr());
16550     }
16551     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16552     /// we need to remove its DeclRefExpr from the DRSet.
16553     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16554       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16555       return Base::TransformCXXOperatorCallExpr(E);
16556     }
16557     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16558     /// here.
16559     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16560       if (!Init)
16561         return Init;
16562       /// ConstantExpr are the first layer of implicit node to be removed so if
16563       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16564       if (auto *CE = dyn_cast<ConstantExpr>(Init))
16565         if (CE->isImmediateInvocation())
16566           RemoveImmediateInvocation(CE);
16567       return Base::TransformInitializer(Init, NotCopyInit);
16568     }
16569     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16570       DRSet.erase(E);
16571       return E;
16572     }
16573     bool AlwaysRebuild() { return false; }
16574     bool ReplacingOriginal() { return true; }
16575     bool AllowSkippingCXXConstructExpr() {
16576       bool Res = AllowSkippingFirstCXXConstructExpr;
16577       AllowSkippingFirstCXXConstructExpr = true;
16578       return Res;
16579     }
16580     bool AllowSkippingFirstCXXConstructExpr = true;
16581   } Transformer(SemaRef, Rec.ReferenceToConsteval,
16582                 Rec.ImmediateInvocationCandidates, It);
16583 
16584   /// CXXConstructExpr with a single argument are getting skipped by
16585   /// TreeTransform in some situtation because they could be implicit. This
16586   /// can only occur for the top-level CXXConstructExpr because it is used
16587   /// nowhere in the expression being transformed therefore will not be rebuilt.
16588   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16589   /// skipping the first CXXConstructExpr.
16590   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16591     Transformer.AllowSkippingFirstCXXConstructExpr = false;
16592 
16593   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16594   assert(Res.isUsable());
16595   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16596   It->getPointer()->setSubExpr(Res.get());
16597 }
16598 
16599 static void
HandleImmediateInvocations(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec)16600 HandleImmediateInvocations(Sema &SemaRef,
16601                            Sema::ExpressionEvaluationContextRecord &Rec) {
16602   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16603        Rec.ReferenceToConsteval.size() == 0) ||
16604       SemaRef.RebuildingImmediateInvocation)
16605     return;
16606 
16607   /// When we have more then 1 ImmediateInvocationCandidates we need to check
16608   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16609   /// need to remove ReferenceToConsteval in the immediate invocation.
16610   if (Rec.ImmediateInvocationCandidates.size() > 1) {
16611 
16612     /// Prevent sema calls during the tree transform from adding pointers that
16613     /// are already in the sets.
16614     llvm::SaveAndRestore<bool> DisableIITracking(
16615         SemaRef.RebuildingImmediateInvocation, true);
16616 
16617     /// Prevent diagnostic during tree transfrom as they are duplicates
16618     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16619 
16620     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16621          It != Rec.ImmediateInvocationCandidates.rend(); It++)
16622       if (!It->getInt())
16623         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16624   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16625              Rec.ReferenceToConsteval.size()) {
16626     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16627       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16628       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16629       bool VisitDeclRefExpr(DeclRefExpr *E) {
16630         DRSet.erase(E);
16631         return DRSet.size();
16632       }
16633     } Visitor(Rec.ReferenceToConsteval);
16634     Visitor.TraverseStmt(
16635         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16636   }
16637   for (auto CE : Rec.ImmediateInvocationCandidates)
16638     if (!CE.getInt())
16639       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16640   for (auto DR : Rec.ReferenceToConsteval) {
16641     auto *FD = cast<FunctionDecl>(DR->getDecl());
16642     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16643         << FD;
16644     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16645   }
16646 }
16647 
PopExpressionEvaluationContext()16648 void Sema::PopExpressionEvaluationContext() {
16649   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16650   unsigned NumTypos = Rec.NumTypos;
16651 
16652   if (!Rec.Lambdas.empty()) {
16653     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16654     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16655         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16656       unsigned D;
16657       if (Rec.isUnevaluated()) {
16658         // C++11 [expr.prim.lambda]p2:
16659         //   A lambda-expression shall not appear in an unevaluated operand
16660         //   (Clause 5).
16661         D = diag::err_lambda_unevaluated_operand;
16662       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16663         // C++1y [expr.const]p2:
16664         //   A conditional-expression e is a core constant expression unless the
16665         //   evaluation of e, following the rules of the abstract machine, would
16666         //   evaluate [...] a lambda-expression.
16667         D = diag::err_lambda_in_constant_expression;
16668       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16669         // C++17 [expr.prim.lamda]p2:
16670         // A lambda-expression shall not appear [...] in a template-argument.
16671         D = diag::err_lambda_in_invalid_context;
16672       } else
16673         llvm_unreachable("Couldn't infer lambda error message.");
16674 
16675       for (const auto *L : Rec.Lambdas)
16676         Diag(L->getBeginLoc(), D);
16677     }
16678   }
16679 
16680   WarnOnPendingNoDerefs(Rec);
16681   HandleImmediateInvocations(*this, Rec);
16682 
16683   // Warn on any volatile-qualified simple-assignments that are not discarded-
16684   // value expressions nor unevaluated operands (those cases get removed from
16685   // this list by CheckUnusedVolatileAssignment).
16686   for (auto *BO : Rec.VolatileAssignmentLHSs)
16687     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16688         << BO->getType();
16689 
16690   // When are coming out of an unevaluated context, clear out any
16691   // temporaries that we may have created as part of the evaluation of
16692   // the expression in that context: they aren't relevant because they
16693   // will never be constructed.
16694   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16695     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16696                              ExprCleanupObjects.end());
16697     Cleanup = Rec.ParentCleanup;
16698     CleanupVarDeclMarking();
16699     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16700   // Otherwise, merge the contexts together.
16701   } else {
16702     Cleanup.mergeFrom(Rec.ParentCleanup);
16703     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16704                             Rec.SavedMaybeODRUseExprs.end());
16705   }
16706 
16707   // Pop the current expression evaluation context off the stack.
16708   ExprEvalContexts.pop_back();
16709 
16710   // The global expression evaluation context record is never popped.
16711   ExprEvalContexts.back().NumTypos += NumTypos;
16712 }
16713 
DiscardCleanupsInEvaluationContext()16714 void Sema::DiscardCleanupsInEvaluationContext() {
16715   ExprCleanupObjects.erase(
16716          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16717          ExprCleanupObjects.end());
16718   Cleanup.reset();
16719   MaybeODRUseExprs.clear();
16720 }
16721 
HandleExprEvaluationContextForTypeof(Expr * E)16722 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16723   ExprResult Result = CheckPlaceholderExpr(E);
16724   if (Result.isInvalid())
16725     return ExprError();
16726   E = Result.get();
16727   if (!E->getType()->isVariablyModifiedType())
16728     return E;
16729   return TransformToPotentiallyEvaluated(E);
16730 }
16731 
16732 /// Are we in a context that is potentially constant evaluated per C++20
16733 /// [expr.const]p12?
isPotentiallyConstantEvaluatedContext(Sema & SemaRef)16734 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16735   /// C++2a [expr.const]p12:
16736   //   An expression or conversion is potentially constant evaluated if it is
16737   switch (SemaRef.ExprEvalContexts.back().Context) {
16738     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16739       // -- a manifestly constant-evaluated expression,
16740     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16741     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16742     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16743       // -- a potentially-evaluated expression,
16744     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16745       // -- an immediate subexpression of a braced-init-list,
16746 
16747       // -- [FIXME] an expression of the form & cast-expression that occurs
16748       //    within a templated entity
16749       // -- a subexpression of one of the above that is not a subexpression of
16750       // a nested unevaluated operand.
16751       return true;
16752 
16753     case Sema::ExpressionEvaluationContext::Unevaluated:
16754     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16755       // Expressions in this context are never evaluated.
16756       return false;
16757   }
16758   llvm_unreachable("Invalid context");
16759 }
16760 
16761 /// Return true if this function has a calling convention that requires mangling
16762 /// in the size of the parameter pack.
funcHasParameterSizeMangling(Sema & S,FunctionDecl * FD)16763 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16764   // These manglings don't do anything on non-Windows or non-x86 platforms, so
16765   // we don't need parameter type sizes.
16766   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16767   if (!TT.isOSWindows() || !TT.isX86())
16768     return false;
16769 
16770   // If this is C++ and this isn't an extern "C" function, parameters do not
16771   // need to be complete. In this case, C++ mangling will apply, which doesn't
16772   // use the size of the parameters.
16773   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16774     return false;
16775 
16776   // Stdcall, fastcall, and vectorcall need this special treatment.
16777   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16778   switch (CC) {
16779   case CC_X86StdCall:
16780   case CC_X86FastCall:
16781   case CC_X86VectorCall:
16782     return true;
16783   default:
16784     break;
16785   }
16786   return false;
16787 }
16788 
16789 /// Require that all of the parameter types of function be complete. Normally,
16790 /// parameter types are only required to be complete when a function is called
16791 /// or defined, but to mangle functions with certain calling conventions, the
16792 /// mangler needs to know the size of the parameter list. In this situation,
16793 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16794 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16795 /// result in a linker error. Clang doesn't implement this behavior, and instead
16796 /// attempts to error at compile time.
CheckCompleteParameterTypesForMangler(Sema & S,FunctionDecl * FD,SourceLocation Loc)16797 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16798                                                   SourceLocation Loc) {
16799   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16800     FunctionDecl *FD;
16801     ParmVarDecl *Param;
16802 
16803   public:
16804     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16805         : FD(FD), Param(Param) {}
16806 
16807     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16808       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16809       StringRef CCName;
16810       switch (CC) {
16811       case CC_X86StdCall:
16812         CCName = "stdcall";
16813         break;
16814       case CC_X86FastCall:
16815         CCName = "fastcall";
16816         break;
16817       case CC_X86VectorCall:
16818         CCName = "vectorcall";
16819         break;
16820       default:
16821         llvm_unreachable("CC does not need mangling");
16822       }
16823 
16824       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16825           << Param->getDeclName() << FD->getDeclName() << CCName;
16826     }
16827   };
16828 
16829   for (ParmVarDecl *Param : FD->parameters()) {
16830     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16831     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16832   }
16833 }
16834 
16835 namespace {
16836 enum class OdrUseContext {
16837   /// Declarations in this context are not odr-used.
16838   None,
16839   /// Declarations in this context are formally odr-used, but this is a
16840   /// dependent context.
16841   Dependent,
16842   /// Declarations in this context are odr-used but not actually used (yet).
16843   FormallyOdrUsed,
16844   /// Declarations in this context are used.
16845   Used
16846 };
16847 }
16848 
16849 /// Are we within a context in which references to resolved functions or to
16850 /// variables result in odr-use?
isOdrUseContext(Sema & SemaRef)16851 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16852   OdrUseContext Result;
16853 
16854   switch (SemaRef.ExprEvalContexts.back().Context) {
16855     case Sema::ExpressionEvaluationContext::Unevaluated:
16856     case Sema::ExpressionEvaluationContext::UnevaluatedList:
16857     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16858       return OdrUseContext::None;
16859 
16860     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16861     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16862       Result = OdrUseContext::Used;
16863       break;
16864 
16865     case Sema::ExpressionEvaluationContext::DiscardedStatement:
16866       Result = OdrUseContext::FormallyOdrUsed;
16867       break;
16868 
16869     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16870       // A default argument formally results in odr-use, but doesn't actually
16871       // result in a use in any real sense until it itself is used.
16872       Result = OdrUseContext::FormallyOdrUsed;
16873       break;
16874   }
16875 
16876   if (SemaRef.CurContext->isDependentContext())
16877     return OdrUseContext::Dependent;
16878 
16879   return Result;
16880 }
16881 
isImplicitlyDefinableConstexprFunction(FunctionDecl * Func)16882 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16883   return Func->isConstexpr() &&
16884          (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16885 }
16886 
16887 /// Mark a function referenced, and check whether it is odr-used
16888 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)16889 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16890                                   bool MightBeOdrUse) {
16891   assert(Func && "No function?");
16892 
16893   Func->setReferenced();
16894 
16895   // Recursive functions aren't really used until they're used from some other
16896   // context.
16897   bool IsRecursiveCall = CurContext == Func;
16898 
16899   // C++11 [basic.def.odr]p3:
16900   //   A function whose name appears as a potentially-evaluated expression is
16901   //   odr-used if it is the unique lookup result or the selected member of a
16902   //   set of overloaded functions [...].
16903   //
16904   // We (incorrectly) mark overload resolution as an unevaluated context, so we
16905   // can just check that here.
16906   OdrUseContext OdrUse =
16907       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16908   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16909     OdrUse = OdrUseContext::FormallyOdrUsed;
16910 
16911   // Trivial default constructors and destructors are never actually used.
16912   // FIXME: What about other special members?
16913   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16914       OdrUse == OdrUseContext::Used) {
16915     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16916       if (Constructor->isDefaultConstructor())
16917         OdrUse = OdrUseContext::FormallyOdrUsed;
16918     if (isa<CXXDestructorDecl>(Func))
16919       OdrUse = OdrUseContext::FormallyOdrUsed;
16920   }
16921 
16922   // C++20 [expr.const]p12:
16923   //   A function [...] is needed for constant evaluation if it is [...] a
16924   //   constexpr function that is named by an expression that is potentially
16925   //   constant evaluated
16926   bool NeededForConstantEvaluation =
16927       isPotentiallyConstantEvaluatedContext(*this) &&
16928       isImplicitlyDefinableConstexprFunction(Func);
16929 
16930   // Determine whether we require a function definition to exist, per
16931   // C++11 [temp.inst]p3:
16932   //   Unless a function template specialization has been explicitly
16933   //   instantiated or explicitly specialized, the function template
16934   //   specialization is implicitly instantiated when the specialization is
16935   //   referenced in a context that requires a function definition to exist.
16936   // C++20 [temp.inst]p7:
16937   //   The existence of a definition of a [...] function is considered to
16938   //   affect the semantics of the program if the [...] function is needed for
16939   //   constant evaluation by an expression
16940   // C++20 [basic.def.odr]p10:
16941   //   Every program shall contain exactly one definition of every non-inline
16942   //   function or variable that is odr-used in that program outside of a
16943   //   discarded statement
16944   // C++20 [special]p1:
16945   //   The implementation will implicitly define [defaulted special members]
16946   //   if they are odr-used or needed for constant evaluation.
16947   //
16948   // Note that we skip the implicit instantiation of templates that are only
16949   // used in unused default arguments or by recursive calls to themselves.
16950   // This is formally non-conforming, but seems reasonable in practice.
16951   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16952                                              NeededForConstantEvaluation);
16953 
16954   // C++14 [temp.expl.spec]p6:
16955   //   If a template [...] is explicitly specialized then that specialization
16956   //   shall be declared before the first use of that specialization that would
16957   //   cause an implicit instantiation to take place, in every translation unit
16958   //   in which such a use occurs
16959   if (NeedDefinition &&
16960       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16961        Func->getMemberSpecializationInfo()))
16962     checkSpecializationVisibility(Loc, Func);
16963 
16964   if (getLangOpts().CUDA)
16965     CheckCUDACall(Loc, Func);
16966 
16967   if (getLangOpts().SYCLIsDevice)
16968     checkSYCLDeviceFunction(Loc, Func);
16969 
16970   // If we need a definition, try to create one.
16971   if (NeedDefinition && !Func->getBody()) {
16972     runWithSufficientStackSpace(Loc, [&] {
16973       if (CXXConstructorDecl *Constructor =
16974               dyn_cast<CXXConstructorDecl>(Func)) {
16975         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16976         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16977           if (Constructor->isDefaultConstructor()) {
16978             if (Constructor->isTrivial() &&
16979                 !Constructor->hasAttr<DLLExportAttr>())
16980               return;
16981             DefineImplicitDefaultConstructor(Loc, Constructor);
16982           } else if (Constructor->isCopyConstructor()) {
16983             DefineImplicitCopyConstructor(Loc, Constructor);
16984           } else if (Constructor->isMoveConstructor()) {
16985             DefineImplicitMoveConstructor(Loc, Constructor);
16986           }
16987         } else if (Constructor->getInheritedConstructor()) {
16988           DefineInheritingConstructor(Loc, Constructor);
16989         }
16990       } else if (CXXDestructorDecl *Destructor =
16991                      dyn_cast<CXXDestructorDecl>(Func)) {
16992         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16993         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16994           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16995             return;
16996           DefineImplicitDestructor(Loc, Destructor);
16997         }
16998         if (Destructor->isVirtual() && getLangOpts().AppleKext)
16999           MarkVTableUsed(Loc, Destructor->getParent());
17000       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17001         if (MethodDecl->isOverloadedOperator() &&
17002             MethodDecl->getOverloadedOperator() == OO_Equal) {
17003           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17004           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17005             if (MethodDecl->isCopyAssignmentOperator())
17006               DefineImplicitCopyAssignment(Loc, MethodDecl);
17007             else if (MethodDecl->isMoveAssignmentOperator())
17008               DefineImplicitMoveAssignment(Loc, MethodDecl);
17009           }
17010         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17011                    MethodDecl->getParent()->isLambda()) {
17012           CXXConversionDecl *Conversion =
17013               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17014           if (Conversion->isLambdaToBlockPointerConversion())
17015             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17016           else
17017             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17018         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17019           MarkVTableUsed(Loc, MethodDecl->getParent());
17020       }
17021 
17022       if (Func->isDefaulted() && !Func->isDeleted()) {
17023         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17024         if (DCK != DefaultedComparisonKind::None)
17025           DefineDefaultedComparison(Loc, Func, DCK);
17026       }
17027 
17028       // Implicit instantiation of function templates and member functions of
17029       // class templates.
17030       if (Func->isImplicitlyInstantiable()) {
17031         TemplateSpecializationKind TSK =
17032             Func->getTemplateSpecializationKindForInstantiation();
17033         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17034         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17035         if (FirstInstantiation) {
17036           PointOfInstantiation = Loc;
17037           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17038         } else if (TSK != TSK_ImplicitInstantiation) {
17039           // Use the point of use as the point of instantiation, instead of the
17040           // point of explicit instantiation (which we track as the actual point
17041           // of instantiation). This gives better backtraces in diagnostics.
17042           PointOfInstantiation = Loc;
17043         }
17044 
17045         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17046             Func->isConstexpr()) {
17047           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17048               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17049               CodeSynthesisContexts.size())
17050             PendingLocalImplicitInstantiations.push_back(
17051                 std::make_pair(Func, PointOfInstantiation));
17052           else if (Func->isConstexpr())
17053             // Do not defer instantiations of constexpr functions, to avoid the
17054             // expression evaluator needing to call back into Sema if it sees a
17055             // call to such a function.
17056             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17057           else {
17058             Func->setInstantiationIsPending(true);
17059             PendingInstantiations.push_back(
17060                 std::make_pair(Func, PointOfInstantiation));
17061             // Notify the consumer that a function was implicitly instantiated.
17062             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17063           }
17064         }
17065       } else {
17066         // Walk redefinitions, as some of them may be instantiable.
17067         for (auto i : Func->redecls()) {
17068           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17069             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17070         }
17071       }
17072     });
17073   }
17074 
17075   // C++14 [except.spec]p17:
17076   //   An exception-specification is considered to be needed when:
17077   //   - the function is odr-used or, if it appears in an unevaluated operand,
17078   //     would be odr-used if the expression were potentially-evaluated;
17079   //
17080   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17081   // function is a pure virtual function we're calling, and in that case the
17082   // function was selected by overload resolution and we need to resolve its
17083   // exception specification for a different reason.
17084   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17085   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17086     ResolveExceptionSpec(Loc, FPT);
17087 
17088   // If this is the first "real" use, act on that.
17089   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17090     // Keep track of used but undefined functions.
17091     if (!Func->isDefined()) {
17092       if (mightHaveNonExternalLinkage(Func))
17093         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17094       else if (Func->getMostRecentDecl()->isInlined() &&
17095                !LangOpts.GNUInline &&
17096                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17097         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17098       else if (isExternalWithNoLinkageType(Func))
17099         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17100     }
17101 
17102     // Some x86 Windows calling conventions mangle the size of the parameter
17103     // pack into the name. Computing the size of the parameters requires the
17104     // parameter types to be complete. Check that now.
17105     if (funcHasParameterSizeMangling(*this, Func))
17106       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17107 
17108     // In the MS C++ ABI, the compiler emits destructor variants where they are
17109     // used. If the destructor is used here but defined elsewhere, mark the
17110     // virtual base destructors referenced. If those virtual base destructors
17111     // are inline, this will ensure they are defined when emitting the complete
17112     // destructor variant. This checking may be redundant if the destructor is
17113     // provided later in this TU.
17114     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17115       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17116         CXXRecordDecl *Parent = Dtor->getParent();
17117         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17118           CheckCompleteDestructorVariant(Loc, Dtor);
17119       }
17120     }
17121 
17122     Func->markUsed(Context);
17123   }
17124 }
17125 
17126 /// Directly mark a variable odr-used. Given a choice, prefer to use
17127 /// MarkVariableReferenced since it does additional checks and then
17128 /// calls MarkVarDeclODRUsed.
17129 /// If the variable must be captured:
17130 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17131 ///  - else capture it in the DeclContext that maps to the
17132 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17133 static void
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt=nullptr)17134 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17135                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17136   // Keep track of used but undefined variables.
17137   // FIXME: We shouldn't suppress this warning for static data members.
17138   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17139       (!Var->isExternallyVisible() || Var->isInline() ||
17140        SemaRef.isExternalWithNoLinkageType(Var)) &&
17141       !(Var->isStaticDataMember() && Var->hasInit())) {
17142     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17143     if (old.isInvalid())
17144       old = Loc;
17145   }
17146   QualType CaptureType, DeclRefType;
17147   if (SemaRef.LangOpts.OpenMP)
17148     SemaRef.tryCaptureOpenMPLambdas(Var);
17149   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17150     /*EllipsisLoc*/ SourceLocation(),
17151     /*BuildAndDiagnose*/ true,
17152     CaptureType, DeclRefType,
17153     FunctionScopeIndexToStopAt);
17154 
17155   Var->markUsed(SemaRef.Context);
17156 }
17157 
MarkCaptureUsedInEnclosingContext(VarDecl * Capture,SourceLocation Loc,unsigned CapturingScopeIndex)17158 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17159                                              SourceLocation Loc,
17160                                              unsigned CapturingScopeIndex) {
17161   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17162 }
17163 
17164 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,ValueDecl * var,DeclContext * DC)17165 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17166                                    ValueDecl *var, DeclContext *DC) {
17167   DeclContext *VarDC = var->getDeclContext();
17168 
17169   //  If the parameter still belongs to the translation unit, then
17170   //  we're actually just using one parameter in the declaration of
17171   //  the next.
17172   if (isa<ParmVarDecl>(var) &&
17173       isa<TranslationUnitDecl>(VarDC))
17174     return;
17175 
17176   // For C code, don't diagnose about capture if we're not actually in code
17177   // right now; it's impossible to write a non-constant expression outside of
17178   // function context, so we'll get other (more useful) diagnostics later.
17179   //
17180   // For C++, things get a bit more nasty... it would be nice to suppress this
17181   // diagnostic for certain cases like using a local variable in an array bound
17182   // for a member of a local class, but the correct predicate is not obvious.
17183   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17184     return;
17185 
17186   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17187   unsigned ContextKind = 3; // unknown
17188   if (isa<CXXMethodDecl>(VarDC) &&
17189       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17190     ContextKind = 2;
17191   } else if (isa<FunctionDecl>(VarDC)) {
17192     ContextKind = 0;
17193   } else if (isa<BlockDecl>(VarDC)) {
17194     ContextKind = 1;
17195   }
17196 
17197   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17198     << var << ValueKind << ContextKind << VarDC;
17199   S.Diag(var->getLocation(), diag::note_entity_declared_at)
17200       << var;
17201 
17202   // FIXME: Add additional diagnostic info about class etc. which prevents
17203   // capture.
17204 }
17205 
17206 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)17207 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17208                                       bool &SubCapturesAreNested,
17209                                       QualType &CaptureType,
17210                                       QualType &DeclRefType) {
17211    // Check whether we've already captured it.
17212   if (CSI->CaptureMap.count(Var)) {
17213     // If we found a capture, any subcaptures are nested.
17214     SubCapturesAreNested = true;
17215 
17216     // Retrieve the capture type for this variable.
17217     CaptureType = CSI->getCapture(Var).getCaptureType();
17218 
17219     // Compute the type of an expression that refers to this variable.
17220     DeclRefType = CaptureType.getNonReferenceType();
17221 
17222     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17223     // are mutable in the sense that user can change their value - they are
17224     // private instances of the captured declarations.
17225     const Capture &Cap = CSI->getCapture(Var);
17226     if (Cap.isCopyCapture() &&
17227         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17228         !(isa<CapturedRegionScopeInfo>(CSI) &&
17229           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17230       DeclRefType.addConst();
17231     return true;
17232   }
17233   return false;
17234 }
17235 
17236 // Only block literals, captured statements, and lambda expressions can
17237 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17238 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17239                                  SourceLocation Loc,
17240                                  const bool Diagnose, Sema &S) {
17241   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17242     return getLambdaAwareParentOfDeclContext(DC);
17243   else if (Var->hasLocalStorage()) {
17244     if (Diagnose)
17245        diagnoseUncapturableValueReference(S, Loc, Var, DC);
17246   }
17247   return nullptr;
17248 }
17249 
17250 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17251 // certain types of variables (unnamed, variably modified types etc.)
17252 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17253 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17254                                  SourceLocation Loc,
17255                                  const bool Diagnose, Sema &S) {
17256 
17257   bool IsBlock = isa<BlockScopeInfo>(CSI);
17258   bool IsLambda = isa<LambdaScopeInfo>(CSI);
17259 
17260   // Lambdas are not allowed to capture unnamed variables
17261   // (e.g. anonymous unions).
17262   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17263   // assuming that's the intent.
17264   if (IsLambda && !Var->getDeclName()) {
17265     if (Diagnose) {
17266       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17267       S.Diag(Var->getLocation(), diag::note_declared_at);
17268     }
17269     return false;
17270   }
17271 
17272   // Prohibit variably-modified types in blocks; they're difficult to deal with.
17273   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17274     if (Diagnose) {
17275       S.Diag(Loc, diag::err_ref_vm_type);
17276       S.Diag(Var->getLocation(), diag::note_previous_decl)
17277         << Var->getDeclName();
17278     }
17279     return false;
17280   }
17281   // Prohibit structs with flexible array members too.
17282   // We cannot capture what is in the tail end of the struct.
17283   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17284     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17285       if (Diagnose) {
17286         if (IsBlock)
17287           S.Diag(Loc, diag::err_ref_flexarray_type);
17288         else
17289           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
17290             << Var->getDeclName();
17291         S.Diag(Var->getLocation(), diag::note_previous_decl)
17292           << Var->getDeclName();
17293       }
17294       return false;
17295     }
17296   }
17297   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17298   // Lambdas and captured statements are not allowed to capture __block
17299   // variables; they don't support the expected semantics.
17300   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17301     if (Diagnose) {
17302       S.Diag(Loc, diag::err_capture_block_variable)
17303         << Var->getDeclName() << !IsLambda;
17304       S.Diag(Var->getLocation(), diag::note_previous_decl)
17305         << Var->getDeclName();
17306     }
17307     return false;
17308   }
17309   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17310   if (S.getLangOpts().OpenCL && IsBlock &&
17311       Var->getType()->isBlockPointerType()) {
17312     if (Diagnose)
17313       S.Diag(Loc, diag::err_opencl_block_ref_block);
17314     return false;
17315   }
17316 
17317   return true;
17318 }
17319 
17320 // Returns true if the capture by block was successful.
captureInBlock(BlockScopeInfo * BSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool Nested,Sema & S,bool Invalid)17321 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17322                                  SourceLocation Loc,
17323                                  const bool BuildAndDiagnose,
17324                                  QualType &CaptureType,
17325                                  QualType &DeclRefType,
17326                                  const bool Nested,
17327                                  Sema &S, bool Invalid) {
17328   bool ByRef = false;
17329 
17330   // Blocks are not allowed to capture arrays, excepting OpenCL.
17331   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17332   // (decayed to pointers).
17333   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17334     if (BuildAndDiagnose) {
17335       S.Diag(Loc, diag::err_ref_array_type);
17336       S.Diag(Var->getLocation(), diag::note_previous_decl)
17337       << Var->getDeclName();
17338       Invalid = true;
17339     } else {
17340       return false;
17341     }
17342   }
17343 
17344   // Forbid the block-capture of autoreleasing variables.
17345   if (!Invalid &&
17346       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17347     if (BuildAndDiagnose) {
17348       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17349         << /*block*/ 0;
17350       S.Diag(Var->getLocation(), diag::note_previous_decl)
17351         << Var->getDeclName();
17352       Invalid = true;
17353     } else {
17354       return false;
17355     }
17356   }
17357 
17358   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17359   if (const auto *PT = CaptureType->getAs<PointerType>()) {
17360     QualType PointeeTy = PT->getPointeeType();
17361 
17362     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17363         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17364         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17365       if (BuildAndDiagnose) {
17366         SourceLocation VarLoc = Var->getLocation();
17367         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17368         S.Diag(VarLoc, diag::note_declare_parameter_strong);
17369       }
17370     }
17371   }
17372 
17373   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17374   if (HasBlocksAttr || CaptureType->isReferenceType() ||
17375       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17376     // Block capture by reference does not change the capture or
17377     // declaration reference types.
17378     ByRef = true;
17379   } else {
17380     // Block capture by copy introduces 'const'.
17381     CaptureType = CaptureType.getNonReferenceType().withConst();
17382     DeclRefType = CaptureType;
17383   }
17384 
17385   // Actually capture the variable.
17386   if (BuildAndDiagnose)
17387     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17388                     CaptureType, Invalid);
17389 
17390   return !Invalid;
17391 }
17392 
17393 
17394 /// Capture the given variable in the captured region.
captureInCapturedRegion(CapturedRegionScopeInfo * RSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,Sema & S,bool Invalid)17395 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17396                                     VarDecl *Var,
17397                                     SourceLocation Loc,
17398                                     const bool BuildAndDiagnose,
17399                                     QualType &CaptureType,
17400                                     QualType &DeclRefType,
17401                                     const bool RefersToCapturedVariable,
17402                                     Sema &S, bool Invalid) {
17403   // By default, capture variables by reference.
17404   bool ByRef = true;
17405   // Using an LValue reference type is consistent with Lambdas (see below).
17406   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17407     if (S.isOpenMPCapturedDecl(Var)) {
17408       bool HasConst = DeclRefType.isConstQualified();
17409       DeclRefType = DeclRefType.getUnqualifiedType();
17410       // Don't lose diagnostics about assignments to const.
17411       if (HasConst)
17412         DeclRefType.addConst();
17413     }
17414     // Do not capture firstprivates in tasks.
17415     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17416         OMPC_unknown)
17417       return true;
17418     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17419                                     RSI->OpenMPCaptureLevel);
17420   }
17421 
17422   if (ByRef)
17423     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17424   else
17425     CaptureType = DeclRefType;
17426 
17427   // Actually capture the variable.
17428   if (BuildAndDiagnose)
17429     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17430                     Loc, SourceLocation(), CaptureType, Invalid);
17431 
17432   return !Invalid;
17433 }
17434 
17435 /// Capture the given variable in the lambda.
captureInLambda(LambdaScopeInfo * LSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,const Sema::TryCaptureKind Kind,SourceLocation EllipsisLoc,const bool IsTopScope,Sema & S,bool Invalid)17436 static bool captureInLambda(LambdaScopeInfo *LSI,
17437                             VarDecl *Var,
17438                             SourceLocation Loc,
17439                             const bool BuildAndDiagnose,
17440                             QualType &CaptureType,
17441                             QualType &DeclRefType,
17442                             const bool RefersToCapturedVariable,
17443                             const Sema::TryCaptureKind Kind,
17444                             SourceLocation EllipsisLoc,
17445                             const bool IsTopScope,
17446                             Sema &S, bool Invalid) {
17447   // Determine whether we are capturing by reference or by value.
17448   bool ByRef = false;
17449   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17450     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17451   } else {
17452     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17453   }
17454 
17455   // Compute the type of the field that will capture this variable.
17456   if (ByRef) {
17457     // C++11 [expr.prim.lambda]p15:
17458     //   An entity is captured by reference if it is implicitly or
17459     //   explicitly captured but not captured by copy. It is
17460     //   unspecified whether additional unnamed non-static data
17461     //   members are declared in the closure type for entities
17462     //   captured by reference.
17463     //
17464     // FIXME: It is not clear whether we want to build an lvalue reference
17465     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17466     // to do the former, while EDG does the latter. Core issue 1249 will
17467     // clarify, but for now we follow GCC because it's a more permissive and
17468     // easily defensible position.
17469     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17470   } else {
17471     // C++11 [expr.prim.lambda]p14:
17472     //   For each entity captured by copy, an unnamed non-static
17473     //   data member is declared in the closure type. The
17474     //   declaration order of these members is unspecified. The type
17475     //   of such a data member is the type of the corresponding
17476     //   captured entity if the entity is not a reference to an
17477     //   object, or the referenced type otherwise. [Note: If the
17478     //   captured entity is a reference to a function, the
17479     //   corresponding data member is also a reference to a
17480     //   function. - end note ]
17481     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17482       if (!RefType->getPointeeType()->isFunctionType())
17483         CaptureType = RefType->getPointeeType();
17484     }
17485 
17486     // Forbid the lambda copy-capture of autoreleasing variables.
17487     if (!Invalid &&
17488         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17489       if (BuildAndDiagnose) {
17490         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17491         S.Diag(Var->getLocation(), diag::note_previous_decl)
17492           << Var->getDeclName();
17493         Invalid = true;
17494       } else {
17495         return false;
17496       }
17497     }
17498 
17499     // Make sure that by-copy captures are of a complete and non-abstract type.
17500     if (!Invalid && BuildAndDiagnose) {
17501       if (!CaptureType->isDependentType() &&
17502           S.RequireCompleteSizedType(
17503               Loc, CaptureType,
17504               diag::err_capture_of_incomplete_or_sizeless_type,
17505               Var->getDeclName()))
17506         Invalid = true;
17507       else if (S.RequireNonAbstractType(Loc, CaptureType,
17508                                         diag::err_capture_of_abstract_type))
17509         Invalid = true;
17510     }
17511   }
17512 
17513   // Compute the type of a reference to this captured variable.
17514   if (ByRef)
17515     DeclRefType = CaptureType.getNonReferenceType();
17516   else {
17517     // C++ [expr.prim.lambda]p5:
17518     //   The closure type for a lambda-expression has a public inline
17519     //   function call operator [...]. This function call operator is
17520     //   declared const (9.3.1) if and only if the lambda-expression's
17521     //   parameter-declaration-clause is not followed by mutable.
17522     DeclRefType = CaptureType.getNonReferenceType();
17523     if (!LSI->Mutable && !CaptureType->isReferenceType())
17524       DeclRefType.addConst();
17525   }
17526 
17527   // Add the capture.
17528   if (BuildAndDiagnose)
17529     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17530                     Loc, EllipsisLoc, CaptureType, Invalid);
17531 
17532   return !Invalid;
17533 }
17534 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)17535 bool Sema::tryCaptureVariable(
17536     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17537     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17538     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17539   // An init-capture is notionally from the context surrounding its
17540   // declaration, but its parent DC is the lambda class.
17541   DeclContext *VarDC = Var->getDeclContext();
17542   if (Var->isInitCapture())
17543     VarDC = VarDC->getParent();
17544 
17545   DeclContext *DC = CurContext;
17546   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17547       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17548   // We need to sync up the Declaration Context with the
17549   // FunctionScopeIndexToStopAt
17550   if (FunctionScopeIndexToStopAt) {
17551     unsigned FSIndex = FunctionScopes.size() - 1;
17552     while (FSIndex != MaxFunctionScopesIndex) {
17553       DC = getLambdaAwareParentOfDeclContext(DC);
17554       --FSIndex;
17555     }
17556   }
17557 
17558 
17559   // If the variable is declared in the current context, there is no need to
17560   // capture it.
17561   if (VarDC == DC) return true;
17562 
17563   // Capture global variables if it is required to use private copy of this
17564   // variable.
17565   bool IsGlobal = !Var->hasLocalStorage();
17566   if (IsGlobal &&
17567       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17568                                                 MaxFunctionScopesIndex)))
17569     return true;
17570   Var = Var->getCanonicalDecl();
17571 
17572   // Walk up the stack to determine whether we can capture the variable,
17573   // performing the "simple" checks that don't depend on type. We stop when
17574   // we've either hit the declared scope of the variable or find an existing
17575   // capture of that variable.  We start from the innermost capturing-entity
17576   // (the DC) and ensure that all intervening capturing-entities
17577   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17578   // declcontext can either capture the variable or have already captured
17579   // the variable.
17580   CaptureType = Var->getType();
17581   DeclRefType = CaptureType.getNonReferenceType();
17582   bool Nested = false;
17583   bool Explicit = (Kind != TryCapture_Implicit);
17584   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17585   do {
17586     // Only block literals, captured statements, and lambda expressions can
17587     // capture; other scopes don't work.
17588     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17589                                                               ExprLoc,
17590                                                               BuildAndDiagnose,
17591                                                               *this);
17592     // We need to check for the parent *first* because, if we *have*
17593     // private-captured a global variable, we need to recursively capture it in
17594     // intermediate blocks, lambdas, etc.
17595     if (!ParentDC) {
17596       if (IsGlobal) {
17597         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17598         break;
17599       }
17600       return true;
17601     }
17602 
17603     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
17604     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17605 
17606 
17607     // Check whether we've already captured it.
17608     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17609                                              DeclRefType)) {
17610       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17611       break;
17612     }
17613     // If we are instantiating a generic lambda call operator body,
17614     // we do not want to capture new variables.  What was captured
17615     // during either a lambdas transformation or initial parsing
17616     // should be used.
17617     if (isGenericLambdaCallOperatorSpecialization(DC)) {
17618       if (BuildAndDiagnose) {
17619         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17620         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17621           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17622           Diag(Var->getLocation(), diag::note_previous_decl)
17623              << Var->getDeclName();
17624           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17625         } else
17626           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17627       }
17628       return true;
17629     }
17630 
17631     // Try to capture variable-length arrays types.
17632     if (Var->getType()->isVariablyModifiedType()) {
17633       // We're going to walk down into the type and look for VLA
17634       // expressions.
17635       QualType QTy = Var->getType();
17636       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17637         QTy = PVD->getOriginalType();
17638       captureVariablyModifiedType(Context, QTy, CSI);
17639     }
17640 
17641     if (getLangOpts().OpenMP) {
17642       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17643         // OpenMP private variables should not be captured in outer scope, so
17644         // just break here. Similarly, global variables that are captured in a
17645         // target region should not be captured outside the scope of the region.
17646         if (RSI->CapRegionKind == CR_OpenMP) {
17647           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17648               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17649           // If the variable is private (i.e. not captured) and has variably
17650           // modified type, we still need to capture the type for correct
17651           // codegen in all regions, associated with the construct. Currently,
17652           // it is captured in the innermost captured region only.
17653           if (IsOpenMPPrivateDecl != OMPC_unknown &&
17654               Var->getType()->isVariablyModifiedType()) {
17655             QualType QTy = Var->getType();
17656             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17657               QTy = PVD->getOriginalType();
17658             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17659                  I < E; ++I) {
17660               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17661                   FunctionScopes[FunctionScopesIndex - I]);
17662               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17663                      "Wrong number of captured regions associated with the "
17664                      "OpenMP construct.");
17665               captureVariablyModifiedType(Context, QTy, OuterRSI);
17666             }
17667           }
17668           bool IsTargetCap =
17669               IsOpenMPPrivateDecl != OMPC_private &&
17670               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17671                                          RSI->OpenMPCaptureLevel);
17672           // Do not capture global if it is not privatized in outer regions.
17673           bool IsGlobalCap =
17674               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17675                                                      RSI->OpenMPCaptureLevel);
17676 
17677           // When we detect target captures we are looking from inside the
17678           // target region, therefore we need to propagate the capture from the
17679           // enclosing region. Therefore, the capture is not initially nested.
17680           if (IsTargetCap)
17681             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17682 
17683           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17684               (IsGlobal && !IsGlobalCap)) {
17685             Nested = !IsTargetCap;
17686             DeclRefType = DeclRefType.getUnqualifiedType();
17687             CaptureType = Context.getLValueReferenceType(DeclRefType);
17688             break;
17689           }
17690         }
17691       }
17692     }
17693     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17694       // No capture-default, and this is not an explicit capture
17695       // so cannot capture this variable.
17696       if (BuildAndDiagnose) {
17697         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17698         Diag(Var->getLocation(), diag::note_previous_decl)
17699           << Var->getDeclName();
17700         if (cast<LambdaScopeInfo>(CSI)->Lambda)
17701           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17702                diag::note_lambda_decl);
17703         // FIXME: If we error out because an outer lambda can not implicitly
17704         // capture a variable that an inner lambda explicitly captures, we
17705         // should have the inner lambda do the explicit capture - because
17706         // it makes for cleaner diagnostics later.  This would purely be done
17707         // so that the diagnostic does not misleadingly claim that a variable
17708         // can not be captured by a lambda implicitly even though it is captured
17709         // explicitly.  Suggestion:
17710         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17711         //    at the function head
17712         //  - cache the StartingDeclContext - this must be a lambda
17713         //  - captureInLambda in the innermost lambda the variable.
17714       }
17715       return true;
17716     }
17717 
17718     FunctionScopesIndex--;
17719     DC = ParentDC;
17720     Explicit = false;
17721   } while (!VarDC->Equals(DC));
17722 
17723   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17724   // computing the type of the capture at each step, checking type-specific
17725   // requirements, and adding captures if requested.
17726   // If the variable had already been captured previously, we start capturing
17727   // at the lambda nested within that one.
17728   bool Invalid = false;
17729   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17730        ++I) {
17731     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17732 
17733     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17734     // certain types of variables (unnamed, variably modified types etc.)
17735     // so check for eligibility.
17736     if (!Invalid)
17737       Invalid =
17738           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17739 
17740     // After encountering an error, if we're actually supposed to capture, keep
17741     // capturing in nested contexts to suppress any follow-on diagnostics.
17742     if (Invalid && !BuildAndDiagnose)
17743       return true;
17744 
17745     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17746       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17747                                DeclRefType, Nested, *this, Invalid);
17748       Nested = true;
17749     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17750       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17751                                          CaptureType, DeclRefType, Nested,
17752                                          *this, Invalid);
17753       Nested = true;
17754     } else {
17755       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17756       Invalid =
17757           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17758                            DeclRefType, Nested, Kind, EllipsisLoc,
17759                            /*IsTopScope*/ I == N - 1, *this, Invalid);
17760       Nested = true;
17761     }
17762 
17763     if (Invalid && !BuildAndDiagnose)
17764       return true;
17765   }
17766   return Invalid;
17767 }
17768 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)17769 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17770                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17771   QualType CaptureType;
17772   QualType DeclRefType;
17773   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17774                             /*BuildAndDiagnose=*/true, CaptureType,
17775                             DeclRefType, nullptr);
17776 }
17777 
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)17778 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17779   QualType CaptureType;
17780   QualType DeclRefType;
17781   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17782                              /*BuildAndDiagnose=*/false, CaptureType,
17783                              DeclRefType, nullptr);
17784 }
17785 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)17786 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17787   QualType CaptureType;
17788   QualType DeclRefType;
17789 
17790   // Determine whether we can capture this variable.
17791   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17792                          /*BuildAndDiagnose=*/false, CaptureType,
17793                          DeclRefType, nullptr))
17794     return QualType();
17795 
17796   return DeclRefType;
17797 }
17798 
17799 namespace {
17800 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17801 // The produced TemplateArgumentListInfo* points to data stored within this
17802 // object, so should only be used in contexts where the pointer will not be
17803 // used after the CopiedTemplateArgs object is destroyed.
17804 class CopiedTemplateArgs {
17805   bool HasArgs;
17806   TemplateArgumentListInfo TemplateArgStorage;
17807 public:
17808   template<typename RefExpr>
CopiedTemplateArgs(RefExpr * E)17809   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17810     if (HasArgs)
17811       E->copyTemplateArgumentsInto(TemplateArgStorage);
17812   }
operator TemplateArgumentListInfo*()17813   operator TemplateArgumentListInfo*()
17814 #ifdef __has_cpp_attribute
17815 #if __has_cpp_attribute(clang::lifetimebound)
17816   [[clang::lifetimebound]]
17817 #endif
17818 #endif
17819   {
17820     return HasArgs ? &TemplateArgStorage : nullptr;
17821   }
17822 };
17823 }
17824 
17825 /// Walk the set of potential results of an expression and mark them all as
17826 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17827 ///
17828 /// \return A new expression if we found any potential results, ExprEmpty() if
17829 ///         not, and ExprError() if we diagnosed an error.
rebuildPotentialResultsAsNonOdrUsed(Sema & S,Expr * E,NonOdrUseReason NOUR)17830 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17831                                                       NonOdrUseReason NOUR) {
17832   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17833   // an object that satisfies the requirements for appearing in a
17834   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17835   // is immediately applied."  This function handles the lvalue-to-rvalue
17836   // conversion part.
17837   //
17838   // If we encounter a node that claims to be an odr-use but shouldn't be, we
17839   // transform it into the relevant kind of non-odr-use node and rebuild the
17840   // tree of nodes leading to it.
17841   //
17842   // This is a mini-TreeTransform that only transforms a restricted subset of
17843   // nodes (and only certain operands of them).
17844 
17845   // Rebuild a subexpression.
17846   auto Rebuild = [&](Expr *Sub) {
17847     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17848   };
17849 
17850   // Check whether a potential result satisfies the requirements of NOUR.
17851   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17852     // Any entity other than a VarDecl is always odr-used whenever it's named
17853     // in a potentially-evaluated expression.
17854     auto *VD = dyn_cast<VarDecl>(D);
17855     if (!VD)
17856       return true;
17857 
17858     // C++2a [basic.def.odr]p4:
17859     //   A variable x whose name appears as a potentially-evalauted expression
17860     //   e is odr-used by e unless
17861     //   -- x is a reference that is usable in constant expressions, or
17862     //   -- x is a variable of non-reference type that is usable in constant
17863     //      expressions and has no mutable subobjects, and e is an element of
17864     //      the set of potential results of an expression of
17865     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
17866     //      conversion is applied, or
17867     //   -- x is a variable of non-reference type, and e is an element of the
17868     //      set of potential results of a discarded-value expression to which
17869     //      the lvalue-to-rvalue conversion is not applied
17870     //
17871     // We check the first bullet and the "potentially-evaluated" condition in
17872     // BuildDeclRefExpr. We check the type requirements in the second bullet
17873     // in CheckLValueToRValueConversionOperand below.
17874     switch (NOUR) {
17875     case NOUR_None:
17876     case NOUR_Unevaluated:
17877       llvm_unreachable("unexpected non-odr-use-reason");
17878 
17879     case NOUR_Constant:
17880       // Constant references were handled when they were built.
17881       if (VD->getType()->isReferenceType())
17882         return true;
17883       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17884         if (RD->hasMutableFields())
17885           return true;
17886       if (!VD->isUsableInConstantExpressions(S.Context))
17887         return true;
17888       break;
17889 
17890     case NOUR_Discarded:
17891       if (VD->getType()->isReferenceType())
17892         return true;
17893       break;
17894     }
17895     return false;
17896   };
17897 
17898   // Mark that this expression does not constitute an odr-use.
17899   auto MarkNotOdrUsed = [&] {
17900     S.MaybeODRUseExprs.remove(E);
17901     if (LambdaScopeInfo *LSI = S.getCurLambda())
17902       LSI->markVariableExprAsNonODRUsed(E);
17903   };
17904 
17905   // C++2a [basic.def.odr]p2:
17906   //   The set of potential results of an expression e is defined as follows:
17907   switch (E->getStmtClass()) {
17908   //   -- If e is an id-expression, ...
17909   case Expr::DeclRefExprClass: {
17910     auto *DRE = cast<DeclRefExpr>(E);
17911     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17912       break;
17913 
17914     // Rebuild as a non-odr-use DeclRefExpr.
17915     MarkNotOdrUsed();
17916     return DeclRefExpr::Create(
17917         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17918         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17919         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17920         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17921   }
17922 
17923   case Expr::FunctionParmPackExprClass: {
17924     auto *FPPE = cast<FunctionParmPackExpr>(E);
17925     // If any of the declarations in the pack is odr-used, then the expression
17926     // as a whole constitutes an odr-use.
17927     for (VarDecl *D : *FPPE)
17928       if (IsPotentialResultOdrUsed(D))
17929         return ExprEmpty();
17930 
17931     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17932     // nothing cares about whether we marked this as an odr-use, but it might
17933     // be useful for non-compiler tools.
17934     MarkNotOdrUsed();
17935     break;
17936   }
17937 
17938   //   -- If e is a subscripting operation with an array operand...
17939   case Expr::ArraySubscriptExprClass: {
17940     auto *ASE = cast<ArraySubscriptExpr>(E);
17941     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17942     if (!OldBase->getType()->isArrayType())
17943       break;
17944     ExprResult Base = Rebuild(OldBase);
17945     if (!Base.isUsable())
17946       return Base;
17947     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17948     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17949     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17950     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17951                                      ASE->getRBracketLoc());
17952   }
17953 
17954   case Expr::MemberExprClass: {
17955     auto *ME = cast<MemberExpr>(E);
17956     // -- If e is a class member access expression [...] naming a non-static
17957     //    data member...
17958     if (isa<FieldDecl>(ME->getMemberDecl())) {
17959       ExprResult Base = Rebuild(ME->getBase());
17960       if (!Base.isUsable())
17961         return Base;
17962       return MemberExpr::Create(
17963           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17964           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17965           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17966           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17967           ME->getObjectKind(), ME->isNonOdrUse());
17968     }
17969 
17970     if (ME->getMemberDecl()->isCXXInstanceMember())
17971       break;
17972 
17973     // -- If e is a class member access expression naming a static data member,
17974     //    ...
17975     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17976       break;
17977 
17978     // Rebuild as a non-odr-use MemberExpr.
17979     MarkNotOdrUsed();
17980     return MemberExpr::Create(
17981         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17982         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17983         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17984         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17985     return ExprEmpty();
17986   }
17987 
17988   case Expr::BinaryOperatorClass: {
17989     auto *BO = cast<BinaryOperator>(E);
17990     Expr *LHS = BO->getLHS();
17991     Expr *RHS = BO->getRHS();
17992     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17993     if (BO->getOpcode() == BO_PtrMemD) {
17994       ExprResult Sub = Rebuild(LHS);
17995       if (!Sub.isUsable())
17996         return Sub;
17997       LHS = Sub.get();
17998     //   -- If e is a comma expression, ...
17999     } else if (BO->getOpcode() == BO_Comma) {
18000       ExprResult Sub = Rebuild(RHS);
18001       if (!Sub.isUsable())
18002         return Sub;
18003       RHS = Sub.get();
18004     } else {
18005       break;
18006     }
18007     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18008                         LHS, RHS);
18009   }
18010 
18011   //   -- If e has the form (e1)...
18012   // XXXAR: and do the same for NoChangeBoundsExpr
18013   case Expr::NoChangeBoundsExprClass:
18014   case Expr::ParenExprClass: {
18015     auto *PE = cast<ParenExpr>(E);
18016     ExprResult Sub = Rebuild(PE->getSubExpr());
18017     if (!Sub.isUsable())
18018       return Sub;
18019     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18020   }
18021 
18022   //   -- If e is a glvalue conditional expression, ...
18023   // We don't apply this to a binary conditional operator. FIXME: Should we?
18024   case Expr::ConditionalOperatorClass: {
18025     auto *CO = cast<ConditionalOperator>(E);
18026     ExprResult LHS = Rebuild(CO->getLHS());
18027     if (LHS.isInvalid())
18028       return ExprError();
18029     ExprResult RHS = Rebuild(CO->getRHS());
18030     if (RHS.isInvalid())
18031       return ExprError();
18032     if (!LHS.isUsable() && !RHS.isUsable())
18033       return ExprEmpty();
18034     if (!LHS.isUsable())
18035       LHS = CO->getLHS();
18036     if (!RHS.isUsable())
18037       RHS = CO->getRHS();
18038     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18039                                 CO->getCond(), LHS.get(), RHS.get());
18040   }
18041 
18042   // [Clang extension]
18043   //   -- If e has the form __extension__ e1...
18044   case Expr::UnaryOperatorClass: {
18045     auto *UO = cast<UnaryOperator>(E);
18046     if (UO->getOpcode() != UO_Extension)
18047       break;
18048     ExprResult Sub = Rebuild(UO->getSubExpr());
18049     if (!Sub.isUsable())
18050       return Sub;
18051     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18052                           Sub.get());
18053   }
18054 
18055   // [Clang extension]
18056   //   -- If e has the form _Generic(...), the set of potential results is the
18057   //      union of the sets of potential results of the associated expressions.
18058   case Expr::GenericSelectionExprClass: {
18059     auto *GSE = cast<GenericSelectionExpr>(E);
18060 
18061     SmallVector<Expr *, 4> AssocExprs;
18062     bool AnyChanged = false;
18063     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18064       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18065       if (AssocExpr.isInvalid())
18066         return ExprError();
18067       if (AssocExpr.isUsable()) {
18068         AssocExprs.push_back(AssocExpr.get());
18069         AnyChanged = true;
18070       } else {
18071         AssocExprs.push_back(OrigAssocExpr);
18072       }
18073     }
18074 
18075     return AnyChanged ? S.CreateGenericSelectionExpr(
18076                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
18077                             GSE->getRParenLoc(), GSE->getControllingExpr(),
18078                             GSE->getAssocTypeSourceInfos(), AssocExprs)
18079                       : ExprEmpty();
18080   }
18081 
18082   // [Clang extension]
18083   //   -- If e has the form __builtin_choose_expr(...), the set of potential
18084   //      results is the union of the sets of potential results of the
18085   //      second and third subexpressions.
18086   case Expr::ChooseExprClass: {
18087     auto *CE = cast<ChooseExpr>(E);
18088 
18089     ExprResult LHS = Rebuild(CE->getLHS());
18090     if (LHS.isInvalid())
18091       return ExprError();
18092 
18093     ExprResult RHS = Rebuild(CE->getLHS());
18094     if (RHS.isInvalid())
18095       return ExprError();
18096 
18097     if (!LHS.get() && !RHS.get())
18098       return ExprEmpty();
18099     if (!LHS.isUsable())
18100       LHS = CE->getLHS();
18101     if (!RHS.isUsable())
18102       RHS = CE->getRHS();
18103 
18104     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18105                              RHS.get(), CE->getRParenLoc());
18106   }
18107 
18108   // Step through non-syntactic nodes.
18109   case Expr::ConstantExprClass: {
18110     auto *CE = cast<ConstantExpr>(E);
18111     ExprResult Sub = Rebuild(CE->getSubExpr());
18112     if (!Sub.isUsable())
18113       return Sub;
18114     return ConstantExpr::Create(S.Context, Sub.get());
18115   }
18116 
18117   // We could mostly rely on the recursive rebuilding to rebuild implicit
18118   // casts, but not at the top level, so rebuild them here.
18119   case Expr::ImplicitCastExprClass: {
18120     auto *ICE = cast<ImplicitCastExpr>(E);
18121     // Only step through the narrow set of cast kinds we expect to encounter.
18122     // Anything else suggests we've left the region in which potential results
18123     // can be found.
18124     switch (ICE->getCastKind()) {
18125     case CK_NoOp:
18126     case CK_DerivedToBase:
18127     case CK_UncheckedDerivedToBase: {
18128       ExprResult Sub = Rebuild(ICE->getSubExpr());
18129       if (!Sub.isUsable())
18130         return Sub;
18131       CXXCastPath Path(ICE->path());
18132       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18133                                  ICE->getValueKind(), &Path);
18134     }
18135 
18136     default:
18137       break;
18138     }
18139     break;
18140   }
18141 
18142   default:
18143     break;
18144   }
18145 
18146   // Can't traverse through this node. Nothing to do.
18147   return ExprEmpty();
18148 }
18149 
CheckLValueToRValueConversionOperand(Expr * E)18150 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18151   // Check whether the operand is or contains an object of non-trivial C union
18152   // type.
18153   if (E->getType().isVolatileQualified() &&
18154       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18155        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18156     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18157                           Sema::NTCUC_LValueToRValueVolatile,
18158                           NTCUK_Destruct|NTCUK_Copy);
18159 
18160   // C++2a [basic.def.odr]p4:
18161   //   [...] an expression of non-volatile-qualified non-class type to which
18162   //   the lvalue-to-rvalue conversion is applied [...]
18163   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18164     return E;
18165 
18166   ExprResult Result =
18167       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18168   if (Result.isInvalid())
18169     return ExprError();
18170   return Result.get() ? Result : E;
18171 }
18172 
ActOnConstantExpression(ExprResult Res)18173 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18174   Res = CorrectDelayedTyposInExpr(Res);
18175 
18176   if (!Res.isUsable())
18177     return Res;
18178 
18179   // If a constant-expression is a reference to a variable where we delay
18180   // deciding whether it is an odr-use, just assume we will apply the
18181   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
18182   // (a non-type template argument), we have special handling anyway.
18183   return CheckLValueToRValueConversionOperand(Res.get());
18184 }
18185 
CleanupVarDeclMarking()18186 void Sema::CleanupVarDeclMarking() {
18187   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18188   // call.
18189   MaybeODRUseExprSet LocalMaybeODRUseExprs;
18190   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18191 
18192   for (Expr *E : LocalMaybeODRUseExprs) {
18193     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18194       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18195                          DRE->getLocation(), *this);
18196     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18197       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18198                          *this);
18199     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18200       for (VarDecl *VD : *FP)
18201         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18202     } else {
18203       llvm_unreachable("Unexpected expression");
18204     }
18205   }
18206 
18207   assert(MaybeODRUseExprs.empty() &&
18208          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18209 }
18210 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)18211 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18212                                     VarDecl *Var, Expr *E) {
18213   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18214           isa<FunctionParmPackExpr>(E)) &&
18215          "Invalid Expr argument to DoMarkVarDeclReferenced");
18216   Var->setReferenced();
18217 
18218   if (Var->isInvalidDecl())
18219     return;
18220 
18221   auto *MSI = Var->getMemberSpecializationInfo();
18222   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18223                                        : Var->getTemplateSpecializationKind();
18224 
18225   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18226   bool UsableInConstantExpr =
18227       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18228 
18229   // C++20 [expr.const]p12:
18230   //   A variable [...] is needed for constant evaluation if it is [...] a
18231   //   variable whose name appears as a potentially constant evaluated
18232   //   expression that is either a contexpr variable or is of non-volatile
18233   //   const-qualified integral type or of reference type
18234   bool NeededForConstantEvaluation =
18235       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18236 
18237   bool NeedDefinition =
18238       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18239 
18240   VarTemplateSpecializationDecl *VarSpec =
18241       dyn_cast<VarTemplateSpecializationDecl>(Var);
18242   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18243          "Can't instantiate a partial template specialization.");
18244 
18245   // If this might be a member specialization of a static data member, check
18246   // the specialization is visible. We already did the checks for variable
18247   // template specializations when we created them.
18248   if (NeedDefinition && TSK != TSK_Undeclared &&
18249       !isa<VarTemplateSpecializationDecl>(Var))
18250     SemaRef.checkSpecializationVisibility(Loc, Var);
18251 
18252   // Perform implicit instantiation of static data members, static data member
18253   // templates of class templates, and variable template specializations. Delay
18254   // instantiations of variable templates, except for those that could be used
18255   // in a constant expression.
18256   if (NeedDefinition && isTemplateInstantiation(TSK)) {
18257     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18258     // instantiation declaration if a variable is usable in a constant
18259     // expression (among other cases).
18260     bool TryInstantiating =
18261         TSK == TSK_ImplicitInstantiation ||
18262         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18263 
18264     if (TryInstantiating) {
18265       SourceLocation PointOfInstantiation =
18266           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18267       bool FirstInstantiation = PointOfInstantiation.isInvalid();
18268       if (FirstInstantiation) {
18269         PointOfInstantiation = Loc;
18270         if (MSI)
18271           MSI->setPointOfInstantiation(PointOfInstantiation);
18272         else
18273           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18274       }
18275 
18276       bool InstantiationDependent = false;
18277       bool IsNonDependent =
18278           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
18279                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
18280                   : true;
18281 
18282       // Do not instantiate specializations that are still type-dependent.
18283       if (IsNonDependent) {
18284         if (UsableInConstantExpr) {
18285           // Do not defer instantiations of variables that could be used in a
18286           // constant expression.
18287           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18288             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18289           });
18290         } else if (FirstInstantiation ||
18291                    isa<VarTemplateSpecializationDecl>(Var)) {
18292           // FIXME: For a specialization of a variable template, we don't
18293           // distinguish between "declaration and type implicitly instantiated"
18294           // and "implicit instantiation of definition requested", so we have
18295           // no direct way to avoid enqueueing the pending instantiation
18296           // multiple times.
18297           SemaRef.PendingInstantiations
18298               .push_back(std::make_pair(Var, PointOfInstantiation));
18299         }
18300       }
18301     }
18302   }
18303 
18304   // C++2a [basic.def.odr]p4:
18305   //   A variable x whose name appears as a potentially-evaluated expression e
18306   //   is odr-used by e unless
18307   //   -- x is a reference that is usable in constant expressions
18308   //   -- x is a variable of non-reference type that is usable in constant
18309   //      expressions and has no mutable subobjects [FIXME], and e is an
18310   //      element of the set of potential results of an expression of
18311   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18312   //      conversion is applied
18313   //   -- x is a variable of non-reference type, and e is an element of the set
18314   //      of potential results of a discarded-value expression to which the
18315   //      lvalue-to-rvalue conversion is not applied [FIXME]
18316   //
18317   // We check the first part of the second bullet here, and
18318   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18319   // FIXME: To get the third bullet right, we need to delay this even for
18320   // variables that are not usable in constant expressions.
18321 
18322   // If we already know this isn't an odr-use, there's nothing more to do.
18323   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18324     if (DRE->isNonOdrUse())
18325       return;
18326   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18327     if (ME->isNonOdrUse())
18328       return;
18329 
18330   switch (OdrUse) {
18331   case OdrUseContext::None:
18332     assert((!E || isa<FunctionParmPackExpr>(E)) &&
18333            "missing non-odr-use marking for unevaluated decl ref");
18334     break;
18335 
18336   case OdrUseContext::FormallyOdrUsed:
18337     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18338     // behavior.
18339     break;
18340 
18341   case OdrUseContext::Used:
18342     // If we might later find that this expression isn't actually an odr-use,
18343     // delay the marking.
18344     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18345       SemaRef.MaybeODRUseExprs.insert(E);
18346     else
18347       MarkVarDeclODRUsed(Var, Loc, SemaRef);
18348     break;
18349 
18350   case OdrUseContext::Dependent:
18351     // If this is a dependent context, we don't need to mark variables as
18352     // odr-used, but we may still need to track them for lambda capture.
18353     // FIXME: Do we also need to do this inside dependent typeid expressions
18354     // (which are modeled as unevaluated at this point)?
18355     const bool RefersToEnclosingScope =
18356         (SemaRef.CurContext != Var->getDeclContext() &&
18357          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18358     if (RefersToEnclosingScope) {
18359       LambdaScopeInfo *const LSI =
18360           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18361       if (LSI && (!LSI->CallOperator ||
18362                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18363         // If a variable could potentially be odr-used, defer marking it so
18364         // until we finish analyzing the full expression for any
18365         // lvalue-to-rvalue
18366         // or discarded value conversions that would obviate odr-use.
18367         // Add it to the list of potential captures that will be analyzed
18368         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18369         // unless the variable is a reference that was initialized by a constant
18370         // expression (this will never need to be captured or odr-used).
18371         //
18372         // FIXME: We can simplify this a lot after implementing P0588R1.
18373         assert(E && "Capture variable should be used in an expression.");
18374         if (!Var->getType()->isReferenceType() ||
18375             !Var->isUsableInConstantExpressions(SemaRef.Context))
18376           LSI->addPotentialCapture(E->IgnoreParens());
18377       }
18378     }
18379     break;
18380   }
18381 }
18382 
18383 /// Mark a variable referenced, and check whether it is odr-used
18384 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
18385 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)18386 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18387   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18388 }
18389 
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse)18390 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18391                                Decl *D, Expr *E, bool MightBeOdrUse) {
18392   if (SemaRef.isInOpenMPDeclareTargetContext())
18393     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18394 
18395   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18396     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18397     return;
18398   }
18399 
18400   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18401 
18402   // If this is a call to a method via a cast, also mark the method in the
18403   // derived class used in case codegen can devirtualize the call.
18404   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18405   if (!ME)
18406     return;
18407   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18408   if (!MD)
18409     return;
18410   // Only attempt to devirtualize if this is truly a virtual call.
18411   bool IsVirtualCall = MD->isVirtual() &&
18412                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
18413   if (!IsVirtualCall)
18414     return;
18415 
18416   // If it's possible to devirtualize the call, mark the called function
18417   // referenced.
18418   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18419       ME->getBase(), SemaRef.getLangOpts().AppleKext);
18420   if (DM)
18421     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18422 }
18423 
18424 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E,const Expr * Base)18425 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18426   // TODO: update this with DR# once a defect report is filed.
18427   // C++11 defect. The address of a pure member should not be an ODR use, even
18428   // if it's a qualified reference.
18429   bool OdrUse = true;
18430   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18431     if (Method->isVirtual() &&
18432         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18433       OdrUse = false;
18434 
18435   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18436     if (!isConstantEvaluated() && FD->isConsteval() &&
18437         !RebuildingImmediateInvocation)
18438       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18439   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18440 }
18441 
18442 /// Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)18443 void Sema::MarkMemberReferenced(MemberExpr *E) {
18444   // C++11 [basic.def.odr]p2:
18445   //   A non-overloaded function whose name appears as a potentially-evaluated
18446   //   expression or a member of a set of candidate functions, if selected by
18447   //   overload resolution when referred to from a potentially-evaluated
18448   //   expression, is odr-used, unless it is a pure virtual function and its
18449   //   name is not explicitly qualified.
18450   bool MightBeOdrUse = true;
18451   if (E->performsVirtualDispatch(getLangOpts())) {
18452     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18453       if (Method->isPure())
18454         MightBeOdrUse = false;
18455   }
18456   SourceLocation Loc =
18457       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18458   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18459 }
18460 
18461 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
MarkFunctionParmPackReferenced(FunctionParmPackExpr * E)18462 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18463   for (VarDecl *VD : *E)
18464     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18465 }
18466 
18467 /// Perform marking for a reference to an arbitrary declaration.  It
18468 /// marks the declaration referenced, and performs odr-use checking for
18469 /// functions and variables. This method should not be used when building a
18470 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)18471 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18472                                  bool MightBeOdrUse) {
18473   if (MightBeOdrUse) {
18474     if (auto *VD = dyn_cast<VarDecl>(D)) {
18475       MarkVariableReferenced(Loc, VD);
18476       return;
18477     }
18478   }
18479   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18480     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18481     return;
18482   }
18483   D->setReferenced();
18484 }
18485 
18486 namespace {
18487   // Mark all of the declarations used by a type as referenced.
18488   // FIXME: Not fully implemented yet! We need to have a better understanding
18489   // of when we're entering a context we should not recurse into.
18490   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18491   // TreeTransforms rebuilding the type in a new context. Rather than
18492   // duplicating the TreeTransform logic, we should consider reusing it here.
18493   // Currently that causes problems when rebuilding LambdaExprs.
18494   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18495     Sema &S;
18496     SourceLocation Loc;
18497 
18498   public:
18499     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18500 
MarkReferencedDecls(Sema & S,SourceLocation Loc)18501     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18502 
18503     bool TraverseTemplateArgument(const TemplateArgument &Arg);
18504   };
18505 }
18506 
TraverseTemplateArgument(const TemplateArgument & Arg)18507 bool MarkReferencedDecls::TraverseTemplateArgument(
18508     const TemplateArgument &Arg) {
18509   {
18510     // A non-type template argument is a constant-evaluated context.
18511     EnterExpressionEvaluationContext Evaluated(
18512         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18513     if (Arg.getKind() == TemplateArgument::Declaration) {
18514       if (Decl *D = Arg.getAsDecl())
18515         S.MarkAnyDeclReferenced(Loc, D, true);
18516     } else if (Arg.getKind() == TemplateArgument::Expression) {
18517       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18518     }
18519   }
18520 
18521   return Inherited::TraverseTemplateArgument(Arg);
18522 }
18523 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)18524 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18525   MarkReferencedDecls Marker(*this, Loc);
18526   Marker.TraverseType(T);
18527 }
18528 
18529 namespace {
18530 /// Helper class that marks all of the declarations referenced by
18531 /// potentially-evaluated subexpressions as "referenced".
18532 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18533 public:
18534   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18535   bool SkipLocalVariables;
18536 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)18537   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18538       : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18539 
visitUsedDecl(SourceLocation Loc,Decl * D)18540   void visitUsedDecl(SourceLocation Loc, Decl *D) {
18541     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18542   }
18543 
VisitDeclRefExpr(DeclRefExpr * E)18544   void VisitDeclRefExpr(DeclRefExpr *E) {
18545     // If we were asked not to visit local variables, don't.
18546     if (SkipLocalVariables) {
18547       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18548         if (VD->hasLocalStorage())
18549           return;
18550     }
18551     S.MarkDeclRefReferenced(E);
18552   }
18553 
VisitMemberExpr(MemberExpr * E)18554   void VisitMemberExpr(MemberExpr *E) {
18555     S.MarkMemberReferenced(E);
18556     Visit(E->getBase());
18557   }
18558 };
18559 } // namespace
18560 
18561 /// Mark any declarations that appear within this expression or any
18562 /// potentially-evaluated subexpressions as "referenced".
18563 ///
18564 /// \param SkipLocalVariables If true, don't mark local variables as
18565 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)18566 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18567                                             bool SkipLocalVariables) {
18568   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18569 }
18570 
18571 /// Emit a diagnostic that describes an effect on the run-time behavior
18572 /// of the program being compiled.
18573 ///
18574 /// This routine emits the given diagnostic when the code currently being
18575 /// type-checked is "potentially evaluated", meaning that there is a
18576 /// possibility that the code will actually be executable. Code in sizeof()
18577 /// expressions, code used only during overload resolution, etc., are not
18578 /// potentially evaluated. This routine will suppress such diagnostics or,
18579 /// in the absolutely nutty case of potentially potentially evaluated
18580 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18581 /// later.
18582 ///
18583 /// This routine should be used for all diagnostics that describe the run-time
18584 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18585 /// Failure to do so will likely result in spurious diagnostics or failures
18586 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,ArrayRef<const Stmt * > Stmts,const PartialDiagnostic & PD)18587 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18588                                const PartialDiagnostic &PD) {
18589   switch (ExprEvalContexts.back().Context) {
18590   case ExpressionEvaluationContext::Unevaluated:
18591   case ExpressionEvaluationContext::UnevaluatedList:
18592   case ExpressionEvaluationContext::UnevaluatedAbstract:
18593   case ExpressionEvaluationContext::DiscardedStatement:
18594     // The argument will never be evaluated, so don't complain.
18595     break;
18596 
18597   case ExpressionEvaluationContext::ConstantEvaluated:
18598     // Relevant diagnostics should be produced by constant evaluation.
18599     break;
18600 
18601   case ExpressionEvaluationContext::PotentiallyEvaluated:
18602   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18603     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18604       FunctionScopes.back()->PossiblyUnreachableDiags.
18605         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18606       return true;
18607     }
18608 
18609     // The initializer of a constexpr variable or of the first declaration of a
18610     // static data member is not syntactically a constant evaluated constant,
18611     // but nonetheless is always required to be a constant expression, so we
18612     // can skip diagnosing.
18613     // FIXME: Using the mangling context here is a hack.
18614     if (auto *VD = dyn_cast_or_null<VarDecl>(
18615             ExprEvalContexts.back().ManglingContextDecl)) {
18616       if (VD->isConstexpr() ||
18617           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18618         break;
18619       // FIXME: For any other kind of variable, we should build a CFG for its
18620       // initializer and check whether the context in question is reachable.
18621     }
18622 
18623     Diag(Loc, PD);
18624     return true;
18625   }
18626 
18627   return false;
18628 }
18629 
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)18630 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18631                                const PartialDiagnostic &PD) {
18632   return DiagRuntimeBehavior(
18633       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18634 }
18635 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)18636 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18637                                CallExpr *CE, FunctionDecl *FD) {
18638   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18639     return false;
18640 
18641   // If we're inside a decltype's expression, don't check for a valid return
18642   // type or construct temporaries until we know whether this is the last call.
18643   if (ExprEvalContexts.back().ExprContext ==
18644       ExpressionEvaluationContextRecord::EK_Decltype) {
18645     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18646     return false;
18647   }
18648 
18649   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18650     FunctionDecl *FD;
18651     CallExpr *CE;
18652 
18653   public:
18654     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18655       : FD(FD), CE(CE) { }
18656 
18657     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18658       if (!FD) {
18659         S.Diag(Loc, diag::err_call_incomplete_return)
18660           << T << CE->getSourceRange();
18661         return;
18662       }
18663 
18664       S.Diag(Loc, diag::err_call_function_incomplete_return)
18665         << CE->getSourceRange() << FD->getDeclName() << T;
18666       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18667           << FD->getDeclName();
18668     }
18669   } Diagnoser(FD, CE);
18670 
18671   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18672     return true;
18673 
18674   return false;
18675 }
18676 
18677 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18678 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)18679 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18680   SourceLocation Loc;
18681 
18682   unsigned diagnostic = diag::warn_condition_is_assignment;
18683   bool IsOrAssign = false;
18684 
18685   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18686     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18687       return;
18688 
18689     IsOrAssign = Op->getOpcode() == BO_OrAssign;
18690 
18691     // Greylist some idioms by putting them into a warning subcategory.
18692     if (ObjCMessageExpr *ME
18693           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18694       Selector Sel = ME->getSelector();
18695 
18696       // self = [<foo> init...]
18697       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18698         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18699 
18700       // <foo> = [<bar> nextObject]
18701       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18702         diagnostic = diag::warn_condition_is_idiomatic_assignment;
18703     }
18704 
18705     Loc = Op->getOperatorLoc();
18706   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18707     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18708       return;
18709 
18710     IsOrAssign = Op->getOperator() == OO_PipeEqual;
18711     Loc = Op->getOperatorLoc();
18712   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18713     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18714   else {
18715     // Not an assignment.
18716     return;
18717   }
18718 
18719   Diag(Loc, diagnostic) << E->getSourceRange();
18720 
18721   SourceLocation Open = E->getBeginLoc();
18722   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18723   Diag(Loc, diag::note_condition_assign_silence)
18724         << FixItHint::CreateInsertion(Open, "(")
18725         << FixItHint::CreateInsertion(Close, ")");
18726 
18727   if (IsOrAssign)
18728     Diag(Loc, diag::note_condition_or_assign_to_comparison)
18729       << FixItHint::CreateReplacement(Loc, "!=");
18730   else
18731     Diag(Loc, diag::note_condition_assign_to_comparison)
18732       << FixItHint::CreateReplacement(Loc, "==");
18733 }
18734 
18735 /// Redundant parentheses over an equality comparison can indicate
18736 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)18737 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18738   // Don't warn if the parens came from a macro.
18739   SourceLocation parenLoc = ParenE->getBeginLoc();
18740   if (parenLoc.isInvalid() || parenLoc.isMacroID())
18741     return;
18742   // Don't warn for dependent expressions.
18743   if (ParenE->isTypeDependent())
18744     return;
18745 
18746   Expr *E = ParenE->IgnoreParens();
18747 
18748   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18749     if (opE->getOpcode() == BO_EQ &&
18750         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18751                                                            == Expr::MLV_Valid) {
18752       SourceLocation Loc = opE->getOperatorLoc();
18753 
18754       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18755       SourceRange ParenERange = ParenE->getSourceRange();
18756       Diag(Loc, diag::note_equality_comparison_silence)
18757         << FixItHint::CreateRemoval(ParenERange.getBegin())
18758         << FixItHint::CreateRemoval(ParenERange.getEnd());
18759       Diag(Loc, diag::note_equality_comparison_to_assign)
18760         << FixItHint::CreateReplacement(Loc, "=");
18761     }
18762 }
18763 
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)18764 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18765                                        bool IsConstexpr) {
18766   DiagnoseAssignmentAsCondition(E);
18767   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18768     DiagnoseEqualityWithExtraParens(parenE);
18769 
18770   ExprResult result = CheckPlaceholderExpr(E);
18771   if (result.isInvalid()) return ExprError();
18772   E = result.get();
18773 
18774   if (!E->isTypeDependent()) {
18775     if (getLangOpts().CPlusPlus)
18776       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18777 
18778     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18779     if (ERes.isInvalid())
18780       return ExprError();
18781     E = ERes.get();
18782 
18783     QualType T = E->getType();
18784     if (!T->isScalarType()) { // C99 6.8.4.1p1
18785       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18786         << T << E->getSourceRange();
18787       return ExprError();
18788     }
18789     CheckBoolLikeConversion(E, Loc);
18790   }
18791 
18792   return E;
18793 }
18794 
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)18795 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18796                                            Expr *SubExpr, ConditionKind CK) {
18797   // Empty conditions are valid in for-statements.
18798   if (!SubExpr)
18799     return ConditionResult();
18800 
18801   ExprResult Cond;
18802   switch (CK) {
18803   case ConditionKind::Boolean:
18804     Cond = CheckBooleanCondition(Loc, SubExpr);
18805     break;
18806 
18807   case ConditionKind::ConstexprIf:
18808     Cond = CheckBooleanCondition(Loc, SubExpr, true);
18809     break;
18810 
18811   case ConditionKind::Switch:
18812     Cond = CheckSwitchCondition(Loc, SubExpr);
18813     break;
18814   }
18815   if (Cond.isInvalid())
18816     return ConditionError();
18817 
18818   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18819   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18820   if (!FullExpr.get())
18821     return ConditionError();
18822 
18823   return ConditionResult(*this, nullptr, FullExpr,
18824                          CK == ConditionKind::ConstexprIf);
18825 }
18826 
18827 namespace {
18828   /// A visitor for rebuilding a call to an __unknown_any expression
18829   /// to have an appropriate type.
18830   struct RebuildUnknownAnyFunction
18831     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18832 
18833     Sema &S;
18834 
RebuildUnknownAnyFunction__anon496515c22011::RebuildUnknownAnyFunction18835     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18836 
VisitStmt__anon496515c22011::RebuildUnknownAnyFunction18837     ExprResult VisitStmt(Stmt *S) {
18838       llvm_unreachable("unexpected statement!");
18839     }
18840 
VisitExpr__anon496515c22011::RebuildUnknownAnyFunction18841     ExprResult VisitExpr(Expr *E) {
18842       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18843         << E->getSourceRange();
18844       return ExprError();
18845     }
18846 
18847     /// Rebuild an expression which simply semantically wraps another
18848     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon496515c22011::RebuildUnknownAnyFunction18849     template <class T> ExprResult rebuildSugarExpr(T *E) {
18850       ExprResult SubResult = Visit(E->getSubExpr());
18851       if (SubResult.isInvalid()) return ExprError();
18852 
18853       Expr *SubExpr = SubResult.get();
18854       E->setSubExpr(SubExpr);
18855       E->setType(SubExpr->getType());
18856       E->setValueKind(SubExpr->getValueKind());
18857       assert(E->getObjectKind() == OK_Ordinary);
18858       return E;
18859     }
18860 
VisitParenExpr__anon496515c22011::RebuildUnknownAnyFunction18861     ExprResult VisitParenExpr(ParenExpr *E) {
18862       return rebuildSugarExpr(E);
18863     }
18864 
VisitUnaryExtension__anon496515c22011::RebuildUnknownAnyFunction18865     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18866       return rebuildSugarExpr(E);
18867     }
18868 
VisitUnaryAddrOf__anon496515c22011::RebuildUnknownAnyFunction18869     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18870       ExprResult SubResult = Visit(E->getSubExpr());
18871       if (SubResult.isInvalid()) return ExprError();
18872 
18873       Expr *SubExpr = SubResult.get();
18874       E->setSubExpr(SubExpr);
18875       E->setType(S.Context.getPointerType(SubExpr->getType()));
18876       assert(E->getValueKind() == VK_RValue);
18877       assert(E->getObjectKind() == OK_Ordinary);
18878       return E;
18879     }
18880 
resolveDecl__anon496515c22011::RebuildUnknownAnyFunction18881     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18882       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18883 
18884       E->setType(VD->getType());
18885 
18886       assert(E->getValueKind() == VK_RValue);
18887       if (S.getLangOpts().CPlusPlus &&
18888           !(isa<CXXMethodDecl>(VD) &&
18889             cast<CXXMethodDecl>(VD)->isInstance()))
18890         E->setValueKind(VK_LValue);
18891 
18892       return E;
18893     }
18894 
VisitMemberExpr__anon496515c22011::RebuildUnknownAnyFunction18895     ExprResult VisitMemberExpr(MemberExpr *E) {
18896       return resolveDecl(E, E->getMemberDecl());
18897     }
18898 
VisitDeclRefExpr__anon496515c22011::RebuildUnknownAnyFunction18899     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18900       return resolveDecl(E, E->getDecl());
18901     }
18902   };
18903 }
18904 
18905 /// Given a function expression of unknown-any type, try to rebuild it
18906 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)18907 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18908   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18909   if (Result.isInvalid()) return ExprError();
18910   return S.DefaultFunctionArrayConversion(Result.get());
18911 }
18912 
18913 namespace {
18914   /// A visitor for rebuilding an expression of type __unknown_anytype
18915   /// into one which resolves the type directly on the referring
18916   /// expression.  Strict preservation of the original source
18917   /// structure is not a goal.
18918   struct RebuildUnknownAnyExpr
18919     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18920 
18921     Sema &S;
18922 
18923     /// The current destination type.
18924     QualType DestType;
18925 
RebuildUnknownAnyExpr__anon496515c22111::RebuildUnknownAnyExpr18926     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18927       : S(S), DestType(CastType) {}
18928 
VisitStmt__anon496515c22111::RebuildUnknownAnyExpr18929     ExprResult VisitStmt(Stmt *S) {
18930       llvm_unreachable("unexpected statement!");
18931     }
18932 
VisitExpr__anon496515c22111::RebuildUnknownAnyExpr18933     ExprResult VisitExpr(Expr *E) {
18934       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18935         << E->getSourceRange();
18936       return ExprError();
18937     }
18938 
18939     ExprResult VisitCallExpr(CallExpr *E);
18940     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18941 
18942     /// Rebuild an expression which simply semantically wraps another
18943     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon496515c22111::RebuildUnknownAnyExpr18944     template <class T> ExprResult rebuildSugarExpr(T *E) {
18945       ExprResult SubResult = Visit(E->getSubExpr());
18946       if (SubResult.isInvalid()) return ExprError();
18947       Expr *SubExpr = SubResult.get();
18948       E->setSubExpr(SubExpr);
18949       E->setType(SubExpr->getType());
18950       E->setValueKind(SubExpr->getValueKind());
18951       assert(E->getObjectKind() == OK_Ordinary);
18952       return E;
18953     }
18954 
VisitParenExpr__anon496515c22111::RebuildUnknownAnyExpr18955     ExprResult VisitParenExpr(ParenExpr *E) {
18956       return rebuildSugarExpr(E);
18957     }
18958 
VisitUnaryExtension__anon496515c22111::RebuildUnknownAnyExpr18959     ExprResult VisitUnaryExtension(UnaryOperator *E) {
18960       return rebuildSugarExpr(E);
18961     }
18962 
VisitUnaryAddrOf__anon496515c22111::RebuildUnknownAnyExpr18963     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18964       const PointerType *Ptr = DestType->getAs<PointerType>();
18965       if (!Ptr) {
18966         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18967           << E->getSourceRange();
18968         return ExprError();
18969       }
18970 
18971       if (isa<CallExpr>(E->getSubExpr())) {
18972         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18973           << E->getSourceRange();
18974         return ExprError();
18975       }
18976 
18977       assert(E->getValueKind() == VK_RValue);
18978       assert(E->getObjectKind() == OK_Ordinary);
18979       E->setType(DestType);
18980 
18981       // Build the sub-expression as if it were an object of the pointee type.
18982       DestType = Ptr->getPointeeType();
18983       ExprResult SubResult = Visit(E->getSubExpr());
18984       if (SubResult.isInvalid()) return ExprError();
18985       E->setSubExpr(SubResult.get());
18986       return E;
18987     }
18988 
18989     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18990 
18991     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18992 
VisitMemberExpr__anon496515c22111::RebuildUnknownAnyExpr18993     ExprResult VisitMemberExpr(MemberExpr *E) {
18994       return resolveDecl(E, E->getMemberDecl());
18995     }
18996 
VisitDeclRefExpr__anon496515c22111::RebuildUnknownAnyExpr18997     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18998       return resolveDecl(E, E->getDecl());
18999     }
19000   };
19001 }
19002 
19003 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)19004 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19005   Expr *CalleeExpr = E->getCallee();
19006 
19007   enum FnKind {
19008     FK_MemberFunction,
19009     FK_FunctionPointer,
19010     FK_BlockPointer
19011   };
19012 
19013   FnKind Kind;
19014   QualType CalleeType = CalleeExpr->getType();
19015   if (CalleeType == S.Context.BoundMemberTy) {
19016     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19017     Kind = FK_MemberFunction;
19018     CalleeType = Expr::findBoundMemberType(CalleeExpr);
19019   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19020     CalleeType = Ptr->getPointeeType();
19021     Kind = FK_FunctionPointer;
19022   } else {
19023     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19024     Kind = FK_BlockPointer;
19025   }
19026   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19027 
19028   // Verify that this is a legal result type of a function.
19029   if (DestType->isArrayType() || DestType->isFunctionType()) {
19030     unsigned diagID = diag::err_func_returning_array_function;
19031     if (Kind == FK_BlockPointer)
19032       diagID = diag::err_block_returning_array_function;
19033 
19034     S.Diag(E->getExprLoc(), diagID)
19035       << DestType->isFunctionType() << DestType;
19036     return ExprError();
19037   }
19038 
19039   // Otherwise, go ahead and set DestType as the call's result.
19040   E->setType(DestType.getNonLValueExprType(S.Context));
19041   E->setValueKind(Expr::getValueKindForType(DestType));
19042   assert(E->getObjectKind() == OK_Ordinary);
19043 
19044   // Rebuild the function type, replacing the result type with DestType.
19045   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19046   if (Proto) {
19047     // __unknown_anytype(...) is a special case used by the debugger when
19048     // it has no idea what a function's signature is.
19049     //
19050     // We want to build this call essentially under the K&R
19051     // unprototyped rules, but making a FunctionNoProtoType in C++
19052     // would foul up all sorts of assumptions.  However, we cannot
19053     // simply pass all arguments as variadic arguments, nor can we
19054     // portably just call the function under a non-variadic type; see
19055     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19056     // However, it turns out that in practice it is generally safe to
19057     // call a function declared as "A foo(B,C,D);" under the prototype
19058     // "A foo(B,C,D,...);".  The only known exception is with the
19059     // Windows ABI, where any variadic function is implicitly cdecl
19060     // regardless of its normal CC.  Therefore we change the parameter
19061     // types to match the types of the arguments.
19062     //
19063     // This is a hack, but it is far superior to moving the
19064     // corresponding target-specific code from IR-gen to Sema/AST.
19065 
19066     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19067     SmallVector<QualType, 8> ArgTypes;
19068     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19069       ArgTypes.reserve(E->getNumArgs());
19070       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19071         Expr *Arg = E->getArg(i);
19072         QualType ArgType = Arg->getType();
19073         if (E->isLValue()) {
19074           ArgType = S.Context.getLValueReferenceType(ArgType);
19075         } else if (E->isXValue()) {
19076           ArgType = S.Context.getRValueReferenceType(ArgType);
19077         }
19078         ArgTypes.push_back(ArgType);
19079       }
19080       ParamTypes = ArgTypes;
19081     }
19082     DestType = S.Context.getFunctionType(DestType, ParamTypes,
19083                                          Proto->getExtProtoInfo());
19084   } else {
19085     DestType = S.Context.getFunctionNoProtoType(DestType,
19086                                                 FnType->getExtInfo());
19087   }
19088 
19089   // Rebuild the appropriate pointer-to-function type.
19090   switch (Kind) {
19091   case FK_MemberFunction:
19092     // Nothing to do.
19093     break;
19094 
19095   case FK_FunctionPointer:
19096     DestType = S.Context.getPointerType(DestType);
19097     break;
19098 
19099   case FK_BlockPointer:
19100     DestType = S.Context.getBlockPointerType(DestType);
19101     break;
19102   }
19103 
19104   // Finally, we can recurse.
19105   ExprResult CalleeResult = Visit(CalleeExpr);
19106   if (!CalleeResult.isUsable()) return ExprError();
19107   E->setCallee(CalleeResult.get());
19108 
19109   // Bind a temporary if necessary.
19110   return S.MaybeBindToTemporary(E);
19111 }
19112 
VisitObjCMessageExpr(ObjCMessageExpr * E)19113 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19114   // Verify that this is a legal result type of a call.
19115   if (DestType->isArrayType() || DestType->isFunctionType()) {
19116     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19117       << DestType->isFunctionType() << DestType;
19118     return ExprError();
19119   }
19120 
19121   // Rewrite the method result type if available.
19122   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19123     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19124     Method->setReturnType(DestType);
19125   }
19126 
19127   // Change the type of the message.
19128   E->setType(DestType.getNonReferenceType());
19129   E->setValueKind(Expr::getValueKindForType(DestType));
19130 
19131   return S.MaybeBindToTemporary(E);
19132 }
19133 
VisitImplicitCastExpr(ImplicitCastExpr * E)19134 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19135   // The only case we should ever see here is a function-to-pointer decay.
19136   if (E->getCastKind() == CK_FunctionToPointerDecay) {
19137     assert(E->getValueKind() == VK_RValue);
19138     assert(E->getObjectKind() == OK_Ordinary);
19139 
19140     E->setType(DestType, S.Context, E->getSubExpr());
19141 
19142     // Rebuild the sub-expression as the pointee (function) type.
19143     DestType = DestType->castAs<PointerType>()->getPointeeType();
19144 
19145     ExprResult Result = Visit(E->getSubExpr());
19146     if (!Result.isUsable()) return ExprError();
19147 
19148     E->setSubExpr(Result.get());
19149     return E;
19150   } else if (E->getCastKind() == CK_LValueToRValue) {
19151     assert(E->getValueKind() == VK_RValue);
19152     assert(E->getObjectKind() == OK_Ordinary);
19153 
19154     assert(isa<BlockPointerType>(E->getType()));
19155 
19156     E->setType(DestType, S.Context, E->getSubExpr());
19157 
19158     // The sub-expression has to be a lvalue reference, so rebuild it as such.
19159     DestType = S.Context.getLValueReferenceType(DestType);
19160 
19161     ExprResult Result = Visit(E->getSubExpr());
19162     if (!Result.isUsable()) return ExprError();
19163 
19164     E->setSubExpr(Result.get());
19165     return E;
19166   } else {
19167     llvm_unreachable("Unhandled cast type!");
19168   }
19169 }
19170 
resolveDecl(Expr * E,ValueDecl * VD)19171 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19172   ExprValueKind ValueKind = VK_LValue;
19173   QualType Type = DestType;
19174 
19175   // We know how to make this work for certain kinds of decls:
19176 
19177   //  - functions
19178   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19179     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19180       DestType = Ptr->getPointeeType();
19181       ExprResult Result = resolveDecl(E, VD);
19182       if (Result.isInvalid()) return ExprError();
19183       return S.ImpCastExprToType(Result.get(), Type,
19184                                  CK_FunctionToPointerDecay, VK_RValue);
19185     }
19186 
19187     if (!Type->isFunctionType()) {
19188       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19189         << VD << E->getSourceRange();
19190       return ExprError();
19191     }
19192     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19193       // We must match the FunctionDecl's type to the hack introduced in
19194       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19195       // type. See the lengthy commentary in that routine.
19196       QualType FDT = FD->getType();
19197       const FunctionType *FnType = FDT->castAs<FunctionType>();
19198       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19199       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19200       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19201         SourceLocation Loc = FD->getLocation();
19202         FunctionDecl *NewFD = FunctionDecl::Create(
19203             S.Context, FD->getDeclContext(), Loc, Loc,
19204             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19205             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19206             /*ConstexprKind*/ CSK_unspecified);
19207 
19208         if (FD->getQualifier())
19209           NewFD->setQualifierInfo(FD->getQualifierLoc());
19210 
19211         SmallVector<ParmVarDecl*, 16> Params;
19212         for (const auto &AI : FT->param_types()) {
19213           ParmVarDecl *Param =
19214             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19215           Param->setScopeInfo(0, Params.size());
19216           Params.push_back(Param);
19217         }
19218         NewFD->setParams(Params);
19219         DRE->setDecl(NewFD);
19220         VD = DRE->getDecl();
19221       }
19222     }
19223 
19224     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19225       if (MD->isInstance()) {
19226         ValueKind = VK_RValue;
19227         Type = S.Context.BoundMemberTy;
19228       }
19229 
19230     // Function references aren't l-values in C.
19231     if (!S.getLangOpts().CPlusPlus)
19232       ValueKind = VK_RValue;
19233 
19234   //  - variables
19235   } else if (isa<VarDecl>(VD)) {
19236     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19237       Type = RefTy->getPointeeType();
19238     } else if (Type->isFunctionType()) {
19239       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19240         << VD << E->getSourceRange();
19241       return ExprError();
19242     }
19243 
19244   //  - nothing else
19245   } else {
19246     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19247       << VD << E->getSourceRange();
19248     return ExprError();
19249   }
19250 
19251   // Modifying the declaration like this is friendly to IR-gen but
19252   // also really dangerous.
19253   VD->setType(DestType);
19254   E->setType(Type);
19255   E->setValueKind(ValueKind);
19256   return E;
19257 }
19258 
19259 /// Check a cast of an unknown-any type.  We intentionally only
19260 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)19261 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19262                                      Expr *CastExpr, CastKind &CastKind,
19263                                      ExprValueKind &VK, CXXCastPath &Path) {
19264   // The type we're casting to must be either void or complete.
19265   if (!CastType->isVoidType() &&
19266       RequireCompleteType(TypeRange.getBegin(), CastType,
19267                           diag::err_typecheck_cast_to_incomplete))
19268     return ExprError();
19269 
19270   // Rewrite the casted expression from scratch.
19271   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19272   if (!result.isUsable()) return ExprError();
19273 
19274   CastExpr = result.get();
19275   VK = CastExpr->getValueKind();
19276   CastKind = CK_NoOp;
19277 
19278   return CastExpr;
19279 }
19280 
forceUnknownAnyToType(Expr * E,QualType ToType)19281 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19282   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19283 }
19284 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)19285 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19286                                     Expr *arg, QualType &paramType) {
19287   // If the syntactic form of the argument is not an explicit cast of
19288   // any sort, just do default argument promotion.
19289   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19290   if (!castArg) {
19291     ExprResult result = DefaultArgumentPromotion(arg);
19292     if (result.isInvalid()) return ExprError();
19293     paramType = result.get()->getType();
19294     return result;
19295   }
19296 
19297   // Otherwise, use the type that was written in the explicit cast.
19298   assert(!arg->hasPlaceholderType());
19299   paramType = castArg->getTypeAsWritten();
19300 
19301   // Copy-initialize a parameter of that type.
19302   InitializedEntity entity =
19303     InitializedEntity::InitializeParameter(Context, paramType,
19304                                            /*consumed*/ false);
19305   return PerformCopyInitialization(entity, callLoc, arg);
19306 }
19307 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)19308 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19309   Expr *orig = E;
19310   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19311   while (true) {
19312     E = E->IgnoreParenImpCasts();
19313     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19314       E = call->getCallee();
19315       diagID = diag::err_uncasted_call_of_unknown_any;
19316     } else {
19317       break;
19318     }
19319   }
19320 
19321   SourceLocation loc;
19322   NamedDecl *d;
19323   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19324     loc = ref->getLocation();
19325     d = ref->getDecl();
19326   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19327     loc = mem->getMemberLoc();
19328     d = mem->getMemberDecl();
19329   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19330     diagID = diag::err_uncasted_call_of_unknown_any;
19331     loc = msg->getSelectorStartLoc();
19332     d = msg->getMethodDecl();
19333     if (!d) {
19334       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19335         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19336         << orig->getSourceRange();
19337       return ExprError();
19338     }
19339   } else {
19340     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19341       << E->getSourceRange();
19342     return ExprError();
19343   }
19344 
19345   S.Diag(loc, diagID) << d << orig->getSourceRange();
19346 
19347   // Never recoverable.
19348   return ExprError();
19349 }
19350 
19351 /// Check for operands with placeholder types and complain if found.
19352 /// Returns ExprError() if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)19353 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19354   if (!getLangOpts().CPlusPlus) {
19355     // C cannot handle TypoExpr nodes on either side of a binop because it
19356     // doesn't handle dependent types properly, so make sure any TypoExprs have
19357     // been dealt with before checking the operands.
19358     ExprResult Result = CorrectDelayedTyposInExpr(E);
19359     if (!Result.isUsable()) return ExprError();
19360     E = Result.get();
19361   }
19362 
19363   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19364   if (!placeholderType) return E;
19365 
19366   switch (placeholderType->getKind()) {
19367 
19368   // Overloaded expressions.
19369   case BuiltinType::Overload: {
19370     // Try to resolve a single function template specialization.
19371     // This is obligatory.
19372     ExprResult Result = E;
19373     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19374       return Result;
19375 
19376     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19377     // leaves Result unchanged on failure.
19378     Result = E;
19379     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19380       return Result;
19381 
19382     // If that failed, try to recover with a call.
19383     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19384                          /*complain*/ true);
19385     return Result;
19386   }
19387 
19388   // Bound member functions.
19389   case BuiltinType::BoundMember: {
19390     ExprResult result = E;
19391     const Expr *BME = E->IgnoreParens();
19392     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19393     // Try to give a nicer diagnostic if it is a bound member that we recognize.
19394     if (isa<CXXPseudoDestructorExpr>(BME)) {
19395       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19396     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19397       if (ME->getMemberNameInfo().getName().getNameKind() ==
19398           DeclarationName::CXXDestructorName)
19399         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19400     }
19401     tryToRecoverWithCall(result, PD,
19402                          /*complain*/ true);
19403     return result;
19404   }
19405 
19406   // ARC unbridged casts.
19407   case BuiltinType::ARCUnbridgedCast: {
19408     Expr *realCast = stripARCUnbridgedCast(E);
19409     diagnoseARCUnbridgedCast(realCast);
19410     return realCast;
19411   }
19412 
19413   // Expressions of unknown type.
19414   case BuiltinType::UnknownAny:
19415     return diagnoseUnknownAnyExpr(*this, E);
19416 
19417   // Pseudo-objects.
19418   case BuiltinType::PseudoObject:
19419     return checkPseudoObjectRValue(E);
19420 
19421   case BuiltinType::BuiltinFn: {
19422     // Accept __noop without parens by implicitly converting it to a call expr.
19423     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19424     if (DRE) {
19425       auto *FD = cast<FunctionDecl>(DRE->getDecl());
19426       if (FD->getBuiltinID() == Builtin::BI__noop) {
19427         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19428                               CK_BuiltinFnToFnPtr)
19429                 .get();
19430         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19431                                 VK_RValue, SourceLocation());
19432       }
19433     }
19434 
19435     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19436     return ExprError();
19437   }
19438 
19439   case BuiltinType::IncompleteMatrixIdx:
19440     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19441              ->getRowIdx()
19442              ->getBeginLoc(),
19443          diag::err_matrix_incomplete_index);
19444     return ExprError();
19445 
19446   // Expressions of unknown type.
19447   case BuiltinType::OMPArraySection:
19448     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19449     return ExprError();
19450 
19451   // Expressions of unknown type.
19452   case BuiltinType::OMPArrayShaping:
19453     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19454 
19455   case BuiltinType::OMPIterator:
19456     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19457 
19458   // Everything else should be impossible.
19459 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19460   case BuiltinType::Id:
19461 #include "clang/Basic/OpenCLImageTypes.def"
19462 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19463   case BuiltinType::Id:
19464 #include "clang/Basic/OpenCLExtensionTypes.def"
19465 #define SVE_TYPE(Name, Id, SingletonId) \
19466   case BuiltinType::Id:
19467 #include "clang/Basic/AArch64SVEACLETypes.def"
19468 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19469 #define PLACEHOLDER_TYPE(Id, SingletonId)
19470 #include "clang/AST/BuiltinTypes.def"
19471     break;
19472   }
19473 
19474   llvm_unreachable("invalid placeholder type!");
19475 }
19476 
CheckCaseExpression(Expr * E)19477 bool Sema::CheckCaseExpression(Expr *E) {
19478   if (E->isTypeDependent())
19479     return true;
19480   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19481     return E->getType()->isIntegralOrEnumerationType();
19482   return false;
19483 }
19484 
19485 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19486 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)19487 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19488   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19489          "Unknown Objective-C Boolean value!");
19490   QualType BoolT = Context.ObjCBuiltinBoolTy;
19491   if (!Context.getBOOLDecl()) {
19492     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19493                         Sema::LookupOrdinaryName);
19494     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19495       NamedDecl *ND = Result.getFoundDecl();
19496       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19497         Context.setBOOLDecl(TD);
19498     }
19499   }
19500   if (Context.getBOOLDecl())
19501     BoolT = Context.getBOOLType();
19502   return new (Context)
19503       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19504 }
19505 
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,SourceLocation AtLoc,SourceLocation RParen)19506 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19507     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19508     SourceLocation RParen) {
19509 
19510   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19511 
19512   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19513     return Spec.getPlatform() == Platform;
19514   });
19515 
19516   VersionTuple Version;
19517   if (Spec != AvailSpecs.end())
19518     Version = Spec->getVersion();
19519 
19520   // The use of `@available` in the enclosing function should be analyzed to
19521   // warn when it's used inappropriately (i.e. not if(@available)).
19522   if (getCurFunctionOrMethodDecl())
19523     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19524   else if (getCurBlock() || getCurLambda())
19525     getCurFunction()->HasPotentialAvailabilityViolations = true;
19526 
19527   return new (Context)
19528       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19529 }
19530 
CreateRecoveryExpr(SourceLocation Begin,SourceLocation End,ArrayRef<Expr * > SubExprs,QualType T)19531 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19532                                     ArrayRef<Expr *> SubExprs, QualType T) {
19533   if (!Context.getLangOpts().RecoveryAST)
19534     return ExprError();
19535 
19536   if (isSFINAEContext())
19537     return ExprError();
19538 
19539   if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19540     // We don't know the concrete type, fallback to dependent type.
19541     T = Context.DependentTy;
19542   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19543 }
19544