• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
HasRedeclarationWithoutAvailabilityInCategory(const Decl * D)90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 static AvailabilityResult
DiagnoseAvailabilityOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108                            const ObjCInterfaceDecl *UnknownObjCClass,
109                            bool ObjCPropertyAccess) {
110   // See if this declaration is unavailable or deprecated.
111   std::string Message;
112   AvailabilityResult Result = D->getAvailability(&Message);
113 
114   // For typedefs, if the typedef declaration appears available look
115   // to the underlying type to see if it is more restrictive.
116   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
117     if (Result == AR_Available) {
118       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
119         D = TT->getDecl();
120         Result = D->getAvailability(&Message);
121         continue;
122       }
123     }
124     break;
125   }
126 
127   // Forward class declarations get their attributes from their definition.
128   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
129     if (IDecl->getDefinition()) {
130       D = IDecl->getDefinition();
131       Result = D->getAvailability(&Message);
132     }
133   }
134 
135   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136     if (Result == AR_Available) {
137       const DeclContext *DC = ECD->getDeclContext();
138       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139         Result = TheEnumDecl->getAvailability(&Message);
140     }
141 
142   const ObjCPropertyDecl *ObjCPDecl = nullptr;
143   if (Result == AR_Deprecated || Result == AR_Unavailable ||
144       Result == AR_NotYetIntroduced) {
145     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
147         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
148         if (PDeclResult == Result)
149           ObjCPDecl = PD;
150       }
151     }
152   }
153 
154   switch (Result) {
155     case AR_Available:
156       break;
157 
158     case AR_Deprecated:
159       if (S.getCurContextAvailability() != AR_Deprecated)
160         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
161                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
162                                   ObjCPropertyAccess);
163       break;
164 
165     case AR_NotYetIntroduced: {
166       // Don't do this for enums, they can't be redeclared.
167       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
168         break;
169 
170       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
171       // Objective-C method declarations in categories are not modelled as
172       // redeclarations, so manually look for a redeclaration in a category
173       // if necessary.
174       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
175         Warn = false;
176       // In general, D will point to the most recent redeclaration. However,
177       // for `@class A;` decls, this isn't true -- manually go through the
178       // redecl chain in that case.
179       if (Warn && isa<ObjCInterfaceDecl>(D))
180         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181              Redecl = Redecl->getPreviousDecl())
182           if (!Redecl->hasAttr<AvailabilityAttr>() ||
183               Redecl->getAttr<AvailabilityAttr>()->isInherited())
184             Warn = false;
185 
186       if (Warn)
187         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188                                   UnknownObjCClass, ObjCPDecl,
189                                   ObjCPropertyAccess);
190       break;
191     }
192 
193     case AR_Unavailable:
194       if (S.getCurContextAvailability() != AR_Unavailable)
195         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
196                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
197                                   ObjCPropertyAccess);
198       break;
199 
200     }
201     return Result;
202 }
203 
204 /// \brief Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
206   assert(Decl->isDeleted());
207 
208   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
209 
210   if (Method && Method->isDeleted() && Method->isDefaulted()) {
211     // If the method was explicitly defaulted, point at that declaration.
212     if (!Method->isImplicit())
213       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
214 
215     // Try to diagnose why this special member function was implicitly
216     // deleted. This might fail, if that reason no longer applies.
217     CXXSpecialMember CSM = getSpecialMember(Method);
218     if (CSM != CXXInvalid)
219       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
220 
221     return;
222   }
223 
224   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
225   if (Ctor && Ctor->isInheritingConstructor())
226     return NoteDeletedInheritingConstructor(Ctor);
227 
228   Diag(Decl->getLocation(), diag::note_availability_specified_here)
229     << Decl << true;
230 }
231 
232 /// \brief Determine whether a FunctionDecl was ever declared with an
233 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)234 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
235   for (auto I : D->redecls()) {
236     if (I->getStorageClass() != SC_None)
237       return true;
238   }
239   return false;
240 }
241 
242 /// \brief Check whether we're in an extern inline function and referring to a
243 /// variable or function with internal linkage (C11 6.7.4p3).
244 ///
245 /// This is only a warning because we used to silently accept this code, but
246 /// in many cases it will not behave correctly. This is not enabled in C++ mode
247 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
248 /// and so while there may still be user mistakes, most of the time we can't
249 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)250 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
251                                                       const NamedDecl *D,
252                                                       SourceLocation Loc) {
253   // This is disabled under C++; there are too many ways for this to fire in
254   // contexts where the warning is a false positive, or where it is technically
255   // correct but benign.
256   if (S.getLangOpts().CPlusPlus)
257     return;
258 
259   // Check if this is an inlined function or method.
260   FunctionDecl *Current = S.getCurFunctionDecl();
261   if (!Current)
262     return;
263   if (!Current->isInlined())
264     return;
265   if (!Current->isExternallyVisible())
266     return;
267 
268   // Check if the decl has internal linkage.
269   if (D->getFormalLinkage() != InternalLinkage)
270     return;
271 
272   // Downgrade from ExtWarn to Extension if
273   //  (1) the supposedly external inline function is in the main file,
274   //      and probably won't be included anywhere else.
275   //  (2) the thing we're referencing is a pure function.
276   //  (3) the thing we're referencing is another inline function.
277   // This last can give us false negatives, but it's better than warning on
278   // wrappers for simple C library functions.
279   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
280   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
281   if (!DowngradeWarning && UsedFn)
282     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
283 
284   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
285                                : diag::ext_internal_in_extern_inline)
286     << /*IsVar=*/!UsedFn << D;
287 
288   S.MaybeSuggestAddingStaticToDecl(Current);
289 
290   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
291       << D;
292 }
293 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)294 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
295   const FunctionDecl *First = Cur->getFirstDecl();
296 
297   // Suggest "static" on the function, if possible.
298   if (!hasAnyExplicitStorageClass(First)) {
299     SourceLocation DeclBegin = First->getSourceRange().getBegin();
300     Diag(DeclBegin, diag::note_convert_inline_to_static)
301       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
302   }
303 }
304 
305 /// \brief Determine whether the use of this declaration is valid, and
306 /// emit any corresponding diagnostics.
307 ///
308 /// This routine diagnoses various problems with referencing
309 /// declarations that can occur when using a declaration. For example,
310 /// it might warn if a deprecated or unavailable declaration is being
311 /// used, or produce an error (and return true) if a C++0x deleted
312 /// function is being used.
313 ///
314 /// \returns true if there was an error (this declaration cannot be
315 /// referenced), false otherwise.
316 ///
DiagnoseUseOfDecl(NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)317 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
318                              const ObjCInterfaceDecl *UnknownObjCClass,
319                              bool ObjCPropertyAccess) {
320   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
321     // If there were any diagnostics suppressed by template argument deduction,
322     // emit them now.
323     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
324     if (Pos != SuppressedDiagnostics.end()) {
325       for (const PartialDiagnosticAt &Suppressed : Pos->second)
326         Diag(Suppressed.first, Suppressed.second);
327 
328       // Clear out the list of suppressed diagnostics, so that we don't emit
329       // them again for this specialization. However, we don't obsolete this
330       // entry from the table, because we want to avoid ever emitting these
331       // diagnostics again.
332       Pos->second.clear();
333     }
334 
335     // C++ [basic.start.main]p3:
336     //   The function 'main' shall not be used within a program.
337     if (cast<FunctionDecl>(D)->isMain())
338       Diag(Loc, diag::ext_main_used);
339   }
340 
341   // See if this is an auto-typed variable whose initializer we are parsing.
342   if (ParsingInitForAutoVars.count(D)) {
343     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
344 
345     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
346       << D->getDeclName() << (unsigned)AT->getKeyword();
347     return true;
348   }
349 
350   // See if this is a deleted function.
351   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352     if (FD->isDeleted()) {
353       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
354       if (Ctor && Ctor->isInheritingConstructor())
355         Diag(Loc, diag::err_deleted_inherited_ctor_use)
356             << Ctor->getParent()
357             << Ctor->getInheritedConstructor().getConstructor()->getParent();
358       else
359         Diag(Loc, diag::err_deleted_function_use);
360       NoteDeletedFunction(FD);
361       return true;
362     }
363 
364     // If the function has a deduced return type, and we can't deduce it,
365     // then we can't use it either.
366     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
367         DeduceReturnType(FD, Loc))
368       return true;
369   }
370 
371   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372   // Only the variables omp_in and omp_out are allowed in the combiner.
373   // Only the variables omp_priv and omp_orig are allowed in the
374   // initializer-clause.
375   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
377       isa<VarDecl>(D)) {
378     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379         << getCurFunction()->HasOMPDeclareReductionCombiner;
380     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
381     return true;
382   }
383   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
384                              ObjCPropertyAccess);
385 
386   DiagnoseUnusedOfDecl(*this, D, Loc);
387 
388   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
389 
390   return false;
391 }
392 
393 /// \brief Retrieve the message suffix that should be added to a
394 /// diagnostic complaining about the given function being deleted or
395 /// unavailable.
getDeletedOrUnavailableSuffix(const FunctionDecl * FD)396 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
397   std::string Message;
398   if (FD->getAvailability(&Message))
399     return ": " + Message;
400 
401   return std::string();
402 }
403 
404 /// DiagnoseSentinelCalls - This routine checks whether a call or
405 /// message-send is to a declaration with the sentinel attribute, and
406 /// if so, it checks that the requirements of the sentinel are
407 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)408 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
409                                  ArrayRef<Expr *> Args) {
410   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
411   if (!attr)
412     return;
413 
414   // The number of formal parameters of the declaration.
415   unsigned numFormalParams;
416 
417   // The kind of declaration.  This is also an index into a %select in
418   // the diagnostic.
419   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
420 
421   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
422     numFormalParams = MD->param_size();
423     calleeType = CT_Method;
424   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
425     numFormalParams = FD->param_size();
426     calleeType = CT_Function;
427   } else if (isa<VarDecl>(D)) {
428     QualType type = cast<ValueDecl>(D)->getType();
429     const FunctionType *fn = nullptr;
430     if (const PointerType *ptr = type->getAs<PointerType>()) {
431       fn = ptr->getPointeeType()->getAs<FunctionType>();
432       if (!fn) return;
433       calleeType = CT_Function;
434     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
435       fn = ptr->getPointeeType()->castAs<FunctionType>();
436       calleeType = CT_Block;
437     } else {
438       return;
439     }
440 
441     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
442       numFormalParams = proto->getNumParams();
443     } else {
444       numFormalParams = 0;
445     }
446   } else {
447     return;
448   }
449 
450   // "nullPos" is the number of formal parameters at the end which
451   // effectively count as part of the variadic arguments.  This is
452   // useful if you would prefer to not have *any* formal parameters,
453   // but the language forces you to have at least one.
454   unsigned nullPos = attr->getNullPos();
455   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
456   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
457 
458   // The number of arguments which should follow the sentinel.
459   unsigned numArgsAfterSentinel = attr->getSentinel();
460 
461   // If there aren't enough arguments for all the formal parameters,
462   // the sentinel, and the args after the sentinel, complain.
463   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
464     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
465     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
466     return;
467   }
468 
469   // Otherwise, find the sentinel expression.
470   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
471   if (!sentinelExpr) return;
472   if (sentinelExpr->isValueDependent()) return;
473   if (Context.isSentinelNullExpr(sentinelExpr)) return;
474 
475   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
476   // or 'NULL' if those are actually defined in the context.  Only use
477   // 'nil' for ObjC methods, where it's much more likely that the
478   // variadic arguments form a list of object pointers.
479   SourceLocation MissingNilLoc
480     = getLocForEndOfToken(sentinelExpr->getLocEnd());
481   std::string NullValue;
482   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
483     NullValue = "nil";
484   else if (getLangOpts().CPlusPlus11)
485     NullValue = "nullptr";
486   else if (PP.isMacroDefined("NULL"))
487     NullValue = "NULL";
488   else
489     NullValue = "(void*) 0";
490 
491   if (MissingNilLoc.isInvalid())
492     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
493   else
494     Diag(MissingNilLoc, diag::warn_missing_sentinel)
495       << int(calleeType)
496       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
497   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
498 }
499 
getExprRange(Expr * E) const500 SourceRange Sema::getExprRange(Expr *E) const {
501   return E ? E->getSourceRange() : SourceRange();
502 }
503 
504 //===----------------------------------------------------------------------===//
505 //  Standard Promotions and Conversions
506 //===----------------------------------------------------------------------===//
507 
508 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)509 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
510   // Handle any placeholder expressions which made it here.
511   if (E->getType()->isPlaceholderType()) {
512     ExprResult result = CheckPlaceholderExpr(E);
513     if (result.isInvalid()) return ExprError();
514     E = result.get();
515   }
516 
517   QualType Ty = E->getType();
518   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
519 
520   if (Ty->isFunctionType()) {
521     // If we are here, we are not calling a function but taking
522     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
523     if (getLangOpts().OpenCL) {
524       if (Diagnose)
525         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
526       return ExprError();
527     }
528 
529     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
530       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
532           return ExprError();
533 
534     E = ImpCastExprToType(E, Context.getPointerType(Ty),
535                           CK_FunctionToPointerDecay).get();
536   } else if (Ty->isArrayType()) {
537     // In C90 mode, arrays only promote to pointers if the array expression is
538     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
539     // type 'array of type' is converted to an expression that has type 'pointer
540     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
541     // that has type 'array of type' ...".  The relevant change is "an lvalue"
542     // (C90) to "an expression" (C99).
543     //
544     // C++ 4.2p1:
545     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
546     // T" can be converted to an rvalue of type "pointer to T".
547     //
548     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
549       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
550                             CK_ArrayToPointerDecay).get();
551   }
552   return E;
553 }
554 
CheckForNullPointerDereference(Sema & S,Expr * E)555 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
556   // Check to see if we are dereferencing a null pointer.  If so,
557   // and if not volatile-qualified, this is undefined behavior that the
558   // optimizer will delete, so warn about it.  People sometimes try to use this
559   // to get a deterministic trap and are surprised by clang's behavior.  This
560   // only handles the pattern "*null", which is a very syntactic check.
561   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
562     if (UO->getOpcode() == UO_Deref &&
563         UO->getSubExpr()->IgnoreParenCasts()->
564           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
565         !UO->getType().isVolatileQualified()) {
566     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567                           S.PDiag(diag::warn_indirection_through_null)
568                             << UO->getSubExpr()->getSourceRange());
569     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570                         S.PDiag(diag::note_indirection_through_null));
571   }
572 }
573 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)574 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
575                                     SourceLocation AssignLoc,
576                                     const Expr* RHS) {
577   const ObjCIvarDecl *IV = OIRE->getDecl();
578   if (!IV)
579     return;
580 
581   DeclarationName MemberName = IV->getDeclName();
582   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
583   if (!Member || !Member->isStr("isa"))
584     return;
585 
586   const Expr *Base = OIRE->getBase();
587   QualType BaseType = Base->getType();
588   if (OIRE->isArrow())
589     BaseType = BaseType->getPointeeType();
590   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
591     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
592       ObjCInterfaceDecl *ClassDeclared = nullptr;
593       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
594       if (!ClassDeclared->getSuperClass()
595           && (*ClassDeclared->ivar_begin()) == IV) {
596         if (RHS) {
597           NamedDecl *ObjectSetClass =
598             S.LookupSingleName(S.TUScope,
599                                &S.Context.Idents.get("object_setClass"),
600                                SourceLocation(), S.LookupOrdinaryName);
601           if (ObjectSetClass) {
602             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
603             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
604             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
605             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
606                                                      AssignLoc), ",") <<
607             FixItHint::CreateInsertion(RHSLocEnd, ")");
608           }
609           else
610             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
611         } else {
612           NamedDecl *ObjectGetClass =
613             S.LookupSingleName(S.TUScope,
614                                &S.Context.Idents.get("object_getClass"),
615                                SourceLocation(), S.LookupOrdinaryName);
616           if (ObjectGetClass)
617             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
618             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
619             FixItHint::CreateReplacement(
620                                          SourceRange(OIRE->getOpLoc(),
621                                                      OIRE->getLocEnd()), ")");
622           else
623             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
624         }
625         S.Diag(IV->getLocation(), diag::note_ivar_decl);
626       }
627     }
628 }
629 
DefaultLvalueConversion(Expr * E)630 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
631   // Handle any placeholder expressions which made it here.
632   if (E->getType()->isPlaceholderType()) {
633     ExprResult result = CheckPlaceholderExpr(E);
634     if (result.isInvalid()) return ExprError();
635     E = result.get();
636   }
637 
638   // C++ [conv.lval]p1:
639   //   A glvalue of a non-function, non-array type T can be
640   //   converted to a prvalue.
641   if (!E->isGLValue()) return E;
642 
643   QualType T = E->getType();
644   assert(!T.isNull() && "r-value conversion on typeless expression?");
645 
646   // We don't want to throw lvalue-to-rvalue casts on top of
647   // expressions of certain types in C++.
648   if (getLangOpts().CPlusPlus &&
649       (E->getType() == Context.OverloadTy ||
650        T->isDependentType() ||
651        T->isRecordType()))
652     return E;
653 
654   // The C standard is actually really unclear on this point, and
655   // DR106 tells us what the result should be but not why.  It's
656   // generally best to say that void types just doesn't undergo
657   // lvalue-to-rvalue at all.  Note that expressions of unqualified
658   // 'void' type are never l-values, but qualified void can be.
659   if (T->isVoidType())
660     return E;
661 
662   // OpenCL usually rejects direct accesses to values of 'half' type.
663   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
664       T->isHalfType()) {
665     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
666       << 0 << T;
667     return ExprError();
668   }
669 
670   CheckForNullPointerDereference(*this, E);
671   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
672     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
673                                      &Context.Idents.get("object_getClass"),
674                                      SourceLocation(), LookupOrdinaryName);
675     if (ObjectGetClass)
676       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
677         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
678         FixItHint::CreateReplacement(
679                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
680     else
681       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
682   }
683   else if (const ObjCIvarRefExpr *OIRE =
684             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
685     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
686 
687   // C++ [conv.lval]p1:
688   //   [...] If T is a non-class type, the type of the prvalue is the
689   //   cv-unqualified version of T. Otherwise, the type of the
690   //   rvalue is T.
691   //
692   // C99 6.3.2.1p2:
693   //   If the lvalue has qualified type, the value has the unqualified
694   //   version of the type of the lvalue; otherwise, the value has the
695   //   type of the lvalue.
696   if (T.hasQualifiers())
697     T = T.getUnqualifiedType();
698 
699   // Under the MS ABI, lock down the inheritance model now.
700   if (T->isMemberPointerType() &&
701       Context.getTargetInfo().getCXXABI().isMicrosoft())
702     (void)isCompleteType(E->getExprLoc(), T);
703 
704   UpdateMarkingForLValueToRValue(E);
705 
706   // Loading a __weak object implicitly retains the value, so we need a cleanup to
707   // balance that.
708   if (getLangOpts().ObjCAutoRefCount &&
709       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
710     Cleanup.setExprNeedsCleanups(true);
711 
712   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
713                                             nullptr, VK_RValue);
714 
715   // C11 6.3.2.1p2:
716   //   ... if the lvalue has atomic type, the value has the non-atomic version
717   //   of the type of the lvalue ...
718   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
719     T = Atomic->getValueType().getUnqualifiedType();
720     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
721                                    nullptr, VK_RValue);
722   }
723 
724   return Res;
725 }
726 
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
728   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
729   if (Res.isInvalid())
730     return ExprError();
731   Res = DefaultLvalueConversion(Res.get());
732   if (Res.isInvalid())
733     return ExprError();
734   return Res;
735 }
736 
737 /// CallExprUnaryConversions - a special case of an unary conversion
738 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)739 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
740   QualType Ty = E->getType();
741   ExprResult Res = E;
742   // Only do implicit cast for a function type, but not for a pointer
743   // to function type.
744   if (Ty->isFunctionType()) {
745     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
746                             CK_FunctionToPointerDecay).get();
747     if (Res.isInvalid())
748       return ExprError();
749   }
750   Res = DefaultLvalueConversion(Res.get());
751   if (Res.isInvalid())
752     return ExprError();
753   return Res.get();
754 }
755 
756 /// UsualUnaryConversions - Performs various conversions that are common to most
757 /// operators (C99 6.3). The conversions of array and function types are
758 /// sometimes suppressed. For example, the array->pointer conversion doesn't
759 /// apply if the array is an argument to the sizeof or address (&) operators.
760 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)761 ExprResult Sema::UsualUnaryConversions(Expr *E) {
762   // First, convert to an r-value.
763   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
764   if (Res.isInvalid())
765     return ExprError();
766   E = Res.get();
767 
768   QualType Ty = E->getType();
769   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
770 
771   // Half FP have to be promoted to float unless it is natively supported
772   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
773     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
774 
775   // Try to perform integral promotions if the object has a theoretically
776   // promotable type.
777   if (Ty->isIntegralOrUnscopedEnumerationType()) {
778     // C99 6.3.1.1p2:
779     //
780     //   The following may be used in an expression wherever an int or
781     //   unsigned int may be used:
782     //     - an object or expression with an integer type whose integer
783     //       conversion rank is less than or equal to the rank of int
784     //       and unsigned int.
785     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
786     //
787     //   If an int can represent all values of the original type, the
788     //   value is converted to an int; otherwise, it is converted to an
789     //   unsigned int. These are called the integer promotions. All
790     //   other types are unchanged by the integer promotions.
791 
792     QualType PTy = Context.isPromotableBitField(E);
793     if (!PTy.isNull()) {
794       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
795       return E;
796     }
797     if (Ty->isPromotableIntegerType()) {
798       QualType PT = Context.getPromotedIntegerType(Ty);
799       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
800       return E;
801     }
802   }
803   return E;
804 }
805 
806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
807 /// do not have a prototype. Arguments that have type float or __fp16
808 /// are promoted to double. All other argument types are converted by
809 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
811   QualType Ty = E->getType();
812   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
813 
814   ExprResult Res = UsualUnaryConversions(E);
815   if (Res.isInvalid())
816     return ExprError();
817   E = Res.get();
818 
819   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
820   // double.
821   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
822   if (BTy && (BTy->getKind() == BuiltinType::Half ||
823               BTy->getKind() == BuiltinType::Float))
824     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
825 
826   // C++ performs lvalue-to-rvalue conversion as a default argument
827   // promotion, even on class types, but note:
828   //   C++11 [conv.lval]p2:
829   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
830   //     operand or a subexpression thereof the value contained in the
831   //     referenced object is not accessed. Otherwise, if the glvalue
832   //     has a class type, the conversion copy-initializes a temporary
833   //     of type T from the glvalue and the result of the conversion
834   //     is a prvalue for the temporary.
835   // FIXME: add some way to gate this entire thing for correctness in
836   // potentially potentially evaluated contexts.
837   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
838     ExprResult Temp = PerformCopyInitialization(
839                        InitializedEntity::InitializeTemporary(E->getType()),
840                                                 E->getExprLoc(), E);
841     if (Temp.isInvalid())
842       return ExprError();
843     E = Temp.get();
844   }
845 
846   return E;
847 }
848 
849 /// Determine the degree of POD-ness for an expression.
850 /// Incomplete types are considered POD, since this check can be performed
851 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)852 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
853   if (Ty->isIncompleteType()) {
854     // C++11 [expr.call]p7:
855     //   After these conversions, if the argument does not have arithmetic,
856     //   enumeration, pointer, pointer to member, or class type, the program
857     //   is ill-formed.
858     //
859     // Since we've already performed array-to-pointer and function-to-pointer
860     // decay, the only such type in C++ is cv void. This also handles
861     // initializer lists as variadic arguments.
862     if (Ty->isVoidType())
863       return VAK_Invalid;
864 
865     if (Ty->isObjCObjectType())
866       return VAK_Invalid;
867     return VAK_Valid;
868   }
869 
870   if (Ty.isCXX98PODType(Context))
871     return VAK_Valid;
872 
873   // C++11 [expr.call]p7:
874   //   Passing a potentially-evaluated argument of class type (Clause 9)
875   //   having a non-trivial copy constructor, a non-trivial move constructor,
876   //   or a non-trivial destructor, with no corresponding parameter,
877   //   is conditionally-supported with implementation-defined semantics.
878   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880       if (!Record->hasNonTrivialCopyConstructor() &&
881           !Record->hasNonTrivialMoveConstructor() &&
882           !Record->hasNonTrivialDestructor())
883         return VAK_ValidInCXX11;
884 
885   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
886     return VAK_Valid;
887 
888   if (Ty->isObjCObjectType())
889     return VAK_Invalid;
890 
891   if (getLangOpts().MSVCCompat)
892     return VAK_MSVCUndefined;
893 
894   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895   // permitted to reject them. We should consider doing so.
896   return VAK_Undefined;
897 }
898 
checkVariadicArgument(const Expr * E,VariadicCallType CT)899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900   // Don't allow one to pass an Objective-C interface to a vararg.
901   const QualType &Ty = E->getType();
902   VarArgKind VAK = isValidVarArgType(Ty);
903 
904   // Complain about passing non-POD types through varargs.
905   switch (VAK) {
906   case VAK_ValidInCXX11:
907     DiagRuntimeBehavior(
908         E->getLocStart(), nullptr,
909         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
910           << Ty << CT);
911     // Fall through.
912   case VAK_Valid:
913     if (Ty->isRecordType()) {
914       // This is unlikely to be what the user intended. If the class has a
915       // 'c_str' member function, the user probably meant to call that.
916       DiagRuntimeBehavior(E->getLocStart(), nullptr,
917                           PDiag(diag::warn_pass_class_arg_to_vararg)
918                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
919     }
920     break;
921 
922   case VAK_Undefined:
923   case VAK_MSVCUndefined:
924     DiagRuntimeBehavior(
925         E->getLocStart(), nullptr,
926         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
927           << getLangOpts().CPlusPlus11 << Ty << CT);
928     break;
929 
930   case VAK_Invalid:
931     if (Ty->isObjCObjectType())
932       DiagRuntimeBehavior(
933           E->getLocStart(), nullptr,
934           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
935             << Ty << CT);
936     else
937       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
938         << isa<InitListExpr>(E) << Ty << CT;
939     break;
940   }
941 }
942 
943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
944 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
946                                                   FunctionDecl *FDecl) {
947   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
948     // Strip the unbridged-cast placeholder expression off, if applicable.
949     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
950         (CT == VariadicMethod ||
951          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
952       E = stripARCUnbridgedCast(E);
953 
954     // Otherwise, do normal placeholder checking.
955     } else {
956       ExprResult ExprRes = CheckPlaceholderExpr(E);
957       if (ExprRes.isInvalid())
958         return ExprError();
959       E = ExprRes.get();
960     }
961   }
962 
963   ExprResult ExprRes = DefaultArgumentPromotion(E);
964   if (ExprRes.isInvalid())
965     return ExprError();
966   E = ExprRes.get();
967 
968   // Diagnostics regarding non-POD argument types are
969   // emitted along with format string checking in Sema::CheckFunctionCall().
970   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
971     // Turn this into a trap.
972     CXXScopeSpec SS;
973     SourceLocation TemplateKWLoc;
974     UnqualifiedId Name;
975     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
976                        E->getLocStart());
977     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
978                                           Name, true, false);
979     if (TrapFn.isInvalid())
980       return ExprError();
981 
982     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
983                                     E->getLocStart(), None,
984                                     E->getLocEnd());
985     if (Call.isInvalid())
986       return ExprError();
987 
988     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
989                                   Call.get(), E);
990     if (Comma.isInvalid())
991       return ExprError();
992     return Comma.get();
993   }
994 
995   if (!getLangOpts().CPlusPlus &&
996       RequireCompleteType(E->getExprLoc(), E->getType(),
997                           diag::err_call_incomplete_argument))
998     return ExprError();
999 
1000   return E;
1001 }
1002 
1003 /// \brief Converts an integer to complex float type.  Helper function of
1004 /// UsualArithmeticConversions()
1005 ///
1006 /// \return false if the integer expression is an integer type and is
1007 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1008 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1009                                                   ExprResult &ComplexExpr,
1010                                                   QualType IntTy,
1011                                                   QualType ComplexTy,
1012                                                   bool SkipCast) {
1013   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1014   if (SkipCast) return false;
1015   if (IntTy->isIntegerType()) {
1016     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1017     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1018     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1019                                   CK_FloatingRealToComplex);
1020   } else {
1021     assert(IntTy->isComplexIntegerType());
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1023                                   CK_IntegralComplexToFloatingComplex);
1024   }
1025   return false;
1026 }
1027 
1028 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1029 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1030 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1031                                              ExprResult &RHS, QualType LHSType,
1032                                              QualType RHSType,
1033                                              bool IsCompAssign) {
1034   // if we have an integer operand, the result is the complex type.
1035   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1036                                              /*skipCast*/false))
1037     return LHSType;
1038   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1039                                              /*skipCast*/IsCompAssign))
1040     return RHSType;
1041 
1042   // This handles complex/complex, complex/float, or float/complex.
1043   // When both operands are complex, the shorter operand is converted to the
1044   // type of the longer, and that is the type of the result. This corresponds
1045   // to what is done when combining two real floating-point operands.
1046   // The fun begins when size promotion occur across type domains.
1047   // From H&S 6.3.4: When one operand is complex and the other is a real
1048   // floating-point type, the less precise type is converted, within it's
1049   // real or complex domain, to the precision of the other type. For example,
1050   // when combining a "long double" with a "double _Complex", the
1051   // "double _Complex" is promoted to "long double _Complex".
1052 
1053   // Compute the rank of the two types, regardless of whether they are complex.
1054   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1055 
1056   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1057   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1058   QualType LHSElementType =
1059       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1060   QualType RHSElementType =
1061       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1062 
1063   QualType ResultType = S.Context.getComplexType(LHSElementType);
1064   if (Order < 0) {
1065     // Promote the precision of the LHS if not an assignment.
1066     ResultType = S.Context.getComplexType(RHSElementType);
1067     if (!IsCompAssign) {
1068       if (LHSComplexType)
1069         LHS =
1070             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1071       else
1072         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1073     }
1074   } else if (Order > 0) {
1075     // Promote the precision of the RHS.
1076     if (RHSComplexType)
1077       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1078     else
1079       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1080   }
1081   return ResultType;
1082 }
1083 
1084 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1085 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1086 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1087                                            ExprResult &IntExpr,
1088                                            QualType FloatTy, QualType IntTy,
1089                                            bool ConvertFloat, bool ConvertInt) {
1090   if (IntTy->isIntegerType()) {
1091     if (ConvertInt)
1092       // Convert intExpr to the lhs floating point type.
1093       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1094                                     CK_IntegralToFloating);
1095     return FloatTy;
1096   }
1097 
1098   // Convert both sides to the appropriate complex float.
1099   assert(IntTy->isComplexIntegerType());
1100   QualType result = S.Context.getComplexType(FloatTy);
1101 
1102   // _Complex int -> _Complex float
1103   if (ConvertInt)
1104     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1105                                   CK_IntegralComplexToFloatingComplex);
1106 
1107   // float -> _Complex float
1108   if (ConvertFloat)
1109     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1110                                     CK_FloatingRealToComplex);
1111 
1112   return result;
1113 }
1114 
1115 /// \brief Handle arithmethic conversion with floating point types.  Helper
1116 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1117 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1118                                       ExprResult &RHS, QualType LHSType,
1119                                       QualType RHSType, bool IsCompAssign) {
1120   bool LHSFloat = LHSType->isRealFloatingType();
1121   bool RHSFloat = RHSType->isRealFloatingType();
1122 
1123   // If we have two real floating types, convert the smaller operand
1124   // to the bigger result.
1125   if (LHSFloat && RHSFloat) {
1126     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1127     if (order > 0) {
1128       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1129       return LHSType;
1130     }
1131 
1132     assert(order < 0 && "illegal float comparison");
1133     if (!IsCompAssign)
1134       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1135     return RHSType;
1136   }
1137 
1138   if (LHSFloat) {
1139     // Half FP has to be promoted to float unless it is natively supported
1140     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1141       LHSType = S.Context.FloatTy;
1142 
1143     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1144                                       /*convertFloat=*/!IsCompAssign,
1145                                       /*convertInt=*/ true);
1146   }
1147   assert(RHSFloat);
1148   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149                                     /*convertInt=*/ true,
1150                                     /*convertFloat=*/!IsCompAssign);
1151 }
1152 
1153 /// \brief Diagnose attempts to convert between __float128 and long double if
1154 /// there is no support for such conversion. Helper function of
1155 /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1156 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1157                                       QualType RHSType) {
1158   /*  No issue converting if at least one of the types is not a floating point
1159       type or the two types have the same rank.
1160   */
1161   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1162       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1163     return false;
1164 
1165   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1166          "The remaining types must be floating point types.");
1167 
1168   auto *LHSComplex = LHSType->getAs<ComplexType>();
1169   auto *RHSComplex = RHSType->getAs<ComplexType>();
1170 
1171   QualType LHSElemType = LHSComplex ?
1172     LHSComplex->getElementType() : LHSType;
1173   QualType RHSElemType = RHSComplex ?
1174     RHSComplex->getElementType() : RHSType;
1175 
1176   // No issue if the two types have the same representation
1177   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1178       &S.Context.getFloatTypeSemantics(RHSElemType))
1179     return false;
1180 
1181   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1182                                 RHSElemType == S.Context.LongDoubleTy);
1183   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1184                             RHSElemType == S.Context.Float128Ty);
1185 
1186   /* We've handled the situation where __float128 and long double have the same
1187      representation. The only other allowable conversion is if long double is
1188      really just double.
1189   */
1190   return Float128AndLongDouble &&
1191     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1192      &llvm::APFloat::IEEEdouble);
1193 }
1194 
1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1196 
1197 namespace {
1198 /// These helper callbacks are placed in an anonymous namespace to
1199 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1201   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1202 }
1203 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1205   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1206                              CK_IntegralComplexCast);
1207 }
1208 }
1209 
1210 /// \brief Handle integer arithmetic conversions.  Helper function of
1211 /// UsualArithmeticConversions()
1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1214                                         ExprResult &RHS, QualType LHSType,
1215                                         QualType RHSType, bool IsCompAssign) {
1216   // The rules for this case are in C99 6.3.1.8
1217   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1218   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1219   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1220   if (LHSSigned == RHSSigned) {
1221     // Same signedness; use the higher-ranked type
1222     if (order >= 0) {
1223       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1224       return LHSType;
1225     } else if (!IsCompAssign)
1226       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1227     return RHSType;
1228   } else if (order != (LHSSigned ? 1 : -1)) {
1229     // The unsigned type has greater than or equal rank to the
1230     // signed type, so use the unsigned type
1231     if (RHSSigned) {
1232       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233       return LHSType;
1234     } else if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236     return RHSType;
1237   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1238     // The two types are different widths; if we are here, that
1239     // means the signed type is larger than the unsigned type, so
1240     // use the signed type.
1241     if (LHSSigned) {
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 {
1248     // The signed type is higher-ranked than the unsigned type,
1249     // but isn't actually any bigger (like unsigned int and long
1250     // on most 32-bit systems).  Use the unsigned type corresponding
1251     // to the signed type.
1252     QualType result =
1253       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1254     RHS = (*doRHSCast)(S, RHS.get(), result);
1255     if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), result);
1257     return result;
1258   }
1259 }
1260 
1261 /// \brief Handle conversions with GCC complex int extension.  Helper function
1262 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1264                                            ExprResult &RHS, QualType LHSType,
1265                                            QualType RHSType,
1266                                            bool IsCompAssign) {
1267   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1268   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1269 
1270   if (LHSComplexInt && RHSComplexInt) {
1271     QualType LHSEltType = LHSComplexInt->getElementType();
1272     QualType RHSEltType = RHSComplexInt->getElementType();
1273     QualType ScalarType =
1274       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1275         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1276 
1277     return S.Context.getComplexType(ScalarType);
1278   }
1279 
1280   if (LHSComplexInt) {
1281     QualType LHSEltType = LHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1285     QualType ComplexType = S.Context.getComplexType(ScalarType);
1286     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1287                               CK_IntegralRealToComplex);
1288 
1289     return ComplexType;
1290   }
1291 
1292   assert(RHSComplexInt);
1293 
1294   QualType RHSEltType = RHSComplexInt->getElementType();
1295   QualType ScalarType =
1296     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1297       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1298   QualType ComplexType = S.Context.getComplexType(ScalarType);
1299 
1300   if (!IsCompAssign)
1301     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1302                               CK_IntegralRealToComplex);
1303   return ComplexType;
1304 }
1305 
1306 /// UsualArithmeticConversions - Performs various conversions that are common to
1307 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1308 /// routine returns the first non-arithmetic type found. The client is
1309 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,bool IsCompAssign)1310 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1311                                           bool IsCompAssign) {
1312   if (!IsCompAssign) {
1313     LHS = UsualUnaryConversions(LHS.get());
1314     if (LHS.isInvalid())
1315       return QualType();
1316   }
1317 
1318   RHS = UsualUnaryConversions(RHS.get());
1319   if (RHS.isInvalid())
1320     return QualType();
1321 
1322   // For conversion purposes, we ignore any qualifiers.
1323   // For example, "const float" and "float" are equivalent.
1324   QualType LHSType =
1325     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1326   QualType RHSType =
1327     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1328 
1329   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1330   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1331     LHSType = AtomicLHS->getValueType();
1332 
1333   // If both types are identical, no conversion is needed.
1334   if (LHSType == RHSType)
1335     return LHSType;
1336 
1337   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1338   // The caller can deal with this (e.g. pointer + int).
1339   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1340     return QualType();
1341 
1342   // Apply unary and bitfield promotions to the LHS's type.
1343   QualType LHSUnpromotedType = LHSType;
1344   if (LHSType->isPromotableIntegerType())
1345     LHSType = Context.getPromotedIntegerType(LHSType);
1346   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1347   if (!LHSBitfieldPromoteTy.isNull())
1348     LHSType = LHSBitfieldPromoteTy;
1349   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1350     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1351 
1352   // If both types are identical, no conversion is needed.
1353   if (LHSType == RHSType)
1354     return LHSType;
1355 
1356   // At this point, we have two different arithmetic types.
1357 
1358   // Diagnose attempts to convert between __float128 and long double where
1359   // such conversions currently can't be handled.
1360   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1361     return QualType();
1362 
1363   // Handle complex types first (C99 6.3.1.8p1).
1364   if (LHSType->isComplexType() || RHSType->isComplexType())
1365     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1366                                         IsCompAssign);
1367 
1368   // Now handle "real" floating types (i.e. float, double, long double).
1369   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1370     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1371                                  IsCompAssign);
1372 
1373   // Handle GCC complex int extension.
1374   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1375     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1376                                       IsCompAssign);
1377 
1378   // Finally, we have two differing integer types.
1379   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1380            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1381 }
1382 
1383 
1384 //===----------------------------------------------------------------------===//
1385 //  Semantic Analysis for various Expression Types
1386 //===----------------------------------------------------------------------===//
1387 
1388 
1389 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1390 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1391                                 SourceLocation DefaultLoc,
1392                                 SourceLocation RParenLoc,
1393                                 Expr *ControllingExpr,
1394                                 ArrayRef<ParsedType> ArgTypes,
1395                                 ArrayRef<Expr *> ArgExprs) {
1396   unsigned NumAssocs = ArgTypes.size();
1397   assert(NumAssocs == ArgExprs.size());
1398 
1399   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1400   for (unsigned i = 0; i < NumAssocs; ++i) {
1401     if (ArgTypes[i])
1402       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1403     else
1404       Types[i] = nullptr;
1405   }
1406 
1407   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1408                                              ControllingExpr,
1409                                              llvm::makeArrayRef(Types, NumAssocs),
1410                                              ArgExprs);
1411   delete [] Types;
1412   return ER;
1413 }
1414 
1415 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1416 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1417                                  SourceLocation DefaultLoc,
1418                                  SourceLocation RParenLoc,
1419                                  Expr *ControllingExpr,
1420                                  ArrayRef<TypeSourceInfo *> Types,
1421                                  ArrayRef<Expr *> Exprs) {
1422   unsigned NumAssocs = Types.size();
1423   assert(NumAssocs == Exprs.size());
1424 
1425   // Decay and strip qualifiers for the controlling expression type, and handle
1426   // placeholder type replacement. See committee discussion from WG14 DR423.
1427   {
1428     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1429     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1430     if (R.isInvalid())
1431       return ExprError();
1432     ControllingExpr = R.get();
1433   }
1434 
1435   // The controlling expression is an unevaluated operand, so side effects are
1436   // likely unintended.
1437   if (ActiveTemplateInstantiations.empty() &&
1438       ControllingExpr->HasSideEffects(Context, false))
1439     Diag(ControllingExpr->getExprLoc(),
1440          diag::warn_side_effects_unevaluated_context);
1441 
1442   bool TypeErrorFound = false,
1443        IsResultDependent = ControllingExpr->isTypeDependent(),
1444        ContainsUnexpandedParameterPack
1445          = ControllingExpr->containsUnexpandedParameterPack();
1446 
1447   for (unsigned i = 0; i < NumAssocs; ++i) {
1448     if (Exprs[i]->containsUnexpandedParameterPack())
1449       ContainsUnexpandedParameterPack = true;
1450 
1451     if (Types[i]) {
1452       if (Types[i]->getType()->containsUnexpandedParameterPack())
1453         ContainsUnexpandedParameterPack = true;
1454 
1455       if (Types[i]->getType()->isDependentType()) {
1456         IsResultDependent = true;
1457       } else {
1458         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1459         // complete object type other than a variably modified type."
1460         unsigned D = 0;
1461         if (Types[i]->getType()->isIncompleteType())
1462           D = diag::err_assoc_type_incomplete;
1463         else if (!Types[i]->getType()->isObjectType())
1464           D = diag::err_assoc_type_nonobject;
1465         else if (Types[i]->getType()->isVariablyModifiedType())
1466           D = diag::err_assoc_type_variably_modified;
1467 
1468         if (D != 0) {
1469           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1470             << Types[i]->getTypeLoc().getSourceRange()
1471             << Types[i]->getType();
1472           TypeErrorFound = true;
1473         }
1474 
1475         // C11 6.5.1.1p2 "No two generic associations in the same generic
1476         // selection shall specify compatible types."
1477         for (unsigned j = i+1; j < NumAssocs; ++j)
1478           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1479               Context.typesAreCompatible(Types[i]->getType(),
1480                                          Types[j]->getType())) {
1481             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1482                  diag::err_assoc_compatible_types)
1483               << Types[j]->getTypeLoc().getSourceRange()
1484               << Types[j]->getType()
1485               << Types[i]->getType();
1486             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1487                  diag::note_compat_assoc)
1488               << Types[i]->getTypeLoc().getSourceRange()
1489               << Types[i]->getType();
1490             TypeErrorFound = true;
1491           }
1492       }
1493     }
1494   }
1495   if (TypeErrorFound)
1496     return ExprError();
1497 
1498   // If we determined that the generic selection is result-dependent, don't
1499   // try to compute the result expression.
1500   if (IsResultDependent)
1501     return new (Context) GenericSelectionExpr(
1502         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1503         ContainsUnexpandedParameterPack);
1504 
1505   SmallVector<unsigned, 1> CompatIndices;
1506   unsigned DefaultIndex = -1U;
1507   for (unsigned i = 0; i < NumAssocs; ++i) {
1508     if (!Types[i])
1509       DefaultIndex = i;
1510     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1511                                         Types[i]->getType()))
1512       CompatIndices.push_back(i);
1513   }
1514 
1515   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1516   // type compatible with at most one of the types named in its generic
1517   // association list."
1518   if (CompatIndices.size() > 1) {
1519     // We strip parens here because the controlling expression is typically
1520     // parenthesized in macro definitions.
1521     ControllingExpr = ControllingExpr->IgnoreParens();
1522     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1523       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1524       << (unsigned) CompatIndices.size();
1525     for (unsigned I : CompatIndices) {
1526       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1527            diag::note_compat_assoc)
1528         << Types[I]->getTypeLoc().getSourceRange()
1529         << Types[I]->getType();
1530     }
1531     return ExprError();
1532   }
1533 
1534   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1535   // its controlling expression shall have type compatible with exactly one of
1536   // the types named in its generic association list."
1537   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1538     // We strip parens here because the controlling expression is typically
1539     // parenthesized in macro definitions.
1540     ControllingExpr = ControllingExpr->IgnoreParens();
1541     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1542       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1543     return ExprError();
1544   }
1545 
1546   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1547   // type name that is compatible with the type of the controlling expression,
1548   // then the result expression of the generic selection is the expression
1549   // in that generic association. Otherwise, the result expression of the
1550   // generic selection is the expression in the default generic association."
1551   unsigned ResultIndex =
1552     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1553 
1554   return new (Context) GenericSelectionExpr(
1555       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1556       ContainsUnexpandedParameterPack, ResultIndex);
1557 }
1558 
1559 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1560 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1561 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1562                                      unsigned Offset) {
1563   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1564                                         S.getLangOpts());
1565 }
1566 
1567 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1568 /// 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)1569 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1570                                                  IdentifierInfo *UDSuffix,
1571                                                  SourceLocation UDSuffixLoc,
1572                                                  ArrayRef<Expr*> Args,
1573                                                  SourceLocation LitEndLoc) {
1574   assert(Args.size() <= 2 && "too many arguments for literal operator");
1575 
1576   QualType ArgTy[2];
1577   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1578     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1579     if (ArgTy[ArgIdx]->isArrayType())
1580       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1581   }
1582 
1583   DeclarationName OpName =
1584     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1585   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1586   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1587 
1588   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1589   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1590                               /*AllowRaw*/false, /*AllowTemplate*/false,
1591                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1592     return ExprError();
1593 
1594   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1595 }
1596 
1597 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1598 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1599 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1600 /// multiple tokens.  However, the common case is that StringToks points to one
1601 /// string.
1602 ///
1603 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1604 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1605   assert(!StringToks.empty() && "Must have at least one string!");
1606 
1607   StringLiteralParser Literal(StringToks, PP);
1608   if (Literal.hadError)
1609     return ExprError();
1610 
1611   SmallVector<SourceLocation, 4> StringTokLocs;
1612   for (const Token &Tok : StringToks)
1613     StringTokLocs.push_back(Tok.getLocation());
1614 
1615   QualType CharTy = Context.CharTy;
1616   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1617   if (Literal.isWide()) {
1618     CharTy = Context.getWideCharType();
1619     Kind = StringLiteral::Wide;
1620   } else if (Literal.isUTF8()) {
1621     Kind = StringLiteral::UTF8;
1622   } else if (Literal.isUTF16()) {
1623     CharTy = Context.Char16Ty;
1624     Kind = StringLiteral::UTF16;
1625   } else if (Literal.isUTF32()) {
1626     CharTy = Context.Char32Ty;
1627     Kind = StringLiteral::UTF32;
1628   } else if (Literal.isPascal()) {
1629     CharTy = Context.UnsignedCharTy;
1630   }
1631 
1632   QualType CharTyConst = CharTy;
1633   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1634   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1635     CharTyConst.addConst();
1636 
1637   // Get an array type for the string, according to C99 6.4.5.  This includes
1638   // the nul terminator character as well as the string length for pascal
1639   // strings.
1640   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1641                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1642                                  ArrayType::Normal, 0);
1643 
1644   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1645   if (getLangOpts().OpenCL) {
1646     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1647   }
1648 
1649   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1650   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1651                                              Kind, Literal.Pascal, StrTy,
1652                                              &StringTokLocs[0],
1653                                              StringTokLocs.size());
1654   if (Literal.getUDSuffix().empty())
1655     return Lit;
1656 
1657   // We're building a user-defined literal.
1658   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1659   SourceLocation UDSuffixLoc =
1660     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1661                    Literal.getUDSuffixOffset());
1662 
1663   // Make sure we're allowed user-defined literals here.
1664   if (!UDLScope)
1665     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1666 
1667   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1668   //   operator "" X (str, len)
1669   QualType SizeType = Context.getSizeType();
1670 
1671   DeclarationName OpName =
1672     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1673   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1674   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1675 
1676   QualType ArgTy[] = {
1677     Context.getArrayDecayedType(StrTy), SizeType
1678   };
1679 
1680   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1681   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1682                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1683                                 /*AllowStringTemplate*/true)) {
1684 
1685   case LOLR_Cooked: {
1686     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1687     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1688                                                     StringTokLocs[0]);
1689     Expr *Args[] = { Lit, LenArg };
1690 
1691     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1692   }
1693 
1694   case LOLR_StringTemplate: {
1695     TemplateArgumentListInfo ExplicitArgs;
1696 
1697     unsigned CharBits = Context.getIntWidth(CharTy);
1698     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1699     llvm::APSInt Value(CharBits, CharIsUnsigned);
1700 
1701     TemplateArgument TypeArg(CharTy);
1702     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1703     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1704 
1705     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1706       Value = Lit->getCodeUnit(I);
1707       TemplateArgument Arg(Context, Value, CharTy);
1708       TemplateArgumentLocInfo ArgInfo;
1709       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1710     }
1711     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1712                                     &ExplicitArgs);
1713   }
1714   case LOLR_Raw:
1715   case LOLR_Template:
1716     llvm_unreachable("unexpected literal operator lookup result");
1717   case LOLR_Error:
1718     return ExprError();
1719   }
1720   llvm_unreachable("unexpected literal operator lookup result");
1721 }
1722 
1723 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1724 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1725                        SourceLocation Loc,
1726                        const CXXScopeSpec *SS) {
1727   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1728   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1729 }
1730 
1731 /// BuildDeclRefExpr - Build an expression that references a
1732 /// declaration that does not require a closure capture.
1733 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)1734 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1735                        const DeclarationNameInfo &NameInfo,
1736                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1737                        const TemplateArgumentListInfo *TemplateArgs) {
1738   if (getLangOpts().CUDA)
1739     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1740       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1741         if (CheckCUDATarget(Caller, Callee)) {
1742           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1743             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1744             << IdentifyCUDATarget(Caller);
1745           Diag(D->getLocation(), diag::note_previous_decl)
1746             << D->getIdentifier();
1747           return ExprError();
1748         }
1749       }
1750 
1751   bool RefersToCapturedVariable =
1752       isa<VarDecl>(D) &&
1753       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1754 
1755   DeclRefExpr *E;
1756   if (isa<VarTemplateSpecializationDecl>(D)) {
1757     VarTemplateSpecializationDecl *VarSpec =
1758         cast<VarTemplateSpecializationDecl>(D);
1759 
1760     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761                                         : NestedNameSpecifierLoc(),
1762                             VarSpec->getTemplateKeywordLoc(), D,
1763                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1764                             FoundD, TemplateArgs);
1765   } else {
1766     assert(!TemplateArgs && "No template arguments for non-variable"
1767                             " template specialization references");
1768     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1769                                         : NestedNameSpecifierLoc(),
1770                             SourceLocation(), D, RefersToCapturedVariable,
1771                             NameInfo, Ty, VK, FoundD);
1772   }
1773 
1774   MarkDeclRefReferenced(E);
1775 
1776   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1777       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1778       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1779       recordUseOfEvaluatedWeak(E);
1780 
1781   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1782     UnusedPrivateFields.remove(FD);
1783     // Just in case we're building an illegal pointer-to-member.
1784     if (FD->isBitField())
1785       E->setObjectKind(OK_BitField);
1786   }
1787 
1788   return E;
1789 }
1790 
1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1792 /// possibly a list of template arguments.
1793 ///
1794 /// If this produces template arguments, it is permitted to call
1795 /// DecomposeTemplateName.
1796 ///
1797 /// This actually loses a lot of source location information for
1798 /// non-standard name kinds; we should consider preserving that in
1799 /// some way.
1800 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1802                              TemplateArgumentListInfo &Buffer,
1803                              DeclarationNameInfo &NameInfo,
1804                              const TemplateArgumentListInfo *&TemplateArgs) {
1805   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1806     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1807     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1808 
1809     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1810                                        Id.TemplateId->NumArgs);
1811     translateTemplateArguments(TemplateArgsPtr, Buffer);
1812 
1813     TemplateName TName = Id.TemplateId->Template.get();
1814     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1815     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1816     TemplateArgs = &Buffer;
1817   } else {
1818     NameInfo = GetNameFromUnqualifiedId(Id);
1819     TemplateArgs = nullptr;
1820   }
1821 }
1822 
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)1823 static void emitEmptyLookupTypoDiagnostic(
1824     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1825     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1826     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1827   DeclContext *Ctx =
1828       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1829   if (!TC) {
1830     // Emit a special diagnostic for failed member lookups.
1831     // FIXME: computing the declaration context might fail here (?)
1832     if (Ctx)
1833       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1834                                                  << SS.getRange();
1835     else
1836       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1837     return;
1838   }
1839 
1840   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1841   bool DroppedSpecifier =
1842       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1843   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1844                         ? diag::note_implicit_param_decl
1845                         : diag::note_previous_decl;
1846   if (!Ctx)
1847     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1848                          SemaRef.PDiag(NoteID));
1849   else
1850     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1851                                  << Typo << Ctx << DroppedSpecifier
1852                                  << SS.getRange(),
1853                          SemaRef.PDiag(NoteID));
1854 }
1855 
1856 /// Diagnose an empty lookup.
1857 ///
1858 /// \return false if new lookup candidates were found
1859 bool
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,std::unique_ptr<CorrectionCandidateCallback> CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1861                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1862                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1863                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1864   DeclarationName Name = R.getLookupName();
1865 
1866   unsigned diagnostic = diag::err_undeclared_var_use;
1867   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1868   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1869       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1870       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1871     diagnostic = diag::err_undeclared_use;
1872     diagnostic_suggest = diag::err_undeclared_use_suggest;
1873   }
1874 
1875   // If the original lookup was an unqualified lookup, fake an
1876   // unqualified lookup.  This is useful when (for example) the
1877   // original lookup would not have found something because it was a
1878   // dependent name.
1879   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1880   while (DC) {
1881     if (isa<CXXRecordDecl>(DC)) {
1882       LookupQualifiedName(R, DC);
1883 
1884       if (!R.empty()) {
1885         // Don't give errors about ambiguities in this lookup.
1886         R.suppressDiagnostics();
1887 
1888         // During a default argument instantiation the CurContext points
1889         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1890         // function parameter list, hence add an explicit check.
1891         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1892                               ActiveTemplateInstantiations.back().Kind ==
1893             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1894         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1895         bool isInstance = CurMethod &&
1896                           CurMethod->isInstance() &&
1897                           DC == CurMethod->getParent() && !isDefaultArgument;
1898 
1899         // Give a code modification hint to insert 'this->'.
1900         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1901         // Actually quite difficult!
1902         if (getLangOpts().MSVCCompat)
1903           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1904         if (isInstance) {
1905           Diag(R.getNameLoc(), diagnostic) << Name
1906             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1907           CheckCXXThisCapture(R.getNameLoc());
1908         } else {
1909           Diag(R.getNameLoc(), diagnostic) << Name;
1910         }
1911 
1912         // Do we really want to note all of these?
1913         for (NamedDecl *D : R)
1914           Diag(D->getLocation(), diag::note_dependent_var_use);
1915 
1916         // Return true if we are inside a default argument instantiation
1917         // and the found name refers to an instance member function, otherwise
1918         // the function calling DiagnoseEmptyLookup will try to create an
1919         // implicit member call and this is wrong for default argument.
1920         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1921           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1922           return true;
1923         }
1924 
1925         // Tell the callee to try to recover.
1926         return false;
1927       }
1928 
1929       R.clear();
1930     }
1931 
1932     // In Microsoft mode, if we are performing lookup from within a friend
1933     // function definition declared at class scope then we must set
1934     // DC to the lexical parent to be able to search into the parent
1935     // class.
1936     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1937         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1938         DC->getLexicalParent()->isRecord())
1939       DC = DC->getLexicalParent();
1940     else
1941       DC = DC->getParent();
1942   }
1943 
1944   // We didn't find anything, so try to correct for a typo.
1945   TypoCorrection Corrected;
1946   if (S && Out) {
1947     SourceLocation TypoLoc = R.getNameLoc();
1948     assert(!ExplicitTemplateArgs &&
1949            "Diagnosing an empty lookup with explicit template args!");
1950     *Out = CorrectTypoDelayed(
1951         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1952         [=](const TypoCorrection &TC) {
1953           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1954                                         diagnostic, diagnostic_suggest);
1955         },
1956         nullptr, CTK_ErrorRecovery);
1957     if (*Out)
1958       return true;
1959   } else if (S && (Corrected =
1960                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1961                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1962     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1963     bool DroppedSpecifier =
1964         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1965     R.setLookupName(Corrected.getCorrection());
1966 
1967     bool AcceptableWithRecovery = false;
1968     bool AcceptableWithoutRecovery = false;
1969     NamedDecl *ND = Corrected.getFoundDecl();
1970     if (ND) {
1971       if (Corrected.isOverloaded()) {
1972         OverloadCandidateSet OCS(R.getNameLoc(),
1973                                  OverloadCandidateSet::CSK_Normal);
1974         OverloadCandidateSet::iterator Best;
1975         for (NamedDecl *CD : Corrected) {
1976           if (FunctionTemplateDecl *FTD =
1977                    dyn_cast<FunctionTemplateDecl>(CD))
1978             AddTemplateOverloadCandidate(
1979                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1980                 Args, OCS);
1981           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1982             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1983               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1984                                    Args, OCS);
1985         }
1986         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1987         case OR_Success:
1988           ND = Best->FoundDecl;
1989           Corrected.setCorrectionDecl(ND);
1990           break;
1991         default:
1992           // FIXME: Arbitrarily pick the first declaration for the note.
1993           Corrected.setCorrectionDecl(ND);
1994           break;
1995         }
1996       }
1997       R.addDecl(ND);
1998       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1999         CXXRecordDecl *Record = nullptr;
2000         if (Corrected.getCorrectionSpecifier()) {
2001           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2002           Record = Ty->getAsCXXRecordDecl();
2003         }
2004         if (!Record)
2005           Record = cast<CXXRecordDecl>(
2006               ND->getDeclContext()->getRedeclContext());
2007         R.setNamingClass(Record);
2008       }
2009 
2010       auto *UnderlyingND = ND->getUnderlyingDecl();
2011       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2012                                isa<FunctionTemplateDecl>(UnderlyingND);
2013       // FIXME: If we ended up with a typo for a type name or
2014       // Objective-C class name, we're in trouble because the parser
2015       // is in the wrong place to recover. Suggest the typo
2016       // correction, but don't make it a fix-it since we're not going
2017       // to recover well anyway.
2018       AcceptableWithoutRecovery =
2019           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2020     } else {
2021       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2022       // because we aren't able to recover.
2023       AcceptableWithoutRecovery = true;
2024     }
2025 
2026     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2027       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2028                             ? diag::note_implicit_param_decl
2029                             : diag::note_previous_decl;
2030       if (SS.isEmpty())
2031         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2032                      PDiag(NoteID), AcceptableWithRecovery);
2033       else
2034         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2035                                   << Name << computeDeclContext(SS, false)
2036                                   << DroppedSpecifier << SS.getRange(),
2037                      PDiag(NoteID), AcceptableWithRecovery);
2038 
2039       // Tell the callee whether to try to recover.
2040       return !AcceptableWithRecovery;
2041     }
2042   }
2043   R.clear();
2044 
2045   // Emit a special diagnostic for failed member lookups.
2046   // FIXME: computing the declaration context might fail here (?)
2047   if (!SS.isEmpty()) {
2048     Diag(R.getNameLoc(), diag::err_no_member)
2049       << Name << computeDeclContext(SS, false)
2050       << SS.getRange();
2051     return true;
2052   }
2053 
2054   // Give up, we can't recover.
2055   Diag(R.getNameLoc(), diagnostic) << Name;
2056   return true;
2057 }
2058 
2059 /// In Microsoft mode, if we are inside a template class whose parent class has
2060 /// dependent base classes, and we can't resolve an unqualified identifier, then
2061 /// assume the identifier is a member of a dependent base class.  We can only
2062 /// recover successfully in static methods, instance methods, and other contexts
2063 /// where 'this' is available.  This doesn't precisely match MSVC's
2064 /// instantiation model, but it's close enough.
2065 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2066 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2067                                DeclarationNameInfo &NameInfo,
2068                                SourceLocation TemplateKWLoc,
2069                                const TemplateArgumentListInfo *TemplateArgs) {
2070   // Only try to recover from lookup into dependent bases in static methods or
2071   // contexts where 'this' is available.
2072   QualType ThisType = S.getCurrentThisType();
2073   const CXXRecordDecl *RD = nullptr;
2074   if (!ThisType.isNull())
2075     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2076   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2077     RD = MD->getParent();
2078   if (!RD || !RD->hasAnyDependentBases())
2079     return nullptr;
2080 
2081   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2082   // is available, suggest inserting 'this->' as a fixit.
2083   SourceLocation Loc = NameInfo.getLoc();
2084   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2085   DB << NameInfo.getName() << RD;
2086 
2087   if (!ThisType.isNull()) {
2088     DB << FixItHint::CreateInsertion(Loc, "this->");
2089     return CXXDependentScopeMemberExpr::Create(
2090         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2091         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2092         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2093   }
2094 
2095   // Synthesize a fake NNS that points to the derived class.  This will
2096   // perform name lookup during template instantiation.
2097   CXXScopeSpec SS;
2098   auto *NNS =
2099       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2100   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2101   return DependentScopeDeclRefExpr::Create(
2102       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2103       TemplateArgs);
2104 }
2105 
2106 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2107 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2108                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2109                         bool HasTrailingLParen, bool IsAddressOfOperand,
2110                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2111                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2112   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2113          "cannot be direct & operand and have a trailing lparen");
2114   if (SS.isInvalid())
2115     return ExprError();
2116 
2117   TemplateArgumentListInfo TemplateArgsBuffer;
2118 
2119   // Decompose the UnqualifiedId into the following data.
2120   DeclarationNameInfo NameInfo;
2121   const TemplateArgumentListInfo *TemplateArgs;
2122   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2123 
2124   DeclarationName Name = NameInfo.getName();
2125   IdentifierInfo *II = Name.getAsIdentifierInfo();
2126   SourceLocation NameLoc = NameInfo.getLoc();
2127 
2128   // C++ [temp.dep.expr]p3:
2129   //   An id-expression is type-dependent if it contains:
2130   //     -- an identifier that was declared with a dependent type,
2131   //        (note: handled after lookup)
2132   //     -- a template-id that is dependent,
2133   //        (note: handled in BuildTemplateIdExpr)
2134   //     -- a conversion-function-id that specifies a dependent type,
2135   //     -- a nested-name-specifier that contains a class-name that
2136   //        names a dependent type.
2137   // Determine whether this is a member of an unknown specialization;
2138   // we need to handle these differently.
2139   bool DependentID = false;
2140   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2141       Name.getCXXNameType()->isDependentType()) {
2142     DependentID = true;
2143   } else if (SS.isSet()) {
2144     if (DeclContext *DC = computeDeclContext(SS, false)) {
2145       if (RequireCompleteDeclContext(SS, DC))
2146         return ExprError();
2147     } else {
2148       DependentID = true;
2149     }
2150   }
2151 
2152   if (DependentID)
2153     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2154                                       IsAddressOfOperand, TemplateArgs);
2155 
2156   // Perform the required lookup.
2157   LookupResult R(*this, NameInfo,
2158                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2159                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2160   if (TemplateArgs) {
2161     // Lookup the template name again to correctly establish the context in
2162     // which it was found. This is really unfortunate as we already did the
2163     // lookup to determine that it was a template name in the first place. If
2164     // this becomes a performance hit, we can work harder to preserve those
2165     // results until we get here but it's likely not worth it.
2166     bool MemberOfUnknownSpecialization;
2167     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2168                        MemberOfUnknownSpecialization);
2169 
2170     if (MemberOfUnknownSpecialization ||
2171         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2172       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2173                                         IsAddressOfOperand, TemplateArgs);
2174   } else {
2175     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2176     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2177 
2178     // If the result might be in a dependent base class, this is a dependent
2179     // id-expression.
2180     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2181       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2182                                         IsAddressOfOperand, TemplateArgs);
2183 
2184     // If this reference is in an Objective-C method, then we need to do
2185     // some special Objective-C lookup, too.
2186     if (IvarLookupFollowUp) {
2187       ExprResult E(LookupInObjCMethod(R, S, II, true));
2188       if (E.isInvalid())
2189         return ExprError();
2190 
2191       if (Expr *Ex = E.getAs<Expr>())
2192         return Ex;
2193     }
2194   }
2195 
2196   if (R.isAmbiguous())
2197     return ExprError();
2198 
2199   // This could be an implicitly declared function reference (legal in C90,
2200   // extension in C99, forbidden in C++).
2201   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2202     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2203     if (D) R.addDecl(D);
2204   }
2205 
2206   // Determine whether this name might be a candidate for
2207   // argument-dependent lookup.
2208   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2209 
2210   if (R.empty() && !ADL) {
2211     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2212       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2213                                                    TemplateKWLoc, TemplateArgs))
2214         return E;
2215     }
2216 
2217     // Don't diagnose an empty lookup for inline assembly.
2218     if (IsInlineAsmIdentifier)
2219       return ExprError();
2220 
2221     // If this name wasn't predeclared and if this is not a function
2222     // call, diagnose the problem.
2223     TypoExpr *TE = nullptr;
2224     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2225         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2226     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2227     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2228            "Typo correction callback misconfigured");
2229     if (CCC) {
2230       // Make sure the callback knows what the typo being diagnosed is.
2231       CCC->setTypoName(II);
2232       if (SS.isValid())
2233         CCC->setTypoNNS(SS.getScopeRep());
2234     }
2235     if (DiagnoseEmptyLookup(S, SS, R,
2236                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2237                             nullptr, None, &TE)) {
2238       if (TE && KeywordReplacement) {
2239         auto &State = getTypoExprState(TE);
2240         auto BestTC = State.Consumer->getNextCorrection();
2241         if (BestTC.isKeyword()) {
2242           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2243           if (State.DiagHandler)
2244             State.DiagHandler(BestTC);
2245           KeywordReplacement->startToken();
2246           KeywordReplacement->setKind(II->getTokenID());
2247           KeywordReplacement->setIdentifierInfo(II);
2248           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2249           // Clean up the state associated with the TypoExpr, since it has
2250           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2251           clearDelayedTypo(TE);
2252           // Signal that a correction to a keyword was performed by returning a
2253           // valid-but-null ExprResult.
2254           return (Expr*)nullptr;
2255         }
2256         State.Consumer->resetCorrectionStream();
2257       }
2258       return TE ? TE : ExprError();
2259     }
2260 
2261     assert(!R.empty() &&
2262            "DiagnoseEmptyLookup returned false but added no results");
2263 
2264     // If we found an Objective-C instance variable, let
2265     // LookupInObjCMethod build the appropriate expression to
2266     // reference the ivar.
2267     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2268       R.clear();
2269       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2270       // In a hopelessly buggy code, Objective-C instance variable
2271       // lookup fails and no expression will be built to reference it.
2272       if (!E.isInvalid() && !E.get())
2273         return ExprError();
2274       return E;
2275     }
2276   }
2277 
2278   // This is guaranteed from this point on.
2279   assert(!R.empty() || ADL);
2280 
2281   // Check whether this might be a C++ implicit instance member access.
2282   // C++ [class.mfct.non-static]p3:
2283   //   When an id-expression that is not part of a class member access
2284   //   syntax and not used to form a pointer to member is used in the
2285   //   body of a non-static member function of class X, if name lookup
2286   //   resolves the name in the id-expression to a non-static non-type
2287   //   member of some class C, the id-expression is transformed into a
2288   //   class member access expression using (*this) as the
2289   //   postfix-expression to the left of the . operator.
2290   //
2291   // But we don't actually need to do this for '&' operands if R
2292   // resolved to a function or overloaded function set, because the
2293   // expression is ill-formed if it actually works out to be a
2294   // non-static member function:
2295   //
2296   // C++ [expr.ref]p4:
2297   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2298   //   [t]he expression can be used only as the left-hand operand of a
2299   //   member function call.
2300   //
2301   // There are other safeguards against such uses, but it's important
2302   // to get this right here so that we don't end up making a
2303   // spuriously dependent expression if we're inside a dependent
2304   // instance method.
2305   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2306     bool MightBeImplicitMember;
2307     if (!IsAddressOfOperand)
2308       MightBeImplicitMember = true;
2309     else if (!SS.isEmpty())
2310       MightBeImplicitMember = false;
2311     else if (R.isOverloadedResult())
2312       MightBeImplicitMember = false;
2313     else if (R.isUnresolvableResult())
2314       MightBeImplicitMember = true;
2315     else
2316       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2317                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2318                               isa<MSPropertyDecl>(R.getFoundDecl());
2319 
2320     if (MightBeImplicitMember)
2321       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2322                                              R, TemplateArgs, S);
2323   }
2324 
2325   if (TemplateArgs || TemplateKWLoc.isValid()) {
2326 
2327     // In C++1y, if this is a variable template id, then check it
2328     // in BuildTemplateIdExpr().
2329     // The single lookup result must be a variable template declaration.
2330     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2331         Id.TemplateId->Kind == TNK_Var_template) {
2332       assert(R.getAsSingle<VarTemplateDecl>() &&
2333              "There should only be one declaration found.");
2334     }
2335 
2336     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2337   }
2338 
2339   return BuildDeclarationNameExpr(SS, R, ADL);
2340 }
2341 
2342 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2343 /// declaration name, generally during template instantiation.
2344 /// There's a large number of things which don't need to be done along
2345 /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2346 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2347     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2348     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2349   DeclContext *DC = computeDeclContext(SS, false);
2350   if (!DC)
2351     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2352                                      NameInfo, /*TemplateArgs=*/nullptr);
2353 
2354   if (RequireCompleteDeclContext(SS, DC))
2355     return ExprError();
2356 
2357   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2358   LookupQualifiedName(R, DC);
2359 
2360   if (R.isAmbiguous())
2361     return ExprError();
2362 
2363   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2364     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2365                                      NameInfo, /*TemplateArgs=*/nullptr);
2366 
2367   if (R.empty()) {
2368     Diag(NameInfo.getLoc(), diag::err_no_member)
2369       << NameInfo.getName() << DC << SS.getRange();
2370     return ExprError();
2371   }
2372 
2373   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2374     // Diagnose a missing typename if this resolved unambiguously to a type in
2375     // a dependent context.  If we can recover with a type, downgrade this to
2376     // a warning in Microsoft compatibility mode.
2377     unsigned DiagID = diag::err_typename_missing;
2378     if (RecoveryTSI && getLangOpts().MSVCCompat)
2379       DiagID = diag::ext_typename_missing;
2380     SourceLocation Loc = SS.getBeginLoc();
2381     auto D = Diag(Loc, DiagID);
2382     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2383       << SourceRange(Loc, NameInfo.getEndLoc());
2384 
2385     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2386     // context.
2387     if (!RecoveryTSI)
2388       return ExprError();
2389 
2390     // Only issue the fixit if we're prepared to recover.
2391     D << FixItHint::CreateInsertion(Loc, "typename ");
2392 
2393     // Recover by pretending this was an elaborated type.
2394     QualType Ty = Context.getTypeDeclType(TD);
2395     TypeLocBuilder TLB;
2396     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2397 
2398     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2399     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2400     QTL.setElaboratedKeywordLoc(SourceLocation());
2401     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2402 
2403     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2404 
2405     return ExprEmpty();
2406   }
2407 
2408   // Defend against this resolving to an implicit member access. We usually
2409   // won't get here if this might be a legitimate a class member (we end up in
2410   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2411   // a pointer-to-member or in an unevaluated context in C++11.
2412   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2413     return BuildPossibleImplicitMemberExpr(SS,
2414                                            /*TemplateKWLoc=*/SourceLocation(),
2415                                            R, /*TemplateArgs=*/nullptr, S);
2416 
2417   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2418 }
2419 
2420 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2421 /// detected that we're currently inside an ObjC method.  Perform some
2422 /// additional lookup.
2423 ///
2424 /// Ideally, most of this would be done by lookup, but there's
2425 /// actually quite a lot of extra work involved.
2426 ///
2427 /// Returns a null sentinel to indicate trivial success.
2428 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2429 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2430                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2431   SourceLocation Loc = Lookup.getNameLoc();
2432   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2433 
2434   // Check for error condition which is already reported.
2435   if (!CurMethod)
2436     return ExprError();
2437 
2438   // There are two cases to handle here.  1) scoped lookup could have failed,
2439   // in which case we should look for an ivar.  2) scoped lookup could have
2440   // found a decl, but that decl is outside the current instance method (i.e.
2441   // a global variable).  In these two cases, we do a lookup for an ivar with
2442   // this name, if the lookup sucedes, we replace it our current decl.
2443 
2444   // If we're in a class method, we don't normally want to look for
2445   // ivars.  But if we don't find anything else, and there's an
2446   // ivar, that's an error.
2447   bool IsClassMethod = CurMethod->isClassMethod();
2448 
2449   bool LookForIvars;
2450   if (Lookup.empty())
2451     LookForIvars = true;
2452   else if (IsClassMethod)
2453     LookForIvars = false;
2454   else
2455     LookForIvars = (Lookup.isSingleResult() &&
2456                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2457   ObjCInterfaceDecl *IFace = nullptr;
2458   if (LookForIvars) {
2459     IFace = CurMethod->getClassInterface();
2460     ObjCInterfaceDecl *ClassDeclared;
2461     ObjCIvarDecl *IV = nullptr;
2462     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2463       // Diagnose using an ivar in a class method.
2464       if (IsClassMethod)
2465         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2466                          << IV->getDeclName());
2467 
2468       // If we're referencing an invalid decl, just return this as a silent
2469       // error node.  The error diagnostic was already emitted on the decl.
2470       if (IV->isInvalidDecl())
2471         return ExprError();
2472 
2473       // Check if referencing a field with __attribute__((deprecated)).
2474       if (DiagnoseUseOfDecl(IV, Loc))
2475         return ExprError();
2476 
2477       // Diagnose the use of an ivar outside of the declaring class.
2478       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2479           !declaresSameEntity(ClassDeclared, IFace) &&
2480           !getLangOpts().DebuggerSupport)
2481         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2482 
2483       // FIXME: This should use a new expr for a direct reference, don't
2484       // turn this into Self->ivar, just return a BareIVarExpr or something.
2485       IdentifierInfo &II = Context.Idents.get("self");
2486       UnqualifiedId SelfName;
2487       SelfName.setIdentifier(&II, SourceLocation());
2488       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2489       CXXScopeSpec SelfScopeSpec;
2490       SourceLocation TemplateKWLoc;
2491       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2492                                               SelfName, false, false);
2493       if (SelfExpr.isInvalid())
2494         return ExprError();
2495 
2496       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2497       if (SelfExpr.isInvalid())
2498         return ExprError();
2499 
2500       MarkAnyDeclReferenced(Loc, IV, true);
2501 
2502       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2503       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2504           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2505         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2506 
2507       ObjCIvarRefExpr *Result = new (Context)
2508           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2509                           IV->getLocation(), SelfExpr.get(), true, true);
2510 
2511       if (getLangOpts().ObjCAutoRefCount) {
2512         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2513           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2514             recordUseOfEvaluatedWeak(Result);
2515         }
2516         if (CurContext->isClosure())
2517           Diag(Loc, diag::warn_implicitly_retains_self)
2518             << FixItHint::CreateInsertion(Loc, "self->");
2519       }
2520 
2521       return Result;
2522     }
2523   } else if (CurMethod->isInstanceMethod()) {
2524     // We should warn if a local variable hides an ivar.
2525     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2526       ObjCInterfaceDecl *ClassDeclared;
2527       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2528         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2529             declaresSameEntity(IFace, ClassDeclared))
2530           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2531       }
2532     }
2533   } else if (Lookup.isSingleResult() &&
2534              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2535     // If accessing a stand-alone ivar in a class method, this is an error.
2536     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2537       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2538                        << IV->getDeclName());
2539   }
2540 
2541   if (Lookup.empty() && II && AllowBuiltinCreation) {
2542     // FIXME. Consolidate this with similar code in LookupName.
2543     if (unsigned BuiltinID = II->getBuiltinID()) {
2544       if (!(getLangOpts().CPlusPlus &&
2545             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2546         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2547                                            S, Lookup.isForRedeclaration(),
2548                                            Lookup.getNameLoc());
2549         if (D) Lookup.addDecl(D);
2550       }
2551     }
2552   }
2553   // Sentinel value saying that we didn't do anything special.
2554   return ExprResult((Expr *)nullptr);
2555 }
2556 
2557 /// \brief Cast a base object to a member's actual type.
2558 ///
2559 /// Logically this happens in three phases:
2560 ///
2561 /// * First we cast from the base type to the naming class.
2562 ///   The naming class is the class into which we were looking
2563 ///   when we found the member;  it's the qualifier type if a
2564 ///   qualifier was provided, and otherwise it's the base type.
2565 ///
2566 /// * Next we cast from the naming class to the declaring class.
2567 ///   If the member we found was brought into a class's scope by
2568 ///   a using declaration, this is that class;  otherwise it's
2569 ///   the class declaring the member.
2570 ///
2571 /// * Finally we cast from the declaring class to the "true"
2572 ///   declaring class of the member.  This conversion does not
2573 ///   obey access control.
2574 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2575 Sema::PerformObjectMemberConversion(Expr *From,
2576                                     NestedNameSpecifier *Qualifier,
2577                                     NamedDecl *FoundDecl,
2578                                     NamedDecl *Member) {
2579   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2580   if (!RD)
2581     return From;
2582 
2583   QualType DestRecordType;
2584   QualType DestType;
2585   QualType FromRecordType;
2586   QualType FromType = From->getType();
2587   bool PointerConversions = false;
2588   if (isa<FieldDecl>(Member)) {
2589     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2590 
2591     if (FromType->getAs<PointerType>()) {
2592       DestType = Context.getPointerType(DestRecordType);
2593       FromRecordType = FromType->getPointeeType();
2594       PointerConversions = true;
2595     } else {
2596       DestType = DestRecordType;
2597       FromRecordType = FromType;
2598     }
2599   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2600     if (Method->isStatic())
2601       return From;
2602 
2603     DestType = Method->getThisType(Context);
2604     DestRecordType = DestType->getPointeeType();
2605 
2606     if (FromType->getAs<PointerType>()) {
2607       FromRecordType = FromType->getPointeeType();
2608       PointerConversions = true;
2609     } else {
2610       FromRecordType = FromType;
2611       DestType = DestRecordType;
2612     }
2613   } else {
2614     // No conversion necessary.
2615     return From;
2616   }
2617 
2618   if (DestType->isDependentType() || FromType->isDependentType())
2619     return From;
2620 
2621   // If the unqualified types are the same, no conversion is necessary.
2622   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2623     return From;
2624 
2625   SourceRange FromRange = From->getSourceRange();
2626   SourceLocation FromLoc = FromRange.getBegin();
2627 
2628   ExprValueKind VK = From->getValueKind();
2629 
2630   // C++ [class.member.lookup]p8:
2631   //   [...] Ambiguities can often be resolved by qualifying a name with its
2632   //   class name.
2633   //
2634   // If the member was a qualified name and the qualified referred to a
2635   // specific base subobject type, we'll cast to that intermediate type
2636   // first and then to the object in which the member is declared. That allows
2637   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2638   //
2639   //   class Base { public: int x; };
2640   //   class Derived1 : public Base { };
2641   //   class Derived2 : public Base { };
2642   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2643   //
2644   //   void VeryDerived::f() {
2645   //     x = 17; // error: ambiguous base subobjects
2646   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2647   //   }
2648   if (Qualifier && Qualifier->getAsType()) {
2649     QualType QType = QualType(Qualifier->getAsType(), 0);
2650     assert(QType->isRecordType() && "lookup done with non-record type");
2651 
2652     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2653 
2654     // In C++98, the qualifier type doesn't actually have to be a base
2655     // type of the object type, in which case we just ignore it.
2656     // Otherwise build the appropriate casts.
2657     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2658       CXXCastPath BasePath;
2659       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2660                                        FromLoc, FromRange, &BasePath))
2661         return ExprError();
2662 
2663       if (PointerConversions)
2664         QType = Context.getPointerType(QType);
2665       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2666                                VK, &BasePath).get();
2667 
2668       FromType = QType;
2669       FromRecordType = QRecordType;
2670 
2671       // If the qualifier type was the same as the destination type,
2672       // we're done.
2673       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2674         return From;
2675     }
2676   }
2677 
2678   bool IgnoreAccess = false;
2679 
2680   // If we actually found the member through a using declaration, cast
2681   // down to the using declaration's type.
2682   //
2683   // Pointer equality is fine here because only one declaration of a
2684   // class ever has member declarations.
2685   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2686     assert(isa<UsingShadowDecl>(FoundDecl));
2687     QualType URecordType = Context.getTypeDeclType(
2688                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2689 
2690     // We only need to do this if the naming-class to declaring-class
2691     // conversion is non-trivial.
2692     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2693       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2694       CXXCastPath BasePath;
2695       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2696                                        FromLoc, FromRange, &BasePath))
2697         return ExprError();
2698 
2699       QualType UType = URecordType;
2700       if (PointerConversions)
2701         UType = Context.getPointerType(UType);
2702       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2703                                VK, &BasePath).get();
2704       FromType = UType;
2705       FromRecordType = URecordType;
2706     }
2707 
2708     // We don't do access control for the conversion from the
2709     // declaring class to the true declaring class.
2710     IgnoreAccess = true;
2711   }
2712 
2713   CXXCastPath BasePath;
2714   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2715                                    FromLoc, FromRange, &BasePath,
2716                                    IgnoreAccess))
2717     return ExprError();
2718 
2719   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2720                            VK, &BasePath);
2721 }
2722 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2723 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2724                                       const LookupResult &R,
2725                                       bool HasTrailingLParen) {
2726   // Only when used directly as the postfix-expression of a call.
2727   if (!HasTrailingLParen)
2728     return false;
2729 
2730   // Never if a scope specifier was provided.
2731   if (SS.isSet())
2732     return false;
2733 
2734   // Only in C++ or ObjC++.
2735   if (!getLangOpts().CPlusPlus)
2736     return false;
2737 
2738   // Turn off ADL when we find certain kinds of declarations during
2739   // normal lookup:
2740   for (NamedDecl *D : R) {
2741     // C++0x [basic.lookup.argdep]p3:
2742     //     -- a declaration of a class member
2743     // Since using decls preserve this property, we check this on the
2744     // original decl.
2745     if (D->isCXXClassMember())
2746       return false;
2747 
2748     // C++0x [basic.lookup.argdep]p3:
2749     //     -- a block-scope function declaration that is not a
2750     //        using-declaration
2751     // NOTE: we also trigger this for function templates (in fact, we
2752     // don't check the decl type at all, since all other decl types
2753     // turn off ADL anyway).
2754     if (isa<UsingShadowDecl>(D))
2755       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2756     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2757       return false;
2758 
2759     // C++0x [basic.lookup.argdep]p3:
2760     //     -- a declaration that is neither a function or a function
2761     //        template
2762     // And also for builtin functions.
2763     if (isa<FunctionDecl>(D)) {
2764       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2765 
2766       // But also builtin functions.
2767       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2768         return false;
2769     } else if (!isa<FunctionTemplateDecl>(D))
2770       return false;
2771   }
2772 
2773   return true;
2774 }
2775 
2776 
2777 /// Diagnoses obvious problems with the use of the given declaration
2778 /// as an expression.  This is only actually called for lookups that
2779 /// were not overloaded, and it doesn't promise that the declaration
2780 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)2781 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2782   if (isa<TypedefNameDecl>(D)) {
2783     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2784     return true;
2785   }
2786 
2787   if (isa<ObjCInterfaceDecl>(D)) {
2788     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2789     return true;
2790   }
2791 
2792   if (isa<NamespaceDecl>(D)) {
2793     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2794     return true;
2795   }
2796 
2797   return false;
2798 }
2799 
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)2800 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2801                                           LookupResult &R, bool NeedsADL,
2802                                           bool AcceptInvalidDecl) {
2803   // If this is a single, fully-resolved result and we don't need ADL,
2804   // just build an ordinary singleton decl ref.
2805   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2806     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2807                                     R.getRepresentativeDecl(), nullptr,
2808                                     AcceptInvalidDecl);
2809 
2810   // We only need to check the declaration if there's exactly one
2811   // result, because in the overloaded case the results can only be
2812   // functions and function templates.
2813   if (R.isSingleResult() &&
2814       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2815     return ExprError();
2816 
2817   // Otherwise, just build an unresolved lookup expression.  Suppress
2818   // any lookup-related diagnostics; we'll hash these out later, when
2819   // we've picked a target.
2820   R.suppressDiagnostics();
2821 
2822   UnresolvedLookupExpr *ULE
2823     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2824                                    SS.getWithLocInContext(Context),
2825                                    R.getLookupNameInfo(),
2826                                    NeedsADL, R.isOverloadedResult(),
2827                                    R.begin(), R.end());
2828 
2829   return ULE;
2830 }
2831 
2832 /// \brief 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)2833 ExprResult Sema::BuildDeclarationNameExpr(
2834     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2835     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2836     bool AcceptInvalidDecl) {
2837   assert(D && "Cannot refer to a NULL declaration");
2838   assert(!isa<FunctionTemplateDecl>(D) &&
2839          "Cannot refer unambiguously to a function template");
2840 
2841   SourceLocation Loc = NameInfo.getLoc();
2842   if (CheckDeclInExpr(*this, Loc, D))
2843     return ExprError();
2844 
2845   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2846     // Specifically diagnose references to class templates that are missing
2847     // a template argument list.
2848     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2849                                            << Template << SS.getRange();
2850     Diag(Template->getLocation(), diag::note_template_decl_here);
2851     return ExprError();
2852   }
2853 
2854   // Make sure that we're referring to a value.
2855   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2856   if (!VD) {
2857     Diag(Loc, diag::err_ref_non_value)
2858       << D << SS.getRange();
2859     Diag(D->getLocation(), diag::note_declared_at);
2860     return ExprError();
2861   }
2862 
2863   // Check whether this declaration can be used. Note that we suppress
2864   // this check when we're going to perform argument-dependent lookup
2865   // on this function name, because this might not be the function
2866   // that overload resolution actually selects.
2867   if (DiagnoseUseOfDecl(VD, Loc))
2868     return ExprError();
2869 
2870   // Only create DeclRefExpr's for valid Decl's.
2871   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2872     return ExprError();
2873 
2874   // Handle members of anonymous structs and unions.  If we got here,
2875   // and the reference is to a class member indirect field, then this
2876   // must be the subject of a pointer-to-member expression.
2877   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2878     if (!indirectField->isCXXClassMember())
2879       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2880                                                       indirectField);
2881 
2882   {
2883     QualType type = VD->getType();
2884     ExprValueKind valueKind = VK_RValue;
2885 
2886     switch (D->getKind()) {
2887     // Ignore all the non-ValueDecl kinds.
2888 #define ABSTRACT_DECL(kind)
2889 #define VALUE(type, base)
2890 #define DECL(type, base) \
2891     case Decl::type:
2892 #include "clang/AST/DeclNodes.inc"
2893       llvm_unreachable("invalid value decl kind");
2894 
2895     // These shouldn't make it here.
2896     case Decl::ObjCAtDefsField:
2897     case Decl::ObjCIvar:
2898       llvm_unreachable("forming non-member reference to ivar?");
2899 
2900     // Enum constants are always r-values and never references.
2901     // Unresolved using declarations are dependent.
2902     case Decl::EnumConstant:
2903     case Decl::UnresolvedUsingValue:
2904     case Decl::OMPDeclareReduction:
2905       valueKind = VK_RValue;
2906       break;
2907 
2908     // Fields and indirect fields that got here must be for
2909     // pointer-to-member expressions; we just call them l-values for
2910     // internal consistency, because this subexpression doesn't really
2911     // exist in the high-level semantics.
2912     case Decl::Field:
2913     case Decl::IndirectField:
2914       assert(getLangOpts().CPlusPlus &&
2915              "building reference to field in C?");
2916 
2917       // These can't have reference type in well-formed programs, but
2918       // for internal consistency we do this anyway.
2919       type = type.getNonReferenceType();
2920       valueKind = VK_LValue;
2921       break;
2922 
2923     // Non-type template parameters are either l-values or r-values
2924     // depending on the type.
2925     case Decl::NonTypeTemplateParm: {
2926       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2927         type = reftype->getPointeeType();
2928         valueKind = VK_LValue; // even if the parameter is an r-value reference
2929         break;
2930       }
2931 
2932       // For non-references, we need to strip qualifiers just in case
2933       // the template parameter was declared as 'const int' or whatever.
2934       valueKind = VK_RValue;
2935       type = type.getUnqualifiedType();
2936       break;
2937     }
2938 
2939     case Decl::Var:
2940     case Decl::VarTemplateSpecialization:
2941     case Decl::VarTemplatePartialSpecialization:
2942     case Decl::OMPCapturedExpr:
2943       // In C, "extern void blah;" is valid and is an r-value.
2944       if (!getLangOpts().CPlusPlus &&
2945           !type.hasQualifiers() &&
2946           type->isVoidType()) {
2947         valueKind = VK_RValue;
2948         break;
2949       }
2950       // fallthrough
2951 
2952     case Decl::ImplicitParam:
2953     case Decl::ParmVar: {
2954       // These are always l-values.
2955       valueKind = VK_LValue;
2956       type = type.getNonReferenceType();
2957 
2958       // FIXME: Does the addition of const really only apply in
2959       // potentially-evaluated contexts? Since the variable isn't actually
2960       // captured in an unevaluated context, it seems that the answer is no.
2961       if (!isUnevaluatedContext()) {
2962         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2963         if (!CapturedType.isNull())
2964           type = CapturedType;
2965       }
2966 
2967       break;
2968     }
2969 
2970     case Decl::Function: {
2971       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2972         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2973           type = Context.BuiltinFnTy;
2974           valueKind = VK_RValue;
2975           break;
2976         }
2977       }
2978 
2979       const FunctionType *fty = type->castAs<FunctionType>();
2980 
2981       // If we're referring to a function with an __unknown_anytype
2982       // result type, make the entire expression __unknown_anytype.
2983       if (fty->getReturnType() == Context.UnknownAnyTy) {
2984         type = Context.UnknownAnyTy;
2985         valueKind = VK_RValue;
2986         break;
2987       }
2988 
2989       // Functions are l-values in C++.
2990       if (getLangOpts().CPlusPlus) {
2991         valueKind = VK_LValue;
2992         break;
2993       }
2994 
2995       // C99 DR 316 says that, if a function type comes from a
2996       // function definition (without a prototype), that type is only
2997       // used for checking compatibility. Therefore, when referencing
2998       // the function, we pretend that we don't have the full function
2999       // type.
3000       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3001           isa<FunctionProtoType>(fty))
3002         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3003                                               fty->getExtInfo());
3004 
3005       // Functions are r-values in C.
3006       valueKind = VK_RValue;
3007       break;
3008     }
3009 
3010     case Decl::MSProperty:
3011       valueKind = VK_LValue;
3012       break;
3013 
3014     case Decl::CXXMethod:
3015       // If we're referring to a method with an __unknown_anytype
3016       // result type, make the entire expression __unknown_anytype.
3017       // This should only be possible with a type written directly.
3018       if (const FunctionProtoType *proto
3019             = dyn_cast<FunctionProtoType>(VD->getType()))
3020         if (proto->getReturnType() == Context.UnknownAnyTy) {
3021           type = Context.UnknownAnyTy;
3022           valueKind = VK_RValue;
3023           break;
3024         }
3025 
3026       // C++ methods are l-values if static, r-values if non-static.
3027       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3028         valueKind = VK_LValue;
3029         break;
3030       }
3031       // fallthrough
3032 
3033     case Decl::CXXConversion:
3034     case Decl::CXXDestructor:
3035     case Decl::CXXConstructor:
3036       valueKind = VK_RValue;
3037       break;
3038     }
3039 
3040     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3041                             TemplateArgs);
3042   }
3043 }
3044 
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3045 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3046                                     SmallString<32> &Target) {
3047   Target.resize(CharByteWidth * (Source.size() + 1));
3048   char *ResultPtr = &Target[0];
3049   const UTF8 *ErrorPtr;
3050   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3051   (void)success;
3052   assert(success);
3053   Target.resize(ResultPtr - &Target[0]);
3054 }
3055 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentType IT)3056 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3057                                      PredefinedExpr::IdentType IT) {
3058   // Pick the current block, lambda, captured statement or function.
3059   Decl *currentDecl = nullptr;
3060   if (const BlockScopeInfo *BSI = getCurBlock())
3061     currentDecl = BSI->TheDecl;
3062   else if (const LambdaScopeInfo *LSI = getCurLambda())
3063     currentDecl = LSI->CallOperator;
3064   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3065     currentDecl = CSI->TheCapturedDecl;
3066   else
3067     currentDecl = getCurFunctionOrMethodDecl();
3068 
3069   if (!currentDecl) {
3070     Diag(Loc, diag::ext_predef_outside_function);
3071     currentDecl = Context.getTranslationUnitDecl();
3072   }
3073 
3074   QualType ResTy;
3075   StringLiteral *SL = nullptr;
3076   if (cast<DeclContext>(currentDecl)->isDependentContext())
3077     ResTy = Context.DependentTy;
3078   else {
3079     // Pre-defined identifiers are of type char[x], where x is the length of
3080     // the string.
3081     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3082     unsigned Length = Str.length();
3083 
3084     llvm::APInt LengthI(32, Length + 1);
3085     if (IT == PredefinedExpr::LFunction) {
3086       ResTy = Context.WideCharTy.withConst();
3087       SmallString<32> RawChars;
3088       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3089                               Str, RawChars);
3090       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3091                                            /*IndexTypeQuals*/ 0);
3092       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3093                                  /*Pascal*/ false, ResTy, Loc);
3094     } else {
3095       ResTy = Context.CharTy.withConst();
3096       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3097                                            /*IndexTypeQuals*/ 0);
3098       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3099                                  /*Pascal*/ false, ResTy, Loc);
3100     }
3101   }
3102 
3103   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3104 }
3105 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3106 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3107   PredefinedExpr::IdentType IT;
3108 
3109   switch (Kind) {
3110   default: llvm_unreachable("Unknown simple primary expr!");
3111   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3112   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3113   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3114   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3115   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3116   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3117   }
3118 
3119   return BuildPredefinedExpr(Loc, IT);
3120 }
3121 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3122 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3123   SmallString<16> CharBuffer;
3124   bool Invalid = false;
3125   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3126   if (Invalid)
3127     return ExprError();
3128 
3129   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3130                             PP, Tok.getKind());
3131   if (Literal.hadError())
3132     return ExprError();
3133 
3134   QualType Ty;
3135   if (Literal.isWide())
3136     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3137   else if (Literal.isUTF16())
3138     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3139   else if (Literal.isUTF32())
3140     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3141   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3142     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3143   else
3144     Ty = Context.CharTy;  // 'x' -> char in C++
3145 
3146   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3147   if (Literal.isWide())
3148     Kind = CharacterLiteral::Wide;
3149   else if (Literal.isUTF16())
3150     Kind = CharacterLiteral::UTF16;
3151   else if (Literal.isUTF32())
3152     Kind = CharacterLiteral::UTF32;
3153   else if (Literal.isUTF8())
3154     Kind = CharacterLiteral::UTF8;
3155 
3156   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3157                                              Tok.getLocation());
3158 
3159   if (Literal.getUDSuffix().empty())
3160     return Lit;
3161 
3162   // We're building a user-defined literal.
3163   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3164   SourceLocation UDSuffixLoc =
3165     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3166 
3167   // Make sure we're allowed user-defined literals here.
3168   if (!UDLScope)
3169     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3170 
3171   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3172   //   operator "" X (ch)
3173   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3174                                         Lit, Tok.getLocation());
3175 }
3176 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3177 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3178   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3179   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3180                                 Context.IntTy, Loc);
3181 }
3182 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3183 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3184                                   QualType Ty, SourceLocation Loc) {
3185   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3186 
3187   using llvm::APFloat;
3188   APFloat Val(Format);
3189 
3190   APFloat::opStatus result = Literal.GetFloatValue(Val);
3191 
3192   // Overflow is always an error, but underflow is only an error if
3193   // we underflowed to zero (APFloat reports denormals as underflow).
3194   if ((result & APFloat::opOverflow) ||
3195       ((result & APFloat::opUnderflow) && Val.isZero())) {
3196     unsigned diagnostic;
3197     SmallString<20> buffer;
3198     if (result & APFloat::opOverflow) {
3199       diagnostic = diag::warn_float_overflow;
3200       APFloat::getLargest(Format).toString(buffer);
3201     } else {
3202       diagnostic = diag::warn_float_underflow;
3203       APFloat::getSmallest(Format).toString(buffer);
3204     }
3205 
3206     S.Diag(Loc, diagnostic)
3207       << Ty
3208       << StringRef(buffer.data(), buffer.size());
3209   }
3210 
3211   bool isExact = (result == APFloat::opOK);
3212   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3213 }
3214 
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3215 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3216   assert(E && "Invalid expression");
3217 
3218   if (E->isValueDependent())
3219     return false;
3220 
3221   QualType QT = E->getType();
3222   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3223     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3224     return true;
3225   }
3226 
3227   llvm::APSInt ValueAPS;
3228   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3229 
3230   if (R.isInvalid())
3231     return true;
3232 
3233   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3234   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3235     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3236         << ValueAPS.toString(10) << ValueIsPositive;
3237     return true;
3238   }
3239 
3240   return false;
3241 }
3242 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3243 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3244   // Fast path for a single digit (which is quite common).  A single digit
3245   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3246   if (Tok.getLength() == 1) {
3247     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3248     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3249   }
3250 
3251   SmallString<128> SpellingBuffer;
3252   // NumericLiteralParser wants to overread by one character.  Add padding to
3253   // the buffer in case the token is copied to the buffer.  If getSpelling()
3254   // returns a StringRef to the memory buffer, it should have a null char at
3255   // the EOF, so it is also safe.
3256   SpellingBuffer.resize(Tok.getLength() + 1);
3257 
3258   // Get the spelling of the token, which eliminates trigraphs, etc.
3259   bool Invalid = false;
3260   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3261   if (Invalid)
3262     return ExprError();
3263 
3264   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3265   if (Literal.hadError)
3266     return ExprError();
3267 
3268   if (Literal.hasUDSuffix()) {
3269     // We're building a user-defined literal.
3270     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3271     SourceLocation UDSuffixLoc =
3272       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3273 
3274     // Make sure we're allowed user-defined literals here.
3275     if (!UDLScope)
3276       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3277 
3278     QualType CookedTy;
3279     if (Literal.isFloatingLiteral()) {
3280       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3281       // long double, the literal is treated as a call of the form
3282       //   operator "" X (f L)
3283       CookedTy = Context.LongDoubleTy;
3284     } else {
3285       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3286       // unsigned long long, the literal is treated as a call of the form
3287       //   operator "" X (n ULL)
3288       CookedTy = Context.UnsignedLongLongTy;
3289     }
3290 
3291     DeclarationName OpName =
3292       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3293     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3294     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3295 
3296     SourceLocation TokLoc = Tok.getLocation();
3297 
3298     // Perform literal operator lookup to determine if we're building a raw
3299     // literal or a cooked one.
3300     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3301     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3302                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3303                                   /*AllowStringTemplate*/false)) {
3304     case LOLR_Error:
3305       return ExprError();
3306 
3307     case LOLR_Cooked: {
3308       Expr *Lit;
3309       if (Literal.isFloatingLiteral()) {
3310         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3311       } else {
3312         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3313         if (Literal.GetIntegerValue(ResultVal))
3314           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3315               << /* Unsigned */ 1;
3316         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3317                                      Tok.getLocation());
3318       }
3319       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3320     }
3321 
3322     case LOLR_Raw: {
3323       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3324       // literal is treated as a call of the form
3325       //   operator "" X ("n")
3326       unsigned Length = Literal.getUDSuffixOffset();
3327       QualType StrTy = Context.getConstantArrayType(
3328           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3329           ArrayType::Normal, 0);
3330       Expr *Lit = StringLiteral::Create(
3331           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3332           /*Pascal*/false, StrTy, &TokLoc, 1);
3333       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3334     }
3335 
3336     case LOLR_Template: {
3337       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3338       // template), L is treated as a call fo the form
3339       //   operator "" X <'c1', 'c2', ... 'ck'>()
3340       // where n is the source character sequence c1 c2 ... ck.
3341       TemplateArgumentListInfo ExplicitArgs;
3342       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3343       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3344       llvm::APSInt Value(CharBits, CharIsUnsigned);
3345       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3346         Value = TokSpelling[I];
3347         TemplateArgument Arg(Context, Value, Context.CharTy);
3348         TemplateArgumentLocInfo ArgInfo;
3349         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3350       }
3351       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3352                                       &ExplicitArgs);
3353     }
3354     case LOLR_StringTemplate:
3355       llvm_unreachable("unexpected literal operator lookup result");
3356     }
3357   }
3358 
3359   Expr *Res;
3360 
3361   if (Literal.isFloatingLiteral()) {
3362     QualType Ty;
3363     if (Literal.isHalf){
3364       if (getOpenCLOptions().cl_khr_fp16)
3365         Ty = Context.HalfTy;
3366       else {
3367         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3368         return ExprError();
3369       }
3370     } else if (Literal.isFloat)
3371       Ty = Context.FloatTy;
3372     else if (Literal.isLong)
3373       Ty = Context.LongDoubleTy;
3374     else if (Literal.isFloat128)
3375       Ty = Context.Float128Ty;
3376     else
3377       Ty = Context.DoubleTy;
3378 
3379     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3380 
3381     if (Ty == Context.DoubleTy) {
3382       if (getLangOpts().SinglePrecisionConstants) {
3383         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3384       } else if (getLangOpts().OpenCL &&
3385                  !((getLangOpts().OpenCLVersion >= 120) ||
3386                    getOpenCLOptions().cl_khr_fp64)) {
3387         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3388         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3389       }
3390     }
3391   } else if (!Literal.isIntegerLiteral()) {
3392     return ExprError();
3393   } else {
3394     QualType Ty;
3395 
3396     // 'long long' is a C99 or C++11 feature.
3397     if (!getLangOpts().C99 && Literal.isLongLong) {
3398       if (getLangOpts().CPlusPlus)
3399         Diag(Tok.getLocation(),
3400              getLangOpts().CPlusPlus11 ?
3401              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3402       else
3403         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3404     }
3405 
3406     // Get the value in the widest-possible width.
3407     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3408     llvm::APInt ResultVal(MaxWidth, 0);
3409 
3410     if (Literal.GetIntegerValue(ResultVal)) {
3411       // If this value didn't fit into uintmax_t, error and force to ull.
3412       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3413           << /* Unsigned */ 1;
3414       Ty = Context.UnsignedLongLongTy;
3415       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3416              "long long is not intmax_t?");
3417     } else {
3418       // If this value fits into a ULL, try to figure out what else it fits into
3419       // according to the rules of C99 6.4.4.1p5.
3420 
3421       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3422       // be an unsigned int.
3423       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3424 
3425       // Check from smallest to largest, picking the smallest type we can.
3426       unsigned Width = 0;
3427 
3428       // Microsoft specific integer suffixes are explicitly sized.
3429       if (Literal.MicrosoftInteger) {
3430         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3431           Width = 8;
3432           Ty = Context.CharTy;
3433         } else {
3434           Width = Literal.MicrosoftInteger;
3435           Ty = Context.getIntTypeForBitwidth(Width,
3436                                              /*Signed=*/!Literal.isUnsigned);
3437         }
3438       }
3439 
3440       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3441         // Are int/unsigned possibilities?
3442         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3443 
3444         // Does it fit in a unsigned int?
3445         if (ResultVal.isIntN(IntSize)) {
3446           // Does it fit in a signed int?
3447           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3448             Ty = Context.IntTy;
3449           else if (AllowUnsigned)
3450             Ty = Context.UnsignedIntTy;
3451           Width = IntSize;
3452         }
3453       }
3454 
3455       // Are long/unsigned long possibilities?
3456       if (Ty.isNull() && !Literal.isLongLong) {
3457         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3458 
3459         // Does it fit in a unsigned long?
3460         if (ResultVal.isIntN(LongSize)) {
3461           // Does it fit in a signed long?
3462           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3463             Ty = Context.LongTy;
3464           else if (AllowUnsigned)
3465             Ty = Context.UnsignedLongTy;
3466           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3467           // is compatible.
3468           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3469             const unsigned LongLongSize =
3470                 Context.getTargetInfo().getLongLongWidth();
3471             Diag(Tok.getLocation(),
3472                  getLangOpts().CPlusPlus
3473                      ? Literal.isLong
3474                            ? diag::warn_old_implicitly_unsigned_long_cxx
3475                            : /*C++98 UB*/ diag::
3476                                  ext_old_implicitly_unsigned_long_cxx
3477                      : diag::warn_old_implicitly_unsigned_long)
3478                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3479                                             : /*will be ill-formed*/ 1);
3480             Ty = Context.UnsignedLongTy;
3481           }
3482           Width = LongSize;
3483         }
3484       }
3485 
3486       // Check long long if needed.
3487       if (Ty.isNull()) {
3488         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3489 
3490         // Does it fit in a unsigned long long?
3491         if (ResultVal.isIntN(LongLongSize)) {
3492           // Does it fit in a signed long long?
3493           // To be compatible with MSVC, hex integer literals ending with the
3494           // LL or i64 suffix are always signed in Microsoft mode.
3495           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3496               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3497             Ty = Context.LongLongTy;
3498           else if (AllowUnsigned)
3499             Ty = Context.UnsignedLongLongTy;
3500           Width = LongLongSize;
3501         }
3502       }
3503 
3504       // If we still couldn't decide a type, we probably have something that
3505       // does not fit in a signed long long, but has no U suffix.
3506       if (Ty.isNull()) {
3507         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3508         Ty = Context.UnsignedLongLongTy;
3509         Width = Context.getTargetInfo().getLongLongWidth();
3510       }
3511 
3512       if (ResultVal.getBitWidth() != Width)
3513         ResultVal = ResultVal.trunc(Width);
3514     }
3515     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3516   }
3517 
3518   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3519   if (Literal.isImaginary)
3520     Res = new (Context) ImaginaryLiteral(Res,
3521                                         Context.getComplexType(Res->getType()));
3522 
3523   return Res;
3524 }
3525 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3526 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3527   assert(E && "ActOnParenExpr() missing expr");
3528   return new (Context) ParenExpr(L, R, E);
3529 }
3530 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3531 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3532                                          SourceLocation Loc,
3533                                          SourceRange ArgRange) {
3534   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3535   // scalar or vector data type argument..."
3536   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3537   // type (C99 6.2.5p18) or void.
3538   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3539     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3540       << T << ArgRange;
3541     return true;
3542   }
3543 
3544   assert((T->isVoidType() || !T->isIncompleteType()) &&
3545          "Scalar types should always be complete");
3546   return false;
3547 }
3548 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3549 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3550                                            SourceLocation Loc,
3551                                            SourceRange ArgRange,
3552                                            UnaryExprOrTypeTrait TraitKind) {
3553   // Invalid types must be hard errors for SFINAE in C++.
3554   if (S.LangOpts.CPlusPlus)
3555     return true;
3556 
3557   // C99 6.5.3.4p1:
3558   if (T->isFunctionType() &&
3559       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3560     // sizeof(function)/alignof(function) is allowed as an extension.
3561     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3562       << TraitKind << ArgRange;
3563     return false;
3564   }
3565 
3566   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3567   // this is an error (OpenCL v1.1 s6.3.k)
3568   if (T->isVoidType()) {
3569     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3570                                         : diag::ext_sizeof_alignof_void_type;
3571     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3572     return false;
3573   }
3574 
3575   return true;
3576 }
3577 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3578 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3579                                              SourceLocation Loc,
3580                                              SourceRange ArgRange,
3581                                              UnaryExprOrTypeTrait TraitKind) {
3582   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3583   // runtime doesn't allow it.
3584   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3585     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3586       << T << (TraitKind == UETT_SizeOf)
3587       << ArgRange;
3588     return true;
3589   }
3590 
3591   return false;
3592 }
3593 
3594 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3595 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)3596 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3597                                      Expr *E) {
3598   // Don't warn if the operation changed the type.
3599   if (T != E->getType())
3600     return;
3601 
3602   // Now look for array decays.
3603   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3604   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3605     return;
3606 
3607   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3608                                              << ICE->getType()
3609                                              << ICE->getSubExpr()->getType();
3610 }
3611 
3612 /// \brief Check the constraints on expression operands to unary type expression
3613 /// and type traits.
3614 ///
3615 /// Completes any types necessary and validates the constraints on the operand
3616 /// expression. The logic mostly mirrors the type-based overload, but may modify
3617 /// the expression as it completes the type for that expression through template
3618 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)3619 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3620                                             UnaryExprOrTypeTrait ExprKind) {
3621   QualType ExprTy = E->getType();
3622   assert(!ExprTy->isReferenceType());
3623 
3624   if (ExprKind == UETT_VecStep)
3625     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3626                                         E->getSourceRange());
3627 
3628   // Whitelist some types as extensions
3629   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3630                                       E->getSourceRange(), ExprKind))
3631     return false;
3632 
3633   // 'alignof' applied to an expression only requires the base element type of
3634   // the expression to be complete. 'sizeof' requires the expression's type to
3635   // be complete (and will attempt to complete it if it's an array of unknown
3636   // bound).
3637   if (ExprKind == UETT_AlignOf) {
3638     if (RequireCompleteType(E->getExprLoc(),
3639                             Context.getBaseElementType(E->getType()),
3640                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3641                             E->getSourceRange()))
3642       return true;
3643   } else {
3644     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3645                                 ExprKind, E->getSourceRange()))
3646       return true;
3647   }
3648 
3649   // Completing the expression's type may have changed it.
3650   ExprTy = E->getType();
3651   assert(!ExprTy->isReferenceType());
3652 
3653   if (ExprTy->isFunctionType()) {
3654     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3655       << ExprKind << E->getSourceRange();
3656     return true;
3657   }
3658 
3659   // The operand for sizeof and alignof is in an unevaluated expression context,
3660   // so side effects could result in unintended consequences.
3661   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3662       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3663     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3664 
3665   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3666                                        E->getSourceRange(), ExprKind))
3667     return true;
3668 
3669   if (ExprKind == UETT_SizeOf) {
3670     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3671       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3672         QualType OType = PVD->getOriginalType();
3673         QualType Type = PVD->getType();
3674         if (Type->isPointerType() && OType->isArrayType()) {
3675           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3676             << Type << OType;
3677           Diag(PVD->getLocation(), diag::note_declared_at);
3678         }
3679       }
3680     }
3681 
3682     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3683     // decays into a pointer and returns an unintended result. This is most
3684     // likely a typo for "sizeof(array) op x".
3685     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3686       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3687                                BO->getLHS());
3688       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3689                                BO->getRHS());
3690     }
3691   }
3692 
3693   return false;
3694 }
3695 
3696 /// \brief Check the constraints on operands to unary expression and type
3697 /// traits.
3698 ///
3699 /// This will complete any types necessary, and validate the various constraints
3700 /// on those operands.
3701 ///
3702 /// The UsualUnaryConversions() function is *not* called by this routine.
3703 /// C99 6.3.2.1p[2-4] all state:
3704 ///   Except when it is the operand of the sizeof operator ...
3705 ///
3706 /// C++ [expr.sizeof]p4
3707 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3708 ///   standard conversions are not applied to the operand of sizeof.
3709 ///
3710 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)3711 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3712                                             SourceLocation OpLoc,
3713                                             SourceRange ExprRange,
3714                                             UnaryExprOrTypeTrait ExprKind) {
3715   if (ExprType->isDependentType())
3716     return false;
3717 
3718   // C++ [expr.sizeof]p2:
3719   //     When applied to a reference or a reference type, the result
3720   //     is the size of the referenced type.
3721   // C++11 [expr.alignof]p3:
3722   //     When alignof is applied to a reference type, the result
3723   //     shall be the alignment of the referenced type.
3724   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3725     ExprType = Ref->getPointeeType();
3726 
3727   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3728   //   When alignof or _Alignof is applied to an array type, the result
3729   //   is the alignment of the element type.
3730   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3731     ExprType = Context.getBaseElementType(ExprType);
3732 
3733   if (ExprKind == UETT_VecStep)
3734     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3735 
3736   // Whitelist some types as extensions
3737   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3738                                       ExprKind))
3739     return false;
3740 
3741   if (RequireCompleteType(OpLoc, ExprType,
3742                           diag::err_sizeof_alignof_incomplete_type,
3743                           ExprKind, ExprRange))
3744     return true;
3745 
3746   if (ExprType->isFunctionType()) {
3747     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3748       << ExprKind << ExprRange;
3749     return true;
3750   }
3751 
3752   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3753                                        ExprKind))
3754     return true;
3755 
3756   return false;
3757 }
3758 
CheckAlignOfExpr(Sema & S,Expr * E)3759 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3760   E = E->IgnoreParens();
3761 
3762   // Cannot know anything else if the expression is dependent.
3763   if (E->isTypeDependent())
3764     return false;
3765 
3766   if (E->getObjectKind() == OK_BitField) {
3767     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3768        << 1 << E->getSourceRange();
3769     return true;
3770   }
3771 
3772   ValueDecl *D = nullptr;
3773   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3774     D = DRE->getDecl();
3775   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3776     D = ME->getMemberDecl();
3777   }
3778 
3779   // If it's a field, require the containing struct to have a
3780   // complete definition so that we can compute the layout.
3781   //
3782   // This can happen in C++11 onwards, either by naming the member
3783   // in a way that is not transformed into a member access expression
3784   // (in an unevaluated operand, for instance), or by naming the member
3785   // in a trailing-return-type.
3786   //
3787   // For the record, since __alignof__ on expressions is a GCC
3788   // extension, GCC seems to permit this but always gives the
3789   // nonsensical answer 0.
3790   //
3791   // We don't really need the layout here --- we could instead just
3792   // directly check for all the appropriate alignment-lowing
3793   // attributes --- but that would require duplicating a lot of
3794   // logic that just isn't worth duplicating for such a marginal
3795   // use-case.
3796   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3797     // Fast path this check, since we at least know the record has a
3798     // definition if we can find a member of it.
3799     if (!FD->getParent()->isCompleteDefinition()) {
3800       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3801         << E->getSourceRange();
3802       return true;
3803     }
3804 
3805     // Otherwise, if it's a field, and the field doesn't have
3806     // reference type, then it must have a complete type (or be a
3807     // flexible array member, which we explicitly want to
3808     // white-list anyway), which makes the following checks trivial.
3809     if (!FD->getType()->isReferenceType())
3810       return false;
3811   }
3812 
3813   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3814 }
3815 
CheckVecStepExpr(Expr * E)3816 bool Sema::CheckVecStepExpr(Expr *E) {
3817   E = E->IgnoreParens();
3818 
3819   // Cannot know anything else if the expression is dependent.
3820   if (E->isTypeDependent())
3821     return false;
3822 
3823   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3824 }
3825 
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)3826 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3827                                         CapturingScopeInfo *CSI) {
3828   assert(T->isVariablyModifiedType());
3829   assert(CSI != nullptr);
3830 
3831   // We're going to walk down into the type and look for VLA expressions.
3832   do {
3833     const Type *Ty = T.getTypePtr();
3834     switch (Ty->getTypeClass()) {
3835 #define TYPE(Class, Base)
3836 #define ABSTRACT_TYPE(Class, Base)
3837 #define NON_CANONICAL_TYPE(Class, Base)
3838 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3839 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3840 #include "clang/AST/TypeNodes.def"
3841       T = QualType();
3842       break;
3843     // These types are never variably-modified.
3844     case Type::Builtin:
3845     case Type::Complex:
3846     case Type::Vector:
3847     case Type::ExtVector:
3848     case Type::Record:
3849     case Type::Enum:
3850     case Type::Elaborated:
3851     case Type::TemplateSpecialization:
3852     case Type::ObjCObject:
3853     case Type::ObjCInterface:
3854     case Type::ObjCObjectPointer:
3855     case Type::Pipe:
3856       llvm_unreachable("type class is never variably-modified!");
3857     case Type::Adjusted:
3858       T = cast<AdjustedType>(Ty)->getOriginalType();
3859       break;
3860     case Type::Decayed:
3861       T = cast<DecayedType>(Ty)->getPointeeType();
3862       break;
3863     case Type::Pointer:
3864       T = cast<PointerType>(Ty)->getPointeeType();
3865       break;
3866     case Type::BlockPointer:
3867       T = cast<BlockPointerType>(Ty)->getPointeeType();
3868       break;
3869     case Type::LValueReference:
3870     case Type::RValueReference:
3871       T = cast<ReferenceType>(Ty)->getPointeeType();
3872       break;
3873     case Type::MemberPointer:
3874       T = cast<MemberPointerType>(Ty)->getPointeeType();
3875       break;
3876     case Type::ConstantArray:
3877     case Type::IncompleteArray:
3878       // Losing element qualification here is fine.
3879       T = cast<ArrayType>(Ty)->getElementType();
3880       break;
3881     case Type::VariableArray: {
3882       // Losing element qualification here is fine.
3883       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3884 
3885       // Unknown size indication requires no size computation.
3886       // Otherwise, evaluate and record it.
3887       if (auto Size = VAT->getSizeExpr()) {
3888         if (!CSI->isVLATypeCaptured(VAT)) {
3889           RecordDecl *CapRecord = nullptr;
3890           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3891             CapRecord = LSI->Lambda;
3892           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3893             CapRecord = CRSI->TheRecordDecl;
3894           }
3895           if (CapRecord) {
3896             auto ExprLoc = Size->getExprLoc();
3897             auto SizeType = Context.getSizeType();
3898             // Build the non-static data member.
3899             auto Field =
3900                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3901                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3902                                   /*BW*/ nullptr, /*Mutable*/ false,
3903                                   /*InitStyle*/ ICIS_NoInit);
3904             Field->setImplicit(true);
3905             Field->setAccess(AS_private);
3906             Field->setCapturedVLAType(VAT);
3907             CapRecord->addDecl(Field);
3908 
3909             CSI->addVLATypeCapture(ExprLoc, SizeType);
3910           }
3911         }
3912       }
3913       T = VAT->getElementType();
3914       break;
3915     }
3916     case Type::FunctionProto:
3917     case Type::FunctionNoProto:
3918       T = cast<FunctionType>(Ty)->getReturnType();
3919       break;
3920     case Type::Paren:
3921     case Type::TypeOf:
3922     case Type::UnaryTransform:
3923     case Type::Attributed:
3924     case Type::SubstTemplateTypeParm:
3925     case Type::PackExpansion:
3926       // Keep walking after single level desugaring.
3927       T = T.getSingleStepDesugaredType(Context);
3928       break;
3929     case Type::Typedef:
3930       T = cast<TypedefType>(Ty)->desugar();
3931       break;
3932     case Type::Decltype:
3933       T = cast<DecltypeType>(Ty)->desugar();
3934       break;
3935     case Type::Auto:
3936       T = cast<AutoType>(Ty)->getDeducedType();
3937       break;
3938     case Type::TypeOfExpr:
3939       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3940       break;
3941     case Type::Atomic:
3942       T = cast<AtomicType>(Ty)->getValueType();
3943       break;
3944     }
3945   } while (!T.isNull() && T->isVariablyModifiedType());
3946 }
3947 
3948 /// \brief Build a sizeof or alignof expression given a type operand.
3949 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)3950 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3951                                      SourceLocation OpLoc,
3952                                      UnaryExprOrTypeTrait ExprKind,
3953                                      SourceRange R) {
3954   if (!TInfo)
3955     return ExprError();
3956 
3957   QualType T = TInfo->getType();
3958 
3959   if (!T->isDependentType() &&
3960       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3961     return ExprError();
3962 
3963   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3964     if (auto *TT = T->getAs<TypedefType>()) {
3965       for (auto I = FunctionScopes.rbegin(),
3966                 E = std::prev(FunctionScopes.rend());
3967            I != E; ++I) {
3968         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3969         if (CSI == nullptr)
3970           break;
3971         DeclContext *DC = nullptr;
3972         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3973           DC = LSI->CallOperator;
3974         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3975           DC = CRSI->TheCapturedDecl;
3976         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3977           DC = BSI->TheDecl;
3978         if (DC) {
3979           if (DC->containsDecl(TT->getDecl()))
3980             break;
3981           captureVariablyModifiedType(Context, T, CSI);
3982         }
3983       }
3984     }
3985   }
3986 
3987   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3988   return new (Context) UnaryExprOrTypeTraitExpr(
3989       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3990 }
3991 
3992 /// \brief Build a sizeof or alignof expression given an expression
3993 /// operand.
3994 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)3995 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3996                                      UnaryExprOrTypeTrait ExprKind) {
3997   ExprResult PE = CheckPlaceholderExpr(E);
3998   if (PE.isInvalid())
3999     return ExprError();
4000 
4001   E = PE.get();
4002 
4003   // Verify that the operand is valid.
4004   bool isInvalid = false;
4005   if (E->isTypeDependent()) {
4006     // Delay type-checking for type-dependent expressions.
4007   } else if (ExprKind == UETT_AlignOf) {
4008     isInvalid = CheckAlignOfExpr(*this, E);
4009   } else if (ExprKind == UETT_VecStep) {
4010     isInvalid = CheckVecStepExpr(E);
4011   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4012       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4013       isInvalid = true;
4014   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4015     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4016     isInvalid = true;
4017   } else {
4018     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4019   }
4020 
4021   if (isInvalid)
4022     return ExprError();
4023 
4024   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4025     PE = TransformToPotentiallyEvaluated(E);
4026     if (PE.isInvalid()) return ExprError();
4027     E = PE.get();
4028   }
4029 
4030   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4031   return new (Context) UnaryExprOrTypeTraitExpr(
4032       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4033 }
4034 
4035 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4036 /// expr and the same for @c alignof and @c __alignof
4037 /// Note that the ArgRange is invalid if isType is false.
4038 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4039 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4040                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4041                                     void *TyOrEx, SourceRange ArgRange) {
4042   // If error parsing type, ignore.
4043   if (!TyOrEx) return ExprError();
4044 
4045   if (IsType) {
4046     TypeSourceInfo *TInfo;
4047     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4048     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4049   }
4050 
4051   Expr *ArgEx = (Expr *)TyOrEx;
4052   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4053   return Result;
4054 }
4055 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4056 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4057                                      bool IsReal) {
4058   if (V.get()->isTypeDependent())
4059     return S.Context.DependentTy;
4060 
4061   // _Real and _Imag are only l-values for normal l-values.
4062   if (V.get()->getObjectKind() != OK_Ordinary) {
4063     V = S.DefaultLvalueConversion(V.get());
4064     if (V.isInvalid())
4065       return QualType();
4066   }
4067 
4068   // These operators return the element type of a complex type.
4069   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4070     return CT->getElementType();
4071 
4072   // Otherwise they pass through real integer and floating point types here.
4073   if (V.get()->getType()->isArithmeticType())
4074     return V.get()->getType();
4075 
4076   // Test for placeholders.
4077   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4078   if (PR.isInvalid()) return QualType();
4079   if (PR.get() != V.get()) {
4080     V = PR;
4081     return CheckRealImagOperand(S, V, Loc, IsReal);
4082   }
4083 
4084   // Reject anything else.
4085   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4086     << (IsReal ? "__real" : "__imag");
4087   return QualType();
4088 }
4089 
4090 
4091 
4092 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4093 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4094                           tok::TokenKind Kind, Expr *Input) {
4095   UnaryOperatorKind Opc;
4096   switch (Kind) {
4097   default: llvm_unreachable("Unknown unary op!");
4098   case tok::plusplus:   Opc = UO_PostInc; break;
4099   case tok::minusminus: Opc = UO_PostDec; break;
4100   }
4101 
4102   // Since this might is a postfix expression, get rid of ParenListExprs.
4103   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4104   if (Result.isInvalid()) return ExprError();
4105   Input = Result.get();
4106 
4107   return BuildUnaryOp(S, OpLoc, Opc, Input);
4108 }
4109 
4110 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4111 ///
4112 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4113 static bool checkArithmeticOnObjCPointer(Sema &S,
4114                                          SourceLocation opLoc,
4115                                          Expr *op) {
4116   assert(op->getType()->isObjCObjectPointerType());
4117   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4118       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4119     return false;
4120 
4121   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4122     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4123     << op->getSourceRange();
4124   return true;
4125 }
4126 
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4127 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4128   auto *BaseNoParens = Base->IgnoreParens();
4129   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4130     return MSProp->getPropertyDecl()->getType()->isArrayType();
4131   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4132 }
4133 
4134 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4135 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4136                               Expr *idx, SourceLocation rbLoc) {
4137   if (base && !base->getType().isNull() &&
4138       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4139     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4140                                     /*Length=*/nullptr, rbLoc);
4141 
4142   // Since this might be a postfix expression, get rid of ParenListExprs.
4143   if (isa<ParenListExpr>(base)) {
4144     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4145     if (result.isInvalid()) return ExprError();
4146     base = result.get();
4147   }
4148 
4149   // Handle any non-overload placeholder types in the base and index
4150   // expressions.  We can't handle overloads here because the other
4151   // operand might be an overloadable type, in which case the overload
4152   // resolution for the operator overload should get the first crack
4153   // at the overload.
4154   bool IsMSPropertySubscript = false;
4155   if (base->getType()->isNonOverloadPlaceholderType()) {
4156     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4157     if (!IsMSPropertySubscript) {
4158       ExprResult result = CheckPlaceholderExpr(base);
4159       if (result.isInvalid())
4160         return ExprError();
4161       base = result.get();
4162     }
4163   }
4164   if (idx->getType()->isNonOverloadPlaceholderType()) {
4165     ExprResult result = CheckPlaceholderExpr(idx);
4166     if (result.isInvalid()) return ExprError();
4167     idx = result.get();
4168   }
4169 
4170   // Build an unanalyzed expression if either operand is type-dependent.
4171   if (getLangOpts().CPlusPlus &&
4172       (base->isTypeDependent() || idx->isTypeDependent())) {
4173     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4174                                             VK_LValue, OK_Ordinary, rbLoc);
4175   }
4176 
4177   // MSDN, property (C++)
4178   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4179   // This attribute can also be used in the declaration of an empty array in a
4180   // class or structure definition. For example:
4181   // __declspec(property(get=GetX, put=PutX)) int x[];
4182   // The above statement indicates that x[] can be used with one or more array
4183   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4184   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4185   if (IsMSPropertySubscript) {
4186     // Build MS property subscript expression if base is MS property reference
4187     // or MS property subscript.
4188     return new (Context) MSPropertySubscriptExpr(
4189         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4190   }
4191 
4192   // Use C++ overloaded-operator rules if either operand has record
4193   // type.  The spec says to do this if either type is *overloadable*,
4194   // but enum types can't declare subscript operators or conversion
4195   // operators, so there's nothing interesting for overload resolution
4196   // to do if there aren't any record types involved.
4197   //
4198   // ObjC pointers have their own subscripting logic that is not tied
4199   // to overload resolution and so should not take this path.
4200   if (getLangOpts().CPlusPlus &&
4201       (base->getType()->isRecordType() ||
4202        (!base->getType()->isObjCObjectPointerType() &&
4203         idx->getType()->isRecordType()))) {
4204     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4205   }
4206 
4207   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4208 }
4209 
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLoc,Expr * Length,SourceLocation RBLoc)4210 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4211                                           Expr *LowerBound,
4212                                           SourceLocation ColonLoc, Expr *Length,
4213                                           SourceLocation RBLoc) {
4214   if (Base->getType()->isPlaceholderType() &&
4215       !Base->getType()->isSpecificPlaceholderType(
4216           BuiltinType::OMPArraySection)) {
4217     ExprResult Result = CheckPlaceholderExpr(Base);
4218     if (Result.isInvalid())
4219       return ExprError();
4220     Base = Result.get();
4221   }
4222   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4223     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4224     if (Result.isInvalid())
4225       return ExprError();
4226     Result = DefaultLvalueConversion(Result.get());
4227     if (Result.isInvalid())
4228       return ExprError();
4229     LowerBound = Result.get();
4230   }
4231   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4232     ExprResult Result = CheckPlaceholderExpr(Length);
4233     if (Result.isInvalid())
4234       return ExprError();
4235     Result = DefaultLvalueConversion(Result.get());
4236     if (Result.isInvalid())
4237       return ExprError();
4238     Length = Result.get();
4239   }
4240 
4241   // Build an unanalyzed expression if either operand is type-dependent.
4242   if (Base->isTypeDependent() ||
4243       (LowerBound &&
4244        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4245       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4246     return new (Context)
4247         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4248                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4249   }
4250 
4251   // Perform default conversions.
4252   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4253   QualType ResultTy;
4254   if (OriginalTy->isAnyPointerType()) {
4255     ResultTy = OriginalTy->getPointeeType();
4256   } else if (OriginalTy->isArrayType()) {
4257     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4258   } else {
4259     return ExprError(
4260         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4261         << Base->getSourceRange());
4262   }
4263   // C99 6.5.2.1p1
4264   if (LowerBound) {
4265     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4266                                                       LowerBound);
4267     if (Res.isInvalid())
4268       return ExprError(Diag(LowerBound->getExprLoc(),
4269                             diag::err_omp_typecheck_section_not_integer)
4270                        << 0 << LowerBound->getSourceRange());
4271     LowerBound = Res.get();
4272 
4273     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4274         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4275       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4276           << 0 << LowerBound->getSourceRange();
4277   }
4278   if (Length) {
4279     auto Res =
4280         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4281     if (Res.isInvalid())
4282       return ExprError(Diag(Length->getExprLoc(),
4283                             diag::err_omp_typecheck_section_not_integer)
4284                        << 1 << Length->getSourceRange());
4285     Length = Res.get();
4286 
4287     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4288         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4289       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4290           << 1 << Length->getSourceRange();
4291   }
4292 
4293   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4294   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4295   // type. Note that functions are not objects, and that (in C99 parlance)
4296   // incomplete types are not object types.
4297   if (ResultTy->isFunctionType()) {
4298     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4299         << ResultTy << Base->getSourceRange();
4300     return ExprError();
4301   }
4302 
4303   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4304                           diag::err_omp_section_incomplete_type, Base))
4305     return ExprError();
4306 
4307   if (LowerBound) {
4308     llvm::APSInt LowerBoundValue;
4309     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4310       // OpenMP 4.0, [2.4 Array Sections]
4311       // The lower-bound and length must evaluate to non-negative integers.
4312       if (LowerBoundValue.isNegative()) {
4313         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4314             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4315             << LowerBound->getSourceRange();
4316         return ExprError();
4317       }
4318     }
4319   }
4320 
4321   if (Length) {
4322     llvm::APSInt LengthValue;
4323     if (Length->EvaluateAsInt(LengthValue, Context)) {
4324       // OpenMP 4.0, [2.4 Array Sections]
4325       // The lower-bound and length must evaluate to non-negative integers.
4326       if (LengthValue.isNegative()) {
4327         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4328             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4329             << Length->getSourceRange();
4330         return ExprError();
4331       }
4332     }
4333   } else if (ColonLoc.isValid() &&
4334              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4335                                       !OriginalTy->isVariableArrayType()))) {
4336     // OpenMP 4.0, [2.4 Array Sections]
4337     // When the size of the array dimension is not known, the length must be
4338     // specified explicitly.
4339     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4340         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4341     return ExprError();
4342   }
4343 
4344   if (!Base->getType()->isSpecificPlaceholderType(
4345           BuiltinType::OMPArraySection)) {
4346     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4347     if (Result.isInvalid())
4348       return ExprError();
4349     Base = Result.get();
4350   }
4351   return new (Context)
4352       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4353                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4354 }
4355 
4356 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)4357 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4358                                       Expr *Idx, SourceLocation RLoc) {
4359   Expr *LHSExp = Base;
4360   Expr *RHSExp = Idx;
4361 
4362   // Perform default conversions.
4363   if (!LHSExp->getType()->getAs<VectorType>()) {
4364     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4365     if (Result.isInvalid())
4366       return ExprError();
4367     LHSExp = Result.get();
4368   }
4369   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4370   if (Result.isInvalid())
4371     return ExprError();
4372   RHSExp = Result.get();
4373 
4374   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4375   ExprValueKind VK = VK_LValue;
4376   ExprObjectKind OK = OK_Ordinary;
4377 
4378   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4379   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4380   // in the subscript position. As a result, we need to derive the array base
4381   // and index from the expression types.
4382   Expr *BaseExpr, *IndexExpr;
4383   QualType ResultType;
4384   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4385     BaseExpr = LHSExp;
4386     IndexExpr = RHSExp;
4387     ResultType = Context.DependentTy;
4388   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4389     BaseExpr = LHSExp;
4390     IndexExpr = RHSExp;
4391     ResultType = PTy->getPointeeType();
4392   } else if (const ObjCObjectPointerType *PTy =
4393                LHSTy->getAs<ObjCObjectPointerType>()) {
4394     BaseExpr = LHSExp;
4395     IndexExpr = RHSExp;
4396 
4397     // Use custom logic if this should be the pseudo-object subscript
4398     // expression.
4399     if (!LangOpts.isSubscriptPointerArithmetic())
4400       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4401                                           nullptr);
4402 
4403     ResultType = PTy->getPointeeType();
4404   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4405      // Handle the uncommon case of "123[Ptr]".
4406     BaseExpr = RHSExp;
4407     IndexExpr = LHSExp;
4408     ResultType = PTy->getPointeeType();
4409   } else if (const ObjCObjectPointerType *PTy =
4410                RHSTy->getAs<ObjCObjectPointerType>()) {
4411      // Handle the uncommon case of "123[Ptr]".
4412     BaseExpr = RHSExp;
4413     IndexExpr = LHSExp;
4414     ResultType = PTy->getPointeeType();
4415     if (!LangOpts.isSubscriptPointerArithmetic()) {
4416       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4417         << ResultType << BaseExpr->getSourceRange();
4418       return ExprError();
4419     }
4420   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4421     BaseExpr = LHSExp;    // vectors: V[123]
4422     IndexExpr = RHSExp;
4423     VK = LHSExp->getValueKind();
4424     if (VK != VK_RValue)
4425       OK = OK_VectorComponent;
4426 
4427     // FIXME: need to deal with const...
4428     ResultType = VTy->getElementType();
4429   } else if (LHSTy->isArrayType()) {
4430     // If we see an array that wasn't promoted by
4431     // DefaultFunctionArrayLvalueConversion, it must be an array that
4432     // wasn't promoted because of the C90 rule that doesn't
4433     // allow promoting non-lvalue arrays.  Warn, then
4434     // force the promotion here.
4435     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4436         LHSExp->getSourceRange();
4437     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4438                                CK_ArrayToPointerDecay).get();
4439     LHSTy = LHSExp->getType();
4440 
4441     BaseExpr = LHSExp;
4442     IndexExpr = RHSExp;
4443     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4444   } else if (RHSTy->isArrayType()) {
4445     // Same as previous, except for 123[f().a] case
4446     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4447         RHSExp->getSourceRange();
4448     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4449                                CK_ArrayToPointerDecay).get();
4450     RHSTy = RHSExp->getType();
4451 
4452     BaseExpr = RHSExp;
4453     IndexExpr = LHSExp;
4454     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4455   } else {
4456     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4457        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4458   }
4459   // C99 6.5.2.1p1
4460   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4461     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4462                      << IndexExpr->getSourceRange());
4463 
4464   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4465        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4466          && !IndexExpr->isTypeDependent())
4467     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4468 
4469   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4470   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4471   // type. Note that Functions are not objects, and that (in C99 parlance)
4472   // incomplete types are not object types.
4473   if (ResultType->isFunctionType()) {
4474     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4475       << ResultType << BaseExpr->getSourceRange();
4476     return ExprError();
4477   }
4478 
4479   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4480     // GNU extension: subscripting on pointer to void
4481     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4482       << BaseExpr->getSourceRange();
4483 
4484     // C forbids expressions of unqualified void type from being l-values.
4485     // See IsCForbiddenLValueType.
4486     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4487   } else if (!ResultType->isDependentType() &&
4488       RequireCompleteType(LLoc, ResultType,
4489                           diag::err_subscript_incomplete_type, BaseExpr))
4490     return ExprError();
4491 
4492   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4493          !ResultType.isCForbiddenLValueType());
4494 
4495   return new (Context)
4496       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4497 }
4498 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)4499 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4500                                         FunctionDecl *FD,
4501                                         ParmVarDecl *Param) {
4502   if (Param->hasUnparsedDefaultArg()) {
4503     Diag(CallLoc,
4504          diag::err_use_of_default_argument_to_function_declared_later) <<
4505       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4506     Diag(UnparsedDefaultArgLocs[Param],
4507          diag::note_default_argument_declared_here);
4508     return ExprError();
4509   }
4510 
4511   if (Param->hasUninstantiatedDefaultArg()) {
4512     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4513 
4514     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4515                                                  Param);
4516 
4517     // Instantiate the expression.
4518     MultiLevelTemplateArgumentList MutiLevelArgList
4519       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4520 
4521     InstantiatingTemplate Inst(*this, CallLoc, Param,
4522                                MutiLevelArgList.getInnermost());
4523     if (Inst.isInvalid())
4524       return ExprError();
4525 
4526     ExprResult Result;
4527     {
4528       // C++ [dcl.fct.default]p5:
4529       //   The names in the [default argument] expression are bound, and
4530       //   the semantic constraints are checked, at the point where the
4531       //   default argument expression appears.
4532       ContextRAII SavedContext(*this, FD);
4533       LocalInstantiationScope Local(*this);
4534       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4535     }
4536     if (Result.isInvalid())
4537       return ExprError();
4538 
4539     // Check the expression as an initializer for the parameter.
4540     InitializedEntity Entity
4541       = InitializedEntity::InitializeParameter(Context, Param);
4542     InitializationKind Kind
4543       = InitializationKind::CreateCopy(Param->getLocation(),
4544              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4545     Expr *ResultE = Result.getAs<Expr>();
4546 
4547     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4548     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4549     if (Result.isInvalid())
4550       return ExprError();
4551 
4552     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4553                                  Param->getOuterLocStart());
4554     if (Result.isInvalid())
4555       return ExprError();
4556 
4557     // Remember the instantiated default argument.
4558     Param->setDefaultArg(Result.getAs<Expr>());
4559     if (ASTMutationListener *L = getASTMutationListener()) {
4560       L->DefaultArgumentInstantiated(Param);
4561     }
4562   }
4563 
4564   // If the default argument expression is not set yet, we are building it now.
4565   if (!Param->hasInit()) {
4566     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4567     Param->setInvalidDecl();
4568     return ExprError();
4569   }
4570 
4571   // If the default expression creates temporaries, we need to
4572   // push them to the current stack of expression temporaries so they'll
4573   // be properly destroyed.
4574   // FIXME: We should really be rebuilding the default argument with new
4575   // bound temporaries; see the comment in PR5810.
4576   // We don't need to do that with block decls, though, because
4577   // blocks in default argument expression can never capture anything.
4578   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4579     // Set the "needs cleanups" bit regardless of whether there are
4580     // any explicit objects.
4581     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4582 
4583     // Append all the objects to the cleanup list.  Right now, this
4584     // should always be a no-op, because blocks in default argument
4585     // expressions should never be able to capture anything.
4586     assert(!Init->getNumObjects() &&
4587            "default argument expression has capturing blocks?");
4588   }
4589 
4590   // We already type-checked the argument, so we know it works.
4591   // Just mark all of the declarations in this potentially-evaluated expression
4592   // as being "referenced".
4593   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4594                                    /*SkipLocalVariables=*/true);
4595   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4596 }
4597 
4598 
4599 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)4600 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4601                           Expr *Fn) {
4602   if (Proto && Proto->isVariadic()) {
4603     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4604       return VariadicConstructor;
4605     else if (Fn && Fn->getType()->isBlockPointerType())
4606       return VariadicBlock;
4607     else if (FDecl) {
4608       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4609         if (Method->isInstance())
4610           return VariadicMethod;
4611     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4612       return VariadicMethod;
4613     return VariadicFunction;
4614   }
4615   return VariadicDoesNotApply;
4616 }
4617 
4618 namespace {
4619 class FunctionCallCCC : public FunctionCallFilterCCC {
4620 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)4621   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4622                   unsigned NumArgs, MemberExpr *ME)
4623       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4624         FunctionName(FuncName) {}
4625 
ValidateCandidate(const TypoCorrection & candidate)4626   bool ValidateCandidate(const TypoCorrection &candidate) override {
4627     if (!candidate.getCorrectionSpecifier() ||
4628         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4629       return false;
4630     }
4631 
4632     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4633   }
4634 
4635 private:
4636   const IdentifierInfo *const FunctionName;
4637 };
4638 }
4639 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)4640 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4641                                                FunctionDecl *FDecl,
4642                                                ArrayRef<Expr *> Args) {
4643   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4644   DeclarationName FuncName = FDecl->getDeclName();
4645   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4646 
4647   if (TypoCorrection Corrected = S.CorrectTypo(
4648           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4649           S.getScopeForContext(S.CurContext), nullptr,
4650           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4651                                              Args.size(), ME),
4652           Sema::CTK_ErrorRecovery)) {
4653     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4654       if (Corrected.isOverloaded()) {
4655         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4656         OverloadCandidateSet::iterator Best;
4657         for (NamedDecl *CD : Corrected) {
4658           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4659             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4660                                    OCS);
4661         }
4662         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4663         case OR_Success:
4664           ND = Best->FoundDecl;
4665           Corrected.setCorrectionDecl(ND);
4666           break;
4667         default:
4668           break;
4669         }
4670       }
4671       ND = ND->getUnderlyingDecl();
4672       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4673         return Corrected;
4674     }
4675   }
4676   return TypoCorrection();
4677 }
4678 
4679 /// ConvertArgumentsForCall - Converts the arguments specified in
4680 /// Args/NumArgs to the parameter types of the function FDecl with
4681 /// function prototype Proto. Call is the call expression itself, and
4682 /// Fn is the function expression. For a C++ member function, this
4683 /// routine does not attempt to convert the object argument. Returns
4684 /// true if the call is ill-formed.
4685 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)4686 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4687                               FunctionDecl *FDecl,
4688                               const FunctionProtoType *Proto,
4689                               ArrayRef<Expr *> Args,
4690                               SourceLocation RParenLoc,
4691                               bool IsExecConfig) {
4692   // Bail out early if calling a builtin with custom typechecking.
4693   if (FDecl)
4694     if (unsigned ID = FDecl->getBuiltinID())
4695       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4696         return false;
4697 
4698   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4699   // assignment, to the types of the corresponding parameter, ...
4700   unsigned NumParams = Proto->getNumParams();
4701   bool Invalid = false;
4702   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4703   unsigned FnKind = Fn->getType()->isBlockPointerType()
4704                        ? 1 /* block */
4705                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4706                                        : 0 /* function */);
4707 
4708   // If too few arguments are available (and we don't have default
4709   // arguments for the remaining parameters), don't make the call.
4710   if (Args.size() < NumParams) {
4711     if (Args.size() < MinArgs) {
4712       TypoCorrection TC;
4713       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4714         unsigned diag_id =
4715             MinArgs == NumParams && !Proto->isVariadic()
4716                 ? diag::err_typecheck_call_too_few_args_suggest
4717                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4718         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4719                                         << static_cast<unsigned>(Args.size())
4720                                         << TC.getCorrectionRange());
4721       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4722         Diag(RParenLoc,
4723              MinArgs == NumParams && !Proto->isVariadic()
4724                  ? diag::err_typecheck_call_too_few_args_one
4725                  : diag::err_typecheck_call_too_few_args_at_least_one)
4726             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4727       else
4728         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4729                             ? diag::err_typecheck_call_too_few_args
4730                             : diag::err_typecheck_call_too_few_args_at_least)
4731             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4732             << Fn->getSourceRange();
4733 
4734       // Emit the location of the prototype.
4735       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4736         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4737           << FDecl;
4738 
4739       return true;
4740     }
4741     Call->setNumArgs(Context, NumParams);
4742   }
4743 
4744   // If too many are passed and not variadic, error on the extras and drop
4745   // them.
4746   if (Args.size() > NumParams) {
4747     if (!Proto->isVariadic()) {
4748       TypoCorrection TC;
4749       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4750         unsigned diag_id =
4751             MinArgs == NumParams && !Proto->isVariadic()
4752                 ? diag::err_typecheck_call_too_many_args_suggest
4753                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4754         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4755                                         << static_cast<unsigned>(Args.size())
4756                                         << TC.getCorrectionRange());
4757       } else if (NumParams == 1 && FDecl &&
4758                  FDecl->getParamDecl(0)->getDeclName())
4759         Diag(Args[NumParams]->getLocStart(),
4760              MinArgs == NumParams
4761                  ? diag::err_typecheck_call_too_many_args_one
4762                  : diag::err_typecheck_call_too_many_args_at_most_one)
4763             << FnKind << FDecl->getParamDecl(0)
4764             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4765             << SourceRange(Args[NumParams]->getLocStart(),
4766                            Args.back()->getLocEnd());
4767       else
4768         Diag(Args[NumParams]->getLocStart(),
4769              MinArgs == NumParams
4770                  ? diag::err_typecheck_call_too_many_args
4771                  : diag::err_typecheck_call_too_many_args_at_most)
4772             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4773             << Fn->getSourceRange()
4774             << SourceRange(Args[NumParams]->getLocStart(),
4775                            Args.back()->getLocEnd());
4776 
4777       // Emit the location of the prototype.
4778       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4779         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4780           << FDecl;
4781 
4782       // This deletes the extra arguments.
4783       Call->setNumArgs(Context, NumParams);
4784       return true;
4785     }
4786   }
4787   SmallVector<Expr *, 8> AllArgs;
4788   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4789 
4790   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4791                                    Proto, 0, Args, AllArgs, CallType);
4792   if (Invalid)
4793     return true;
4794   unsigned TotalNumArgs = AllArgs.size();
4795   for (unsigned i = 0; i < TotalNumArgs; ++i)
4796     Call->setArg(i, AllArgs[i]);
4797 
4798   return false;
4799 }
4800 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)4801 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4802                                   const FunctionProtoType *Proto,
4803                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4804                                   SmallVectorImpl<Expr *> &AllArgs,
4805                                   VariadicCallType CallType, bool AllowExplicit,
4806                                   bool IsListInitialization) {
4807   unsigned NumParams = Proto->getNumParams();
4808   bool Invalid = false;
4809   size_t ArgIx = 0;
4810   // Continue to check argument types (even if we have too few/many args).
4811   for (unsigned i = FirstParam; i < NumParams; i++) {
4812     QualType ProtoArgType = Proto->getParamType(i);
4813 
4814     Expr *Arg;
4815     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4816     if (ArgIx < Args.size()) {
4817       Arg = Args[ArgIx++];
4818 
4819       if (RequireCompleteType(Arg->getLocStart(),
4820                               ProtoArgType,
4821                               diag::err_call_incomplete_argument, Arg))
4822         return true;
4823 
4824       // Strip the unbridged-cast placeholder expression off, if applicable.
4825       bool CFAudited = false;
4826       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4827           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4828           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4829         Arg = stripARCUnbridgedCast(Arg);
4830       else if (getLangOpts().ObjCAutoRefCount &&
4831                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4832                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4833         CFAudited = true;
4834 
4835       InitializedEntity Entity =
4836           Param ? InitializedEntity::InitializeParameter(Context, Param,
4837                                                          ProtoArgType)
4838                 : InitializedEntity::InitializeParameter(
4839                       Context, ProtoArgType, Proto->isParamConsumed(i));
4840 
4841       // Remember that parameter belongs to a CF audited API.
4842       if (CFAudited)
4843         Entity.setParameterCFAudited();
4844 
4845       ExprResult ArgE = PerformCopyInitialization(
4846           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4847       if (ArgE.isInvalid())
4848         return true;
4849 
4850       Arg = ArgE.getAs<Expr>();
4851     } else {
4852       assert(Param && "can't use default arguments without a known callee");
4853 
4854       ExprResult ArgExpr =
4855         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4856       if (ArgExpr.isInvalid())
4857         return true;
4858 
4859       Arg = ArgExpr.getAs<Expr>();
4860     }
4861 
4862     // Check for array bounds violations for each argument to the call. This
4863     // check only triggers warnings when the argument isn't a more complex Expr
4864     // with its own checking, such as a BinaryOperator.
4865     CheckArrayAccess(Arg);
4866 
4867     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4868     CheckStaticArrayArgument(CallLoc, Param, Arg);
4869 
4870     AllArgs.push_back(Arg);
4871   }
4872 
4873   // If this is a variadic call, handle args passed through "...".
4874   if (CallType != VariadicDoesNotApply) {
4875     // Assume that extern "C" functions with variadic arguments that
4876     // return __unknown_anytype aren't *really* variadic.
4877     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4878         FDecl->isExternC()) {
4879       for (Expr *A : Args.slice(ArgIx)) {
4880         QualType paramType; // ignored
4881         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4882         Invalid |= arg.isInvalid();
4883         AllArgs.push_back(arg.get());
4884       }
4885 
4886     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4887     } else {
4888       for (Expr *A : Args.slice(ArgIx)) {
4889         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4890         Invalid |= Arg.isInvalid();
4891         AllArgs.push_back(Arg.get());
4892       }
4893     }
4894 
4895     // Check for array bounds violations.
4896     for (Expr *A : Args.slice(ArgIx))
4897       CheckArrayAccess(A);
4898   }
4899   return Invalid;
4900 }
4901 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)4902 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4903   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4904   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4905     TL = DTL.getOriginalLoc();
4906   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4907     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4908       << ATL.getLocalSourceRange();
4909 }
4910 
4911 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4912 /// array parameter, check that it is non-null, and that if it is formed by
4913 /// array-to-pointer decay, the underlying array is sufficiently large.
4914 ///
4915 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4916 /// array type derivation, then for each call to the function, the value of the
4917 /// corresponding actual argument shall provide access to the first element of
4918 /// an array with at least as many elements as specified by the size expression.
4919 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)4920 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4921                                ParmVarDecl *Param,
4922                                const Expr *ArgExpr) {
4923   // Static array parameters are not supported in C++.
4924   if (!Param || getLangOpts().CPlusPlus)
4925     return;
4926 
4927   QualType OrigTy = Param->getOriginalType();
4928 
4929   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4930   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4931     return;
4932 
4933   if (ArgExpr->isNullPointerConstant(Context,
4934                                      Expr::NPC_NeverValueDependent)) {
4935     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4936     DiagnoseCalleeStaticArrayParam(*this, Param);
4937     return;
4938   }
4939 
4940   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4941   if (!CAT)
4942     return;
4943 
4944   const ConstantArrayType *ArgCAT =
4945     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4946   if (!ArgCAT)
4947     return;
4948 
4949   if (ArgCAT->getSize().ult(CAT->getSize())) {
4950     Diag(CallLoc, diag::warn_static_array_too_small)
4951       << ArgExpr->getSourceRange()
4952       << (unsigned) ArgCAT->getSize().getZExtValue()
4953       << (unsigned) CAT->getSize().getZExtValue();
4954     DiagnoseCalleeStaticArrayParam(*this, Param);
4955   }
4956 }
4957 
4958 /// Given a function expression of unknown-any type, try to rebuild it
4959 /// to have a function type.
4960 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4961 
4962 /// Is the given type a placeholder that we need to lower out
4963 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)4964 static bool isPlaceholderToRemoveAsArg(QualType type) {
4965   // Placeholders are never sugared.
4966   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4967   if (!placeholder) return false;
4968 
4969   switch (placeholder->getKind()) {
4970   // Ignore all the non-placeholder types.
4971 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4972   case BuiltinType::Id:
4973 #include "clang/Basic/OpenCLImageTypes.def"
4974 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4975 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4976 #include "clang/AST/BuiltinTypes.def"
4977     return false;
4978 
4979   // We cannot lower out overload sets; they might validly be resolved
4980   // by the call machinery.
4981   case BuiltinType::Overload:
4982     return false;
4983 
4984   // Unbridged casts in ARC can be handled in some call positions and
4985   // should be left in place.
4986   case BuiltinType::ARCUnbridgedCast:
4987     return false;
4988 
4989   // Pseudo-objects should be converted as soon as possible.
4990   case BuiltinType::PseudoObject:
4991     return true;
4992 
4993   // The debugger mode could theoretically but currently does not try
4994   // to resolve unknown-typed arguments based on known parameter types.
4995   case BuiltinType::UnknownAny:
4996     return true;
4997 
4998   // These are always invalid as call arguments and should be reported.
4999   case BuiltinType::BoundMember:
5000   case BuiltinType::BuiltinFn:
5001   case BuiltinType::OMPArraySection:
5002     return true;
5003 
5004   }
5005   llvm_unreachable("bad builtin type kind");
5006 }
5007 
5008 /// Check an argument list for placeholders that we won't try to
5009 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)5010 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5011   // Apply this processing to all the arguments at once instead of
5012   // dying at the first failure.
5013   bool hasInvalid = false;
5014   for (size_t i = 0, e = args.size(); i != e; i++) {
5015     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5016       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5017       if (result.isInvalid()) hasInvalid = true;
5018       else args[i] = result.get();
5019     } else if (hasInvalid) {
5020       (void)S.CorrectDelayedTyposInExpr(args[i]);
5021     }
5022   }
5023   return hasInvalid;
5024 }
5025 
5026 /// If a builtin function has a pointer argument with no explicit address
5027 /// space, then it should be able to accept a pointer to any address
5028 /// space as input.  In order to do this, we need to replace the
5029 /// standard builtin declaration with one that uses the same address space
5030 /// as the call.
5031 ///
5032 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5033 ///                  it does not contain any pointer arguments without
5034 ///                  an address space qualifer.  Otherwise the rewritten
5035 ///                  FunctionDecl is returned.
5036 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,const FunctionDecl * FDecl,MultiExprArg ArgExprs)5037 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5038                                                 const FunctionDecl *FDecl,
5039                                                 MultiExprArg ArgExprs) {
5040 
5041   QualType DeclType = FDecl->getType();
5042   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5043 
5044   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5045       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5046     return nullptr;
5047 
5048   bool NeedsNewDecl = false;
5049   unsigned i = 0;
5050   SmallVector<QualType, 8> OverloadParams;
5051 
5052   for (QualType ParamType : FT->param_types()) {
5053 
5054     // Convert array arguments to pointer to simplify type lookup.
5055     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5056     QualType ArgType = Arg->getType();
5057     if (!ParamType->isPointerType() ||
5058         ParamType.getQualifiers().hasAddressSpace() ||
5059         !ArgType->isPointerType() ||
5060         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5061       OverloadParams.push_back(ParamType);
5062       continue;
5063     }
5064 
5065     NeedsNewDecl = true;
5066     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5067 
5068     QualType PointeeType = ParamType->getPointeeType();
5069     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5070     OverloadParams.push_back(Context.getPointerType(PointeeType));
5071   }
5072 
5073   if (!NeedsNewDecl)
5074     return nullptr;
5075 
5076   FunctionProtoType::ExtProtoInfo EPI;
5077   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5078                                                 OverloadParams, EPI);
5079   DeclContext *Parent = Context.getTranslationUnitDecl();
5080   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5081                                                     FDecl->getLocation(),
5082                                                     FDecl->getLocation(),
5083                                                     FDecl->getIdentifier(),
5084                                                     OverloadTy,
5085                                                     /*TInfo=*/nullptr,
5086                                                     SC_Extern, false,
5087                                                     /*hasPrototype=*/true);
5088   SmallVector<ParmVarDecl*, 16> Params;
5089   FT = cast<FunctionProtoType>(OverloadTy);
5090   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5091     QualType ParamType = FT->getParamType(i);
5092     ParmVarDecl *Parm =
5093         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5094                                 SourceLocation(), nullptr, ParamType,
5095                                 /*TInfo=*/nullptr, SC_None, nullptr);
5096     Parm->setScopeInfo(0, i);
5097     Params.push_back(Parm);
5098   }
5099   OverloadDecl->setParams(Params);
5100   return OverloadDecl;
5101 }
5102 
isNumberOfArgsValidForCall(Sema & S,const FunctionDecl * Callee,std::size_t NumArgs)5103 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5104                                        std::size_t NumArgs) {
5105   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5106                          /*PartialOverloading=*/false))
5107     return Callee->isVariadic();
5108   return Callee->getMinRequiredArguments() <= NumArgs;
5109 }
5110 
5111 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5112 /// This provides the location of the left/right parens and a list of comma
5113 /// locations.
5114 ExprResult
ActOnCallExpr(Scope * S,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)5115 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5116                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5117                     Expr *ExecConfig, bool IsExecConfig) {
5118   // Since this might be a postfix expression, get rid of ParenListExprs.
5119   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5120   if (Result.isInvalid()) return ExprError();
5121   Fn = Result.get();
5122 
5123   if (checkArgsForPlaceholders(*this, ArgExprs))
5124     return ExprError();
5125 
5126   if (getLangOpts().CPlusPlus) {
5127     // If this is a pseudo-destructor expression, build the call immediately.
5128     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5129       if (!ArgExprs.empty()) {
5130         // Pseudo-destructor calls should not have any arguments.
5131         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5132           << FixItHint::CreateRemoval(
5133                                     SourceRange(ArgExprs.front()->getLocStart(),
5134                                                 ArgExprs.back()->getLocEnd()));
5135       }
5136 
5137       return new (Context)
5138           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5139     }
5140     if (Fn->getType() == Context.PseudoObjectTy) {
5141       ExprResult result = CheckPlaceholderExpr(Fn);
5142       if (result.isInvalid()) return ExprError();
5143       Fn = result.get();
5144     }
5145 
5146     // Determine whether this is a dependent call inside a C++ template,
5147     // in which case we won't do any semantic analysis now.
5148     bool Dependent = false;
5149     if (Fn->isTypeDependent())
5150       Dependent = true;
5151     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5152       Dependent = true;
5153 
5154     if (Dependent) {
5155       if (ExecConfig) {
5156         return new (Context) CUDAKernelCallExpr(
5157             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5158             Context.DependentTy, VK_RValue, RParenLoc);
5159       } else {
5160         return new (Context) CallExpr(
5161             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5162       }
5163     }
5164 
5165     // Determine whether this is a call to an object (C++ [over.call.object]).
5166     if (Fn->getType()->isRecordType())
5167       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5168                                           RParenLoc);
5169 
5170     if (Fn->getType() == Context.UnknownAnyTy) {
5171       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5172       if (result.isInvalid()) return ExprError();
5173       Fn = result.get();
5174     }
5175 
5176     if (Fn->getType() == Context.BoundMemberTy) {
5177       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5178     }
5179   }
5180 
5181   // Check for overloaded calls.  This can happen even in C due to extensions.
5182   if (Fn->getType() == Context.OverloadTy) {
5183     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5184 
5185     // We aren't supposed to apply this logic for if there's an '&' involved.
5186     if (!find.HasFormOfMemberPointer) {
5187       OverloadExpr *ovl = find.Expression;
5188       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5189         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5190                                        RParenLoc, ExecConfig,
5191                                        /*AllowTypoCorrection=*/true,
5192                                        find.IsAddressOfOperand);
5193       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5194     }
5195   }
5196 
5197   // If we're directly calling a function, get the appropriate declaration.
5198   if (Fn->getType() == Context.UnknownAnyTy) {
5199     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5200     if (result.isInvalid()) return ExprError();
5201     Fn = result.get();
5202   }
5203 
5204   Expr *NakedFn = Fn->IgnoreParens();
5205 
5206   bool CallingNDeclIndirectly = false;
5207   NamedDecl *NDecl = nullptr;
5208   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5209     if (UnOp->getOpcode() == UO_AddrOf) {
5210       CallingNDeclIndirectly = true;
5211       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5212     }
5213   }
5214 
5215   if (isa<DeclRefExpr>(NakedFn)) {
5216     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5217 
5218     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5219     if (FDecl && FDecl->getBuiltinID()) {
5220       // Rewrite the function decl for this builtin by replacing parameters
5221       // with no explicit address space with the address space of the arguments
5222       // in ArgExprs.
5223       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5224         NDecl = FDecl;
5225         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5226                            SourceLocation(), FDecl, false,
5227                            SourceLocation(), FDecl->getType(),
5228                            Fn->getValueKind(), FDecl);
5229       }
5230     }
5231   } else if (isa<MemberExpr>(NakedFn))
5232     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5233 
5234   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5235     if (CallingNDeclIndirectly &&
5236         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5237                                            Fn->getLocStart()))
5238       return ExprError();
5239 
5240     // CheckEnableIf assumes that the we're passing in a sane number of args for
5241     // FD, but that doesn't always hold true here. This is because, in some
5242     // cases, we'll emit a diag about an ill-formed function call, but then
5243     // we'll continue on as if the function call wasn't ill-formed. So, if the
5244     // number of args looks incorrect, don't do enable_if checks; we should've
5245     // already emitted an error about the bad call.
5246     if (FD->hasAttr<EnableIfAttr>() &&
5247         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5248       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5249         Diag(Fn->getLocStart(),
5250              isa<CXXMethodDecl>(FD) ?
5251                  diag::err_ovl_no_viable_member_function_in_call :
5252                  diag::err_ovl_no_viable_function_in_call)
5253           << FD << FD->getSourceRange();
5254         Diag(FD->getLocation(),
5255              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5256             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5257       }
5258     }
5259   }
5260 
5261   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5262                                ExecConfig, IsExecConfig);
5263 }
5264 
5265 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5266 ///
5267 /// __builtin_astype( value, dst type )
5268 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)5269 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5270                                  SourceLocation BuiltinLoc,
5271                                  SourceLocation RParenLoc) {
5272   ExprValueKind VK = VK_RValue;
5273   ExprObjectKind OK = OK_Ordinary;
5274   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5275   QualType SrcTy = E->getType();
5276   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5277     return ExprError(Diag(BuiltinLoc,
5278                           diag::err_invalid_astype_of_different_size)
5279                      << DstTy
5280                      << SrcTy
5281                      << E->getSourceRange());
5282   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5283 }
5284 
5285 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5286 /// provided arguments.
5287 ///
5288 /// __builtin_convertvector( value, dst type )
5289 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)5290 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5291                                         SourceLocation BuiltinLoc,
5292                                         SourceLocation RParenLoc) {
5293   TypeSourceInfo *TInfo;
5294   GetTypeFromParser(ParsedDestTy, &TInfo);
5295   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5296 }
5297 
5298 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5299 /// i.e. an expression not of \p OverloadTy.  The expression should
5300 /// unary-convert to an expression of function-pointer or
5301 /// block-pointer type.
5302 ///
5303 /// \param NDecl the declaration being called, if available
5304 ExprResult
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig)5305 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5306                             SourceLocation LParenLoc,
5307                             ArrayRef<Expr *> Args,
5308                             SourceLocation RParenLoc,
5309                             Expr *Config, bool IsExecConfig) {
5310   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5311   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5312 
5313   // Functions with 'interrupt' attribute cannot be called directly.
5314   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5315     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5316     return ExprError();
5317   }
5318 
5319   // Promote the function operand.
5320   // We special-case function promotion here because we only allow promoting
5321   // builtin functions to function pointers in the callee of a call.
5322   ExprResult Result;
5323   if (BuiltinID &&
5324       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5325     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5326                                CK_BuiltinFnToFnPtr).get();
5327   } else {
5328     Result = CallExprUnaryConversions(Fn);
5329   }
5330   if (Result.isInvalid())
5331     return ExprError();
5332   Fn = Result.get();
5333 
5334   // Make the call expr early, before semantic checks.  This guarantees cleanup
5335   // of arguments and function on error.
5336   CallExpr *TheCall;
5337   if (Config)
5338     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5339                                                cast<CallExpr>(Config), Args,
5340                                                Context.BoolTy, VK_RValue,
5341                                                RParenLoc);
5342   else
5343     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5344                                      VK_RValue, RParenLoc);
5345 
5346   if (!getLangOpts().CPlusPlus) {
5347     // C cannot always handle TypoExpr nodes in builtin calls and direct
5348     // function calls as their argument checking don't necessarily handle
5349     // dependent types properly, so make sure any TypoExprs have been
5350     // dealt with.
5351     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5352     if (!Result.isUsable()) return ExprError();
5353     TheCall = dyn_cast<CallExpr>(Result.get());
5354     if (!TheCall) return Result;
5355     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5356   }
5357 
5358   // Bail out early if calling a builtin with custom typechecking.
5359   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5360     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5361 
5362  retry:
5363   const FunctionType *FuncT;
5364   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5365     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5366     // have type pointer to function".
5367     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5368     if (!FuncT)
5369       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5370                          << Fn->getType() << Fn->getSourceRange());
5371   } else if (const BlockPointerType *BPT =
5372                Fn->getType()->getAs<BlockPointerType>()) {
5373     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5374   } else {
5375     // Handle calls to expressions of unknown-any type.
5376     if (Fn->getType() == Context.UnknownAnyTy) {
5377       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5378       if (rewrite.isInvalid()) return ExprError();
5379       Fn = rewrite.get();
5380       TheCall->setCallee(Fn);
5381       goto retry;
5382     }
5383 
5384     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5385       << Fn->getType() << Fn->getSourceRange());
5386   }
5387 
5388   if (getLangOpts().CUDA) {
5389     if (Config) {
5390       // CUDA: Kernel calls must be to global functions
5391       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5392         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5393             << FDecl->getName() << Fn->getSourceRange());
5394 
5395       // CUDA: Kernel function must have 'void' return type
5396       if (!FuncT->getReturnType()->isVoidType())
5397         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5398             << Fn->getType() << Fn->getSourceRange());
5399     } else {
5400       // CUDA: Calls to global functions must be configured
5401       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5402         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5403             << FDecl->getName() << Fn->getSourceRange());
5404     }
5405   }
5406 
5407   // Check for a valid return type
5408   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5409                           FDecl))
5410     return ExprError();
5411 
5412   // We know the result type of the call, set it.
5413   TheCall->setType(FuncT->getCallResultType(Context));
5414   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5415 
5416   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5417   if (Proto) {
5418     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5419                                 IsExecConfig))
5420       return ExprError();
5421   } else {
5422     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5423 
5424     if (FDecl) {
5425       // Check if we have too few/too many template arguments, based
5426       // on our knowledge of the function definition.
5427       const FunctionDecl *Def = nullptr;
5428       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5429         Proto = Def->getType()->getAs<FunctionProtoType>();
5430        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5431           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5432           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5433       }
5434 
5435       // If the function we're calling isn't a function prototype, but we have
5436       // a function prototype from a prior declaratiom, use that prototype.
5437       if (!FDecl->hasPrototype())
5438         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5439     }
5440 
5441     // Promote the arguments (C99 6.5.2.2p6).
5442     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5443       Expr *Arg = Args[i];
5444 
5445       if (Proto && i < Proto->getNumParams()) {
5446         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5447             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5448         ExprResult ArgE =
5449             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5450         if (ArgE.isInvalid())
5451           return true;
5452 
5453         Arg = ArgE.getAs<Expr>();
5454 
5455       } else {
5456         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5457 
5458         if (ArgE.isInvalid())
5459           return true;
5460 
5461         Arg = ArgE.getAs<Expr>();
5462       }
5463 
5464       if (RequireCompleteType(Arg->getLocStart(),
5465                               Arg->getType(),
5466                               diag::err_call_incomplete_argument, Arg))
5467         return ExprError();
5468 
5469       TheCall->setArg(i, Arg);
5470     }
5471   }
5472 
5473   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5474     if (!Method->isStatic())
5475       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5476         << Fn->getSourceRange());
5477 
5478   // Check for sentinels
5479   if (NDecl)
5480     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5481 
5482   // Do special checking on direct calls to functions.
5483   if (FDecl) {
5484     if (CheckFunctionCall(FDecl, TheCall, Proto))
5485       return ExprError();
5486 
5487     if (BuiltinID)
5488       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5489   } else if (NDecl) {
5490     if (CheckPointerCall(NDecl, TheCall, Proto))
5491       return ExprError();
5492   } else {
5493     if (CheckOtherCall(TheCall, Proto))
5494       return ExprError();
5495   }
5496 
5497   return MaybeBindToTemporary(TheCall);
5498 }
5499 
5500 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)5501 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5502                            SourceLocation RParenLoc, Expr *InitExpr) {
5503   assert(Ty && "ActOnCompoundLiteral(): missing type");
5504   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5505 
5506   TypeSourceInfo *TInfo;
5507   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5508   if (!TInfo)
5509     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5510 
5511   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5512 }
5513 
5514 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)5515 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5516                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5517   QualType literalType = TInfo->getType();
5518 
5519   if (literalType->isArrayType()) {
5520     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5521           diag::err_illegal_decl_array_incomplete_type,
5522           SourceRange(LParenLoc,
5523                       LiteralExpr->getSourceRange().getEnd())))
5524       return ExprError();
5525     if (literalType->isVariableArrayType())
5526       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5527         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5528   } else if (!literalType->isDependentType() &&
5529              RequireCompleteType(LParenLoc, literalType,
5530                diag::err_typecheck_decl_incomplete_type,
5531                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5532     return ExprError();
5533 
5534   InitializedEntity Entity
5535     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5536   InitializationKind Kind
5537     = InitializationKind::CreateCStyleCast(LParenLoc,
5538                                            SourceRange(LParenLoc, RParenLoc),
5539                                            /*InitList=*/true);
5540   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5541   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5542                                       &literalType);
5543   if (Result.isInvalid())
5544     return ExprError();
5545   LiteralExpr = Result.get();
5546 
5547   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5548   if (isFileScope &&
5549       !LiteralExpr->isTypeDependent() &&
5550       !LiteralExpr->isValueDependent() &&
5551       !literalType->isDependentType()) { // 6.5.2.5p3
5552     if (CheckForConstantInitializer(LiteralExpr, literalType))
5553       return ExprError();
5554   }
5555 
5556   // In C, compound literals are l-values for some reason.
5557   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5558 
5559   return MaybeBindToTemporary(
5560            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5561                                              VK, LiteralExpr, isFileScope));
5562 }
5563 
5564 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)5565 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5566                     SourceLocation RBraceLoc) {
5567   // Immediately handle non-overload placeholders.  Overloads can be
5568   // resolved contextually, but everything else here can't.
5569   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5570     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5571       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5572 
5573       // Ignore failures; dropping the entire initializer list because
5574       // of one failure would be terrible for indexing/etc.
5575       if (result.isInvalid()) continue;
5576 
5577       InitArgList[I] = result.get();
5578     }
5579   }
5580 
5581   // Semantic analysis for initializers is done by ActOnDeclarator() and
5582   // CheckInitializer() - it requires knowledge of the object being intialized.
5583 
5584   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5585                                                RBraceLoc);
5586   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5587   return E;
5588 }
5589 
5590 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)5591 void Sema::maybeExtendBlockObject(ExprResult &E) {
5592   assert(E.get()->getType()->isBlockPointerType());
5593   assert(E.get()->isRValue());
5594 
5595   // Only do this in an r-value context.
5596   if (!getLangOpts().ObjCAutoRefCount) return;
5597 
5598   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5599                                CK_ARCExtendBlockObject, E.get(),
5600                                /*base path*/ nullptr, VK_RValue);
5601   Cleanup.setExprNeedsCleanups(true);
5602 }
5603 
5604 /// Prepare a conversion of the given expression to an ObjC object
5605 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)5606 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5607   QualType type = E.get()->getType();
5608   if (type->isObjCObjectPointerType()) {
5609     return CK_BitCast;
5610   } else if (type->isBlockPointerType()) {
5611     maybeExtendBlockObject(E);
5612     return CK_BlockPointerToObjCPointerCast;
5613   } else {
5614     assert(type->isPointerType());
5615     return CK_CPointerToObjCPointerCast;
5616   }
5617 }
5618 
5619 /// Prepares for a scalar cast, performing all the necessary stages
5620 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)5621 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5622   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5623   // Also, callers should have filtered out the invalid cases with
5624   // pointers.  Everything else should be possible.
5625 
5626   QualType SrcTy = Src.get()->getType();
5627   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5628     return CK_NoOp;
5629 
5630   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5631   case Type::STK_MemberPointer:
5632     llvm_unreachable("member pointer type in C");
5633 
5634   case Type::STK_CPointer:
5635   case Type::STK_BlockPointer:
5636   case Type::STK_ObjCObjectPointer:
5637     switch (DestTy->getScalarTypeKind()) {
5638     case Type::STK_CPointer: {
5639       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5640       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5641       if (SrcAS != DestAS)
5642         return CK_AddressSpaceConversion;
5643       return CK_BitCast;
5644     }
5645     case Type::STK_BlockPointer:
5646       return (SrcKind == Type::STK_BlockPointer
5647                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5648     case Type::STK_ObjCObjectPointer:
5649       if (SrcKind == Type::STK_ObjCObjectPointer)
5650         return CK_BitCast;
5651       if (SrcKind == Type::STK_CPointer)
5652         return CK_CPointerToObjCPointerCast;
5653       maybeExtendBlockObject(Src);
5654       return CK_BlockPointerToObjCPointerCast;
5655     case Type::STK_Bool:
5656       return CK_PointerToBoolean;
5657     case Type::STK_Integral:
5658       return CK_PointerToIntegral;
5659     case Type::STK_Floating:
5660     case Type::STK_FloatingComplex:
5661     case Type::STK_IntegralComplex:
5662     case Type::STK_MemberPointer:
5663       llvm_unreachable("illegal cast from pointer");
5664     }
5665     llvm_unreachable("Should have returned before this");
5666 
5667   case Type::STK_Bool: // casting from bool is like casting from an integer
5668   case Type::STK_Integral:
5669     switch (DestTy->getScalarTypeKind()) {
5670     case Type::STK_CPointer:
5671     case Type::STK_ObjCObjectPointer:
5672     case Type::STK_BlockPointer:
5673       if (Src.get()->isNullPointerConstant(Context,
5674                                            Expr::NPC_ValueDependentIsNull))
5675         return CK_NullToPointer;
5676       return CK_IntegralToPointer;
5677     case Type::STK_Bool:
5678       return CK_IntegralToBoolean;
5679     case Type::STK_Integral:
5680       return CK_IntegralCast;
5681     case Type::STK_Floating:
5682       return CK_IntegralToFloating;
5683     case Type::STK_IntegralComplex:
5684       Src = ImpCastExprToType(Src.get(),
5685                       DestTy->castAs<ComplexType>()->getElementType(),
5686                       CK_IntegralCast);
5687       return CK_IntegralRealToComplex;
5688     case Type::STK_FloatingComplex:
5689       Src = ImpCastExprToType(Src.get(),
5690                       DestTy->castAs<ComplexType>()->getElementType(),
5691                       CK_IntegralToFloating);
5692       return CK_FloatingRealToComplex;
5693     case Type::STK_MemberPointer:
5694       llvm_unreachable("member pointer type in C");
5695     }
5696     llvm_unreachable("Should have returned before this");
5697 
5698   case Type::STK_Floating:
5699     switch (DestTy->getScalarTypeKind()) {
5700     case Type::STK_Floating:
5701       return CK_FloatingCast;
5702     case Type::STK_Bool:
5703       return CK_FloatingToBoolean;
5704     case Type::STK_Integral:
5705       return CK_FloatingToIntegral;
5706     case Type::STK_FloatingComplex:
5707       Src = ImpCastExprToType(Src.get(),
5708                               DestTy->castAs<ComplexType>()->getElementType(),
5709                               CK_FloatingCast);
5710       return CK_FloatingRealToComplex;
5711     case Type::STK_IntegralComplex:
5712       Src = ImpCastExprToType(Src.get(),
5713                               DestTy->castAs<ComplexType>()->getElementType(),
5714                               CK_FloatingToIntegral);
5715       return CK_IntegralRealToComplex;
5716     case Type::STK_CPointer:
5717     case Type::STK_ObjCObjectPointer:
5718     case Type::STK_BlockPointer:
5719       llvm_unreachable("valid float->pointer cast?");
5720     case Type::STK_MemberPointer:
5721       llvm_unreachable("member pointer type in C");
5722     }
5723     llvm_unreachable("Should have returned before this");
5724 
5725   case Type::STK_FloatingComplex:
5726     switch (DestTy->getScalarTypeKind()) {
5727     case Type::STK_FloatingComplex:
5728       return CK_FloatingComplexCast;
5729     case Type::STK_IntegralComplex:
5730       return CK_FloatingComplexToIntegralComplex;
5731     case Type::STK_Floating: {
5732       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5733       if (Context.hasSameType(ET, DestTy))
5734         return CK_FloatingComplexToReal;
5735       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5736       return CK_FloatingCast;
5737     }
5738     case Type::STK_Bool:
5739       return CK_FloatingComplexToBoolean;
5740     case Type::STK_Integral:
5741       Src = ImpCastExprToType(Src.get(),
5742                               SrcTy->castAs<ComplexType>()->getElementType(),
5743                               CK_FloatingComplexToReal);
5744       return CK_FloatingToIntegral;
5745     case Type::STK_CPointer:
5746     case Type::STK_ObjCObjectPointer:
5747     case Type::STK_BlockPointer:
5748       llvm_unreachable("valid complex float->pointer cast?");
5749     case Type::STK_MemberPointer:
5750       llvm_unreachable("member pointer type in C");
5751     }
5752     llvm_unreachable("Should have returned before this");
5753 
5754   case Type::STK_IntegralComplex:
5755     switch (DestTy->getScalarTypeKind()) {
5756     case Type::STK_FloatingComplex:
5757       return CK_IntegralComplexToFloatingComplex;
5758     case Type::STK_IntegralComplex:
5759       return CK_IntegralComplexCast;
5760     case Type::STK_Integral: {
5761       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5762       if (Context.hasSameType(ET, DestTy))
5763         return CK_IntegralComplexToReal;
5764       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5765       return CK_IntegralCast;
5766     }
5767     case Type::STK_Bool:
5768       return CK_IntegralComplexToBoolean;
5769     case Type::STK_Floating:
5770       Src = ImpCastExprToType(Src.get(),
5771                               SrcTy->castAs<ComplexType>()->getElementType(),
5772                               CK_IntegralComplexToReal);
5773       return CK_IntegralToFloating;
5774     case Type::STK_CPointer:
5775     case Type::STK_ObjCObjectPointer:
5776     case Type::STK_BlockPointer:
5777       llvm_unreachable("valid complex int->pointer cast?");
5778     case Type::STK_MemberPointer:
5779       llvm_unreachable("member pointer type in C");
5780     }
5781     llvm_unreachable("Should have returned before this");
5782   }
5783 
5784   llvm_unreachable("Unhandled scalar cast");
5785 }
5786 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)5787 static bool breakDownVectorType(QualType type, uint64_t &len,
5788                                 QualType &eltType) {
5789   // Vectors are simple.
5790   if (const VectorType *vecType = type->getAs<VectorType>()) {
5791     len = vecType->getNumElements();
5792     eltType = vecType->getElementType();
5793     assert(eltType->isScalarType());
5794     return true;
5795   }
5796 
5797   // We allow lax conversion to and from non-vector types, but only if
5798   // they're real types (i.e. non-complex, non-pointer scalar types).
5799   if (!type->isRealType()) return false;
5800 
5801   len = 1;
5802   eltType = type;
5803   return true;
5804 }
5805 
5806 /// Are the two types lax-compatible vector types?  That is, given
5807 /// that one of them is a vector, do they have equal storage sizes,
5808 /// where the storage size is the number of elements times the element
5809 /// size?
5810 ///
5811 /// This will also return false if either of the types is neither a
5812 /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)5813 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5814   assert(destTy->isVectorType() || srcTy->isVectorType());
5815 
5816   // Disallow lax conversions between scalars and ExtVectors (these
5817   // conversions are allowed for other vector types because common headers
5818   // depend on them).  Most scalar OP ExtVector cases are handled by the
5819   // splat path anyway, which does what we want (convert, not bitcast).
5820   // What this rules out for ExtVectors is crazy things like char4*float.
5821   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5822   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5823 
5824   uint64_t srcLen, destLen;
5825   QualType srcEltTy, destEltTy;
5826   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5827   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5828 
5829   // ASTContext::getTypeSize will return the size rounded up to a
5830   // power of 2, so instead of using that, we need to use the raw
5831   // element size multiplied by the element count.
5832   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5833   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5834 
5835   return (srcLen * srcEltSize == destLen * destEltSize);
5836 }
5837 
5838 /// Is this a legal conversion between two types, one of which is
5839 /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)5840 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5841   assert(destTy->isVectorType() || srcTy->isVectorType());
5842 
5843   if (!Context.getLangOpts().LaxVectorConversions)
5844     return false;
5845   return areLaxCompatibleVectorTypes(srcTy, destTy);
5846 }
5847 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)5848 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5849                            CastKind &Kind) {
5850   assert(VectorTy->isVectorType() && "Not a vector type!");
5851 
5852   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5853     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5854       return Diag(R.getBegin(),
5855                   Ty->isVectorType() ?
5856                   diag::err_invalid_conversion_between_vectors :
5857                   diag::err_invalid_conversion_between_vector_and_integer)
5858         << VectorTy << Ty << R;
5859   } else
5860     return Diag(R.getBegin(),
5861                 diag::err_invalid_conversion_between_vector_and_scalar)
5862       << VectorTy << Ty << R;
5863 
5864   Kind = CK_BitCast;
5865   return false;
5866 }
5867 
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)5868 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5869   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5870 
5871   if (DestElemTy == SplattedExpr->getType())
5872     return SplattedExpr;
5873 
5874   assert(DestElemTy->isFloatingType() ||
5875          DestElemTy->isIntegralOrEnumerationType());
5876 
5877   CastKind CK;
5878   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5879     // OpenCL requires that we convert `true` boolean expressions to -1, but
5880     // only when splatting vectors.
5881     if (DestElemTy->isFloatingType()) {
5882       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5883       // in two steps: boolean to signed integral, then to floating.
5884       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5885                                                  CK_BooleanToSignedIntegral);
5886       SplattedExpr = CastExprRes.get();
5887       CK = CK_IntegralToFloating;
5888     } else {
5889       CK = CK_BooleanToSignedIntegral;
5890     }
5891   } else {
5892     ExprResult CastExprRes = SplattedExpr;
5893     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5894     if (CastExprRes.isInvalid())
5895       return ExprError();
5896     SplattedExpr = CastExprRes.get();
5897   }
5898   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5899 }
5900 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)5901 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5902                                     Expr *CastExpr, CastKind &Kind) {
5903   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5904 
5905   QualType SrcTy = CastExpr->getType();
5906 
5907   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5908   // an ExtVectorType.
5909   // In OpenCL, casts between vectors of different types are not allowed.
5910   // (See OpenCL 6.2).
5911   if (SrcTy->isVectorType()) {
5912     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5913         || (getLangOpts().OpenCL &&
5914             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5915       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5916         << DestTy << SrcTy << R;
5917       return ExprError();
5918     }
5919     Kind = CK_BitCast;
5920     return CastExpr;
5921   }
5922 
5923   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5924   // conversion will take place first from scalar to elt type, and then
5925   // splat from elt type to vector.
5926   if (SrcTy->isPointerType())
5927     return Diag(R.getBegin(),
5928                 diag::err_invalid_conversion_between_vector_and_scalar)
5929       << DestTy << SrcTy << R;
5930 
5931   Kind = CK_VectorSplat;
5932   return prepareVectorSplat(DestTy, CastExpr);
5933 }
5934 
5935 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)5936 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5937                     Declarator &D, ParsedType &Ty,
5938                     SourceLocation RParenLoc, Expr *CastExpr) {
5939   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5940          "ActOnCastExpr(): missing type or expr");
5941 
5942   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5943   if (D.isInvalidType())
5944     return ExprError();
5945 
5946   if (getLangOpts().CPlusPlus) {
5947     // Check that there are no default arguments (C++ only).
5948     CheckExtraCXXDefaultArguments(D);
5949   } else {
5950     // Make sure any TypoExprs have been dealt with.
5951     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5952     if (!Res.isUsable())
5953       return ExprError();
5954     CastExpr = Res.get();
5955   }
5956 
5957   checkUnusedDeclAttributes(D);
5958 
5959   QualType castType = castTInfo->getType();
5960   Ty = CreateParsedType(castType, castTInfo);
5961 
5962   bool isVectorLiteral = false;
5963 
5964   // Check for an altivec or OpenCL literal,
5965   // i.e. all the elements are integer constants.
5966   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5967   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5968   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5969        && castType->isVectorType() && (PE || PLE)) {
5970     if (PLE && PLE->getNumExprs() == 0) {
5971       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5972       return ExprError();
5973     }
5974     if (PE || PLE->getNumExprs() == 1) {
5975       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5976       if (!E->getType()->isVectorType())
5977         isVectorLiteral = true;
5978     }
5979     else
5980       isVectorLiteral = true;
5981   }
5982 
5983   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5984   // then handle it as such.
5985   if (isVectorLiteral)
5986     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5987 
5988   // If the Expr being casted is a ParenListExpr, handle it specially.
5989   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5990   // sequence of BinOp comma operators.
5991   if (isa<ParenListExpr>(CastExpr)) {
5992     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5993     if (Result.isInvalid()) return ExprError();
5994     CastExpr = Result.get();
5995   }
5996 
5997   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5998       !getSourceManager().isInSystemMacro(LParenLoc))
5999     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6000 
6001   CheckTollFreeBridgeCast(castType, CastExpr);
6002 
6003   CheckObjCBridgeRelatedCast(castType, CastExpr);
6004 
6005   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6006 }
6007 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)6008 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6009                                     SourceLocation RParenLoc, Expr *E,
6010                                     TypeSourceInfo *TInfo) {
6011   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6012          "Expected paren or paren list expression");
6013 
6014   Expr **exprs;
6015   unsigned numExprs;
6016   Expr *subExpr;
6017   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6018   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6019     LiteralLParenLoc = PE->getLParenLoc();
6020     LiteralRParenLoc = PE->getRParenLoc();
6021     exprs = PE->getExprs();
6022     numExprs = PE->getNumExprs();
6023   } else { // isa<ParenExpr> by assertion at function entrance
6024     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6025     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6026     subExpr = cast<ParenExpr>(E)->getSubExpr();
6027     exprs = &subExpr;
6028     numExprs = 1;
6029   }
6030 
6031   QualType Ty = TInfo->getType();
6032   assert(Ty->isVectorType() && "Expected vector type");
6033 
6034   SmallVector<Expr *, 8> initExprs;
6035   const VectorType *VTy = Ty->getAs<VectorType>();
6036   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6037 
6038   // '(...)' form of vector initialization in AltiVec: the number of
6039   // initializers must be one or must match the size of the vector.
6040   // If a single value is specified in the initializer then it will be
6041   // replicated to all the components of the vector
6042   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6043     // The number of initializers must be one or must match the size of the
6044     // vector. If a single value is specified in the initializer then it will
6045     // be replicated to all the components of the vector
6046     if (numExprs == 1) {
6047       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6048       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6049       if (Literal.isInvalid())
6050         return ExprError();
6051       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6052                                   PrepareScalarCast(Literal, ElemTy));
6053       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6054     }
6055     else if (numExprs < numElems) {
6056       Diag(E->getExprLoc(),
6057            diag::err_incorrect_number_of_vector_initializers);
6058       return ExprError();
6059     }
6060     else
6061       initExprs.append(exprs, exprs + numExprs);
6062   }
6063   else {
6064     // For OpenCL, when the number of initializers is a single value,
6065     // it will be replicated to all components of the vector.
6066     if (getLangOpts().OpenCL &&
6067         VTy->getVectorKind() == VectorType::GenericVector &&
6068         numExprs == 1) {
6069         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6070         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6071         if (Literal.isInvalid())
6072           return ExprError();
6073         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6074                                     PrepareScalarCast(Literal, ElemTy));
6075         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6076     }
6077 
6078     initExprs.append(exprs, exprs + numExprs);
6079   }
6080   // FIXME: This means that pretty-printing the final AST will produce curly
6081   // braces instead of the original commas.
6082   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6083                                                    initExprs, LiteralRParenLoc);
6084   initE->setType(Ty);
6085   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6086 }
6087 
6088 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6089 /// the ParenListExpr into a sequence of comma binary operators.
6090 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)6091 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6092   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6093   if (!E)
6094     return OrigExpr;
6095 
6096   ExprResult Result(E->getExpr(0));
6097 
6098   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6099     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6100                         E->getExpr(i));
6101 
6102   if (Result.isInvalid()) return ExprError();
6103 
6104   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6105 }
6106 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)6107 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6108                                     SourceLocation R,
6109                                     MultiExprArg Val) {
6110   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6111   return expr;
6112 }
6113 
6114 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6115 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6116 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)6117 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6118                                       SourceLocation QuestionLoc) {
6119   Expr *NullExpr = LHSExpr;
6120   Expr *NonPointerExpr = RHSExpr;
6121   Expr::NullPointerConstantKind NullKind =
6122       NullExpr->isNullPointerConstant(Context,
6123                                       Expr::NPC_ValueDependentIsNotNull);
6124 
6125   if (NullKind == Expr::NPCK_NotNull) {
6126     NullExpr = RHSExpr;
6127     NonPointerExpr = LHSExpr;
6128     NullKind =
6129         NullExpr->isNullPointerConstant(Context,
6130                                         Expr::NPC_ValueDependentIsNotNull);
6131   }
6132 
6133   if (NullKind == Expr::NPCK_NotNull)
6134     return false;
6135 
6136   if (NullKind == Expr::NPCK_ZeroExpression)
6137     return false;
6138 
6139   if (NullKind == Expr::NPCK_ZeroLiteral) {
6140     // In this case, check to make sure that we got here from a "NULL"
6141     // string in the source code.
6142     NullExpr = NullExpr->IgnoreParenImpCasts();
6143     SourceLocation loc = NullExpr->getExprLoc();
6144     if (!findMacroSpelling(loc, "NULL"))
6145       return false;
6146   }
6147 
6148   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6149   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6150       << NonPointerExpr->getType() << DiagType
6151       << NonPointerExpr->getSourceRange();
6152   return true;
6153 }
6154 
6155 /// \brief Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)6156 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6157   QualType CondTy = Cond->getType();
6158 
6159   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6160   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6161     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6162       << CondTy << Cond->getSourceRange();
6163     return true;
6164   }
6165 
6166   // C99 6.5.15p2
6167   if (CondTy->isScalarType()) return false;
6168 
6169   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6170     << CondTy << Cond->getSourceRange();
6171   return true;
6172 }
6173 
6174 /// \brief Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)6175 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6176                                          ExprResult &RHS) {
6177     Expr *LHSExpr = LHS.get();
6178     Expr *RHSExpr = RHS.get();
6179 
6180     if (!LHSExpr->getType()->isVoidType())
6181       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6182         << RHSExpr->getSourceRange();
6183     if (!RHSExpr->getType()->isVoidType())
6184       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6185         << LHSExpr->getSourceRange();
6186     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6187     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6188     return S.Context.VoidTy;
6189 }
6190 
6191 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6192 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)6193 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6194                                         QualType PointerTy) {
6195   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6196       !NullExpr.get()->isNullPointerConstant(S.Context,
6197                                             Expr::NPC_ValueDependentIsNull))
6198     return true;
6199 
6200   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6201   return false;
6202 }
6203 
6204 /// \brief Checks compatibility between two pointers and return the resulting
6205 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6206 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6207                                                      ExprResult &RHS,
6208                                                      SourceLocation Loc) {
6209   QualType LHSTy = LHS.get()->getType();
6210   QualType RHSTy = RHS.get()->getType();
6211 
6212   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6213     // Two identical pointers types are always compatible.
6214     return LHSTy;
6215   }
6216 
6217   QualType lhptee, rhptee;
6218 
6219   // Get the pointee types.
6220   bool IsBlockPointer = false;
6221   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6222     lhptee = LHSBTy->getPointeeType();
6223     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6224     IsBlockPointer = true;
6225   } else {
6226     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6227     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6228   }
6229 
6230   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6231   // differently qualified versions of compatible types, the result type is
6232   // a pointer to an appropriately qualified version of the composite
6233   // type.
6234 
6235   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6236   // clause doesn't make sense for our extensions. E.g. address space 2 should
6237   // be incompatible with address space 3: they may live on different devices or
6238   // anything.
6239   Qualifiers lhQual = lhptee.getQualifiers();
6240   Qualifiers rhQual = rhptee.getQualifiers();
6241 
6242   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6243   lhQual.removeCVRQualifiers();
6244   rhQual.removeCVRQualifiers();
6245 
6246   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6247   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6248 
6249   // For OpenCL:
6250   // 1. If LHS and RHS types match exactly and:
6251   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6252   //  (b) AS overlap => generate addrspacecast
6253   //  (c) AS don't overlap => give an error
6254   // 2. if LHS and RHS types don't match:
6255   //  (a) AS match => use standard C rules, generate bitcast
6256   //  (b) AS overlap => generate addrspacecast instead of bitcast
6257   //  (c) AS don't overlap => give an error
6258 
6259   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6260   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6261 
6262   // OpenCL cases 1c, 2a, 2b, and 2c.
6263   if (CompositeTy.isNull()) {
6264     // In this situation, we assume void* type. No especially good
6265     // reason, but this is what gcc does, and we do have to pick
6266     // to get a consistent AST.
6267     QualType incompatTy;
6268     if (S.getLangOpts().OpenCL) {
6269       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6270       // spaces is disallowed.
6271       unsigned ResultAddrSpace;
6272       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6273         // Cases 2a and 2b.
6274         ResultAddrSpace = lhQual.getAddressSpace();
6275       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6276         // Cases 2a and 2b.
6277         ResultAddrSpace = rhQual.getAddressSpace();
6278       } else {
6279         // Cases 1c and 2c.
6280         S.Diag(Loc,
6281                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6282             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6283             << RHS.get()->getSourceRange();
6284         return QualType();
6285       }
6286 
6287       // Continue handling cases 2a and 2b.
6288       incompatTy = S.Context.getPointerType(
6289           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6290       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6291                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6292                                     ? CK_AddressSpaceConversion /* 2b */
6293                                     : CK_BitCast /* 2a */);
6294       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6295                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6296                                     ? CK_AddressSpaceConversion /* 2b */
6297                                     : CK_BitCast /* 2a */);
6298     } else {
6299       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6300           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6301           << RHS.get()->getSourceRange();
6302       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6303       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6304       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6305     }
6306     return incompatTy;
6307   }
6308 
6309   // The pointer types are compatible.
6310   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6311   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6312   if (IsBlockPointer)
6313     ResultTy = S.Context.getBlockPointerType(ResultTy);
6314   else {
6315     // Cases 1a and 1b for OpenCL.
6316     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6317     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6318                       ? CK_BitCast /* 1a */
6319                       : CK_AddressSpaceConversion /* 1b */;
6320     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6321                       ? CK_BitCast /* 1a */
6322                       : CK_AddressSpaceConversion /* 1b */;
6323     ResultTy = S.Context.getPointerType(ResultTy);
6324   }
6325 
6326   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6327   // if the target type does not change.
6328   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6329   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6330   return ResultTy;
6331 }
6332 
6333 /// \brief Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6334 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6335                                                           ExprResult &LHS,
6336                                                           ExprResult &RHS,
6337                                                           SourceLocation Loc) {
6338   QualType LHSTy = LHS.get()->getType();
6339   QualType RHSTy = RHS.get()->getType();
6340 
6341   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6342     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6343       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6344       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6345       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6346       return destType;
6347     }
6348     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6349       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6350       << RHS.get()->getSourceRange();
6351     return QualType();
6352   }
6353 
6354   // We have 2 block pointer types.
6355   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6356 }
6357 
6358 /// \brief Return the resulting type when the operands are both pointers.
6359 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6360 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6361                                             ExprResult &RHS,
6362                                             SourceLocation Loc) {
6363   // get the pointer types
6364   QualType LHSTy = LHS.get()->getType();
6365   QualType RHSTy = RHS.get()->getType();
6366 
6367   // get the "pointed to" types
6368   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6369   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6370 
6371   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6372   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6373     // Figure out necessary qualifiers (C99 6.5.15p6)
6374     QualType destPointee
6375       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6376     QualType destType = S.Context.getPointerType(destPointee);
6377     // Add qualifiers if necessary.
6378     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6379     // Promote to void*.
6380     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6381     return destType;
6382   }
6383   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6384     QualType destPointee
6385       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6386     QualType destType = S.Context.getPointerType(destPointee);
6387     // Add qualifiers if necessary.
6388     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6389     // Promote to void*.
6390     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6391     return destType;
6392   }
6393 
6394   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6395 }
6396 
6397 /// \brief Return false if the first expression is not an integer and the second
6398 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)6399 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6400                                         Expr* PointerExpr, SourceLocation Loc,
6401                                         bool IsIntFirstExpr) {
6402   if (!PointerExpr->getType()->isPointerType() ||
6403       !Int.get()->getType()->isIntegerType())
6404     return false;
6405 
6406   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6407   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6408 
6409   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6410     << Expr1->getType() << Expr2->getType()
6411     << Expr1->getSourceRange() << Expr2->getSourceRange();
6412   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6413                             CK_IntegralToPointer);
6414   return true;
6415 }
6416 
6417 /// \brief Simple conversion between integer and floating point types.
6418 ///
6419 /// Used when handling the OpenCL conditional operator where the
6420 /// condition is a vector while the other operands are scalar.
6421 ///
6422 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6423 /// types are either integer or floating type. Between the two
6424 /// operands, the type with the higher rank is defined as the "result
6425 /// type". The other operand needs to be promoted to the same type. No
6426 /// other type promotion is allowed. We cannot use
6427 /// UsualArithmeticConversions() for this purpose, since it always
6428 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6429 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6430                                             ExprResult &RHS,
6431                                             SourceLocation QuestionLoc) {
6432   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6433   if (LHS.isInvalid())
6434     return QualType();
6435   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6436   if (RHS.isInvalid())
6437     return QualType();
6438 
6439   // For conversion purposes, we ignore any qualifiers.
6440   // For example, "const float" and "float" are equivalent.
6441   QualType LHSType =
6442     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6443   QualType RHSType =
6444     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6445 
6446   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6447     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6448       << LHSType << LHS.get()->getSourceRange();
6449     return QualType();
6450   }
6451 
6452   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6453     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6454       << RHSType << RHS.get()->getSourceRange();
6455     return QualType();
6456   }
6457 
6458   // If both types are identical, no conversion is needed.
6459   if (LHSType == RHSType)
6460     return LHSType;
6461 
6462   // Now handle "real" floating types (i.e. float, double, long double).
6463   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6464     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6465                                  /*IsCompAssign = */ false);
6466 
6467   // Finally, we have two differing integer types.
6468   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6469   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6470 }
6471 
6472 /// \brief Convert scalar operands to a vector that matches the
6473 ///        condition in length.
6474 ///
6475 /// Used when handling the OpenCL conditional operator where the
6476 /// condition is a vector while the other operands are scalar.
6477 ///
6478 /// We first compute the "result type" for the scalar operands
6479 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6480 /// into a vector of that type where the length matches the condition
6481 /// vector type. s6.11.6 requires that the element types of the result
6482 /// and the condition must have the same number of bits.
6483 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)6484 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6485                               QualType CondTy, SourceLocation QuestionLoc) {
6486   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6487   if (ResTy.isNull()) return QualType();
6488 
6489   const VectorType *CV = CondTy->getAs<VectorType>();
6490   assert(CV);
6491 
6492   // Determine the vector result type
6493   unsigned NumElements = CV->getNumElements();
6494   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6495 
6496   // Ensure that all types have the same number of bits
6497   if (S.Context.getTypeSize(CV->getElementType())
6498       != S.Context.getTypeSize(ResTy)) {
6499     // Since VectorTy is created internally, it does not pretty print
6500     // with an OpenCL name. Instead, we just print a description.
6501     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6502     SmallString<64> Str;
6503     llvm::raw_svector_ostream OS(Str);
6504     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6505     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6506       << CondTy << OS.str();
6507     return QualType();
6508   }
6509 
6510   // Convert operands to the vector result type
6511   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6512   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6513 
6514   return VectorTy;
6515 }
6516 
6517 /// \brief Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)6518 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6519                                        SourceLocation QuestionLoc) {
6520   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6521   // integral type.
6522   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6523   assert(CondTy);
6524   QualType EleTy = CondTy->getElementType();
6525   if (EleTy->isIntegerType()) return false;
6526 
6527   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6528     << Cond->getType() << Cond->getSourceRange();
6529   return true;
6530 }
6531 
6532 /// \brief Return false if the vector condition type and the vector
6533 ///        result type are compatible.
6534 ///
6535 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6536 /// number of elements, and their element types have the same number
6537 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)6538 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6539                               SourceLocation QuestionLoc) {
6540   const VectorType *CV = CondTy->getAs<VectorType>();
6541   const VectorType *RV = VecResTy->getAs<VectorType>();
6542   assert(CV && RV);
6543 
6544   if (CV->getNumElements() != RV->getNumElements()) {
6545     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6546       << CondTy << VecResTy;
6547     return true;
6548   }
6549 
6550   QualType CVE = CV->getElementType();
6551   QualType RVE = RV->getElementType();
6552 
6553   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6554     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6555       << CondTy << VecResTy;
6556     return true;
6557   }
6558 
6559   return false;
6560 }
6561 
6562 /// \brief Return the resulting type for the conditional operator in
6563 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6564 ///        s6.3.i) when the condition is a vector type.
6565 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6566 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6567                              ExprResult &LHS, ExprResult &RHS,
6568                              SourceLocation QuestionLoc) {
6569   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6570   if (Cond.isInvalid())
6571     return QualType();
6572   QualType CondTy = Cond.get()->getType();
6573 
6574   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6575     return QualType();
6576 
6577   // If either operand is a vector then find the vector type of the
6578   // result as specified in OpenCL v1.1 s6.3.i.
6579   if (LHS.get()->getType()->isVectorType() ||
6580       RHS.get()->getType()->isVectorType()) {
6581     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6582                                               /*isCompAssign*/false,
6583                                               /*AllowBothBool*/true,
6584                                               /*AllowBoolConversions*/false);
6585     if (VecResTy.isNull()) return QualType();
6586     // The result type must match the condition type as specified in
6587     // OpenCL v1.1 s6.11.6.
6588     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6589       return QualType();
6590     return VecResTy;
6591   }
6592 
6593   // Both operands are scalar.
6594   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6595 }
6596 
6597 /// \brief Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)6598 static bool checkBlockType(Sema &S, const Expr *E) {
6599   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6600     QualType Ty = CE->getCallee()->getType();
6601     if (Ty->isBlockPointerType()) {
6602       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6603       return true;
6604     }
6605   }
6606   return false;
6607 }
6608 
6609 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6610 /// In that case, LHS = cond.
6611 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)6612 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6613                                         ExprResult &RHS, ExprValueKind &VK,
6614                                         ExprObjectKind &OK,
6615                                         SourceLocation QuestionLoc) {
6616 
6617   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6618   if (!LHSResult.isUsable()) return QualType();
6619   LHS = LHSResult;
6620 
6621   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6622   if (!RHSResult.isUsable()) return QualType();
6623   RHS = RHSResult;
6624 
6625   // C++ is sufficiently different to merit its own checker.
6626   if (getLangOpts().CPlusPlus)
6627     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6628 
6629   VK = VK_RValue;
6630   OK = OK_Ordinary;
6631 
6632   // The OpenCL operator with a vector condition is sufficiently
6633   // different to merit its own checker.
6634   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6635     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6636 
6637   // First, check the condition.
6638   Cond = UsualUnaryConversions(Cond.get());
6639   if (Cond.isInvalid())
6640     return QualType();
6641   if (checkCondition(*this, Cond.get(), QuestionLoc))
6642     return QualType();
6643 
6644   // Now check the two expressions.
6645   if (LHS.get()->getType()->isVectorType() ||
6646       RHS.get()->getType()->isVectorType())
6647     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6648                                /*AllowBothBool*/true,
6649                                /*AllowBoolConversions*/false);
6650 
6651   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6652   if (LHS.isInvalid() || RHS.isInvalid())
6653     return QualType();
6654 
6655   QualType LHSTy = LHS.get()->getType();
6656   QualType RHSTy = RHS.get()->getType();
6657 
6658   // Diagnose attempts to convert between __float128 and long double where
6659   // such conversions currently can't be handled.
6660   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6661     Diag(QuestionLoc,
6662          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6663       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6664     return QualType();
6665   }
6666 
6667   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6668   // selection operator (?:).
6669   if (getLangOpts().OpenCL &&
6670       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6671     return QualType();
6672   }
6673 
6674   // If both operands have arithmetic type, do the usual arithmetic conversions
6675   // to find a common type: C99 6.5.15p3,5.
6676   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6677     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6678     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6679 
6680     return ResTy;
6681   }
6682 
6683   // If both operands are the same structure or union type, the result is that
6684   // type.
6685   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6686     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6687       if (LHSRT->getDecl() == RHSRT->getDecl())
6688         // "If both the operands have structure or union type, the result has
6689         // that type."  This implies that CV qualifiers are dropped.
6690         return LHSTy.getUnqualifiedType();
6691     // FIXME: Type of conditional expression must be complete in C mode.
6692   }
6693 
6694   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6695   // The following || allows only one side to be void (a GCC-ism).
6696   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6697     return checkConditionalVoidType(*this, LHS, RHS);
6698   }
6699 
6700   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6701   // the type of the other operand."
6702   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6703   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6704 
6705   // All objective-c pointer type analysis is done here.
6706   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6707                                                         QuestionLoc);
6708   if (LHS.isInvalid() || RHS.isInvalid())
6709     return QualType();
6710   if (!compositeType.isNull())
6711     return compositeType;
6712 
6713 
6714   // Handle block pointer types.
6715   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6716     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6717                                                      QuestionLoc);
6718 
6719   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6720   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6721     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6722                                                        QuestionLoc);
6723 
6724   // GCC compatibility: soften pointer/integer mismatch.  Note that
6725   // null pointers have been filtered out by this point.
6726   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6727       /*isIntFirstExpr=*/true))
6728     return RHSTy;
6729   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6730       /*isIntFirstExpr=*/false))
6731     return LHSTy;
6732 
6733   // Emit a better diagnostic if one of the expressions is a null pointer
6734   // constant and the other is not a pointer type. In this case, the user most
6735   // likely forgot to take the address of the other expression.
6736   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6737     return QualType();
6738 
6739   // Otherwise, the operands are not compatible.
6740   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6741     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6742     << RHS.get()->getSourceRange();
6743   return QualType();
6744 }
6745 
6746 /// FindCompositeObjCPointerType - Helper method to find composite type of
6747 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6748 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6749                                             SourceLocation QuestionLoc) {
6750   QualType LHSTy = LHS.get()->getType();
6751   QualType RHSTy = RHS.get()->getType();
6752 
6753   // Handle things like Class and struct objc_class*.  Here we case the result
6754   // to the pseudo-builtin, because that will be implicitly cast back to the
6755   // redefinition type if an attempt is made to access its fields.
6756   if (LHSTy->isObjCClassType() &&
6757       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6758     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6759     return LHSTy;
6760   }
6761   if (RHSTy->isObjCClassType() &&
6762       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6763     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6764     return RHSTy;
6765   }
6766   // And the same for struct objc_object* / id
6767   if (LHSTy->isObjCIdType() &&
6768       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6769     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6770     return LHSTy;
6771   }
6772   if (RHSTy->isObjCIdType() &&
6773       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6774     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6775     return RHSTy;
6776   }
6777   // And the same for struct objc_selector* / SEL
6778   if (Context.isObjCSelType(LHSTy) &&
6779       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6780     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6781     return LHSTy;
6782   }
6783   if (Context.isObjCSelType(RHSTy) &&
6784       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6785     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6786     return RHSTy;
6787   }
6788   // Check constraints for Objective-C object pointers types.
6789   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6790 
6791     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6792       // Two identical object pointer types are always compatible.
6793       return LHSTy;
6794     }
6795     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6796     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6797     QualType compositeType = LHSTy;
6798 
6799     // If both operands are interfaces and either operand can be
6800     // assigned to the other, use that type as the composite
6801     // type. This allows
6802     //   xxx ? (A*) a : (B*) b
6803     // where B is a subclass of A.
6804     //
6805     // Additionally, as for assignment, if either type is 'id'
6806     // allow silent coercion. Finally, if the types are
6807     // incompatible then make sure to use 'id' as the composite
6808     // type so the result is acceptable for sending messages to.
6809 
6810     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6811     // It could return the composite type.
6812     if (!(compositeType =
6813           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6814       // Nothing more to do.
6815     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6816       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6817     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6818       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6819     } else if ((LHSTy->isObjCQualifiedIdType() ||
6820                 RHSTy->isObjCQualifiedIdType()) &&
6821                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6822       // Need to handle "id<xx>" explicitly.
6823       // GCC allows qualified id and any Objective-C type to devolve to
6824       // id. Currently localizing to here until clear this should be
6825       // part of ObjCQualifiedIdTypesAreCompatible.
6826       compositeType = Context.getObjCIdType();
6827     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6828       compositeType = Context.getObjCIdType();
6829     } else {
6830       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6831       << LHSTy << RHSTy
6832       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6833       QualType incompatTy = Context.getObjCIdType();
6834       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6835       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6836       return incompatTy;
6837     }
6838     // The object pointer types are compatible.
6839     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6840     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6841     return compositeType;
6842   }
6843   // Check Objective-C object pointer types and 'void *'
6844   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6845     if (getLangOpts().ObjCAutoRefCount) {
6846       // ARC forbids the implicit conversion of object pointers to 'void *',
6847       // so these types are not compatible.
6848       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6849           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6850       LHS = RHS = true;
6851       return QualType();
6852     }
6853     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6854     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6855     QualType destPointee
6856     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6857     QualType destType = Context.getPointerType(destPointee);
6858     // Add qualifiers if necessary.
6859     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6860     // Promote to void*.
6861     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6862     return destType;
6863   }
6864   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6865     if (getLangOpts().ObjCAutoRefCount) {
6866       // ARC forbids the implicit conversion of object pointers to 'void *',
6867       // so these types are not compatible.
6868       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6869           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6870       LHS = RHS = true;
6871       return QualType();
6872     }
6873     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6874     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6875     QualType destPointee
6876     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6877     QualType destType = Context.getPointerType(destPointee);
6878     // Add qualifiers if necessary.
6879     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6880     // Promote to void*.
6881     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6882     return destType;
6883   }
6884   return QualType();
6885 }
6886 
6887 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6888 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)6889 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6890                                const PartialDiagnostic &Note,
6891                                SourceRange ParenRange) {
6892   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6893   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6894       EndLoc.isValid()) {
6895     Self.Diag(Loc, Note)
6896       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6897       << FixItHint::CreateInsertion(EndLoc, ")");
6898   } else {
6899     // We can't display the parentheses, so just show the bare note.
6900     Self.Diag(Loc, Note) << ParenRange;
6901   }
6902 }
6903 
IsArithmeticOp(BinaryOperatorKind Opc)6904 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6905   return BinaryOperator::isAdditiveOp(Opc) ||
6906          BinaryOperator::isMultiplicativeOp(Opc) ||
6907          BinaryOperator::isShiftOp(Opc);
6908 }
6909 
6910 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6911 /// expression, either using a built-in or overloaded operator,
6912 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6913 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)6914 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6915                                    Expr **RHSExprs) {
6916   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6917   E = E->IgnoreImpCasts();
6918   E = E->IgnoreConversionOperator();
6919   E = E->IgnoreImpCasts();
6920 
6921   // Built-in binary operator.
6922   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6923     if (IsArithmeticOp(OP->getOpcode())) {
6924       *Opcode = OP->getOpcode();
6925       *RHSExprs = OP->getRHS();
6926       return true;
6927     }
6928   }
6929 
6930   // Overloaded operator.
6931   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6932     if (Call->getNumArgs() != 2)
6933       return false;
6934 
6935     // Make sure this is really a binary operator that is safe to pass into
6936     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6937     OverloadedOperatorKind OO = Call->getOperator();
6938     if (OO < OO_Plus || OO > OO_Arrow ||
6939         OO == OO_PlusPlus || OO == OO_MinusMinus)
6940       return false;
6941 
6942     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6943     if (IsArithmeticOp(OpKind)) {
6944       *Opcode = OpKind;
6945       *RHSExprs = Call->getArg(1);
6946       return true;
6947     }
6948   }
6949 
6950   return false;
6951 }
6952 
6953 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6954 /// or is a logical expression such as (x==y) which has int type, but is
6955 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)6956 static bool ExprLooksBoolean(Expr *E) {
6957   E = E->IgnoreParenImpCasts();
6958 
6959   if (E->getType()->isBooleanType())
6960     return true;
6961   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6962     return OP->isComparisonOp() || OP->isLogicalOp();
6963   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6964     return OP->getOpcode() == UO_LNot;
6965   if (E->getType()->isPointerType())
6966     return true;
6967 
6968   return false;
6969 }
6970 
6971 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6972 /// and binary operator are mixed in a way that suggests the programmer assumed
6973 /// the conditional operator has higher precedence, for example:
6974 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)6975 static void DiagnoseConditionalPrecedence(Sema &Self,
6976                                           SourceLocation OpLoc,
6977                                           Expr *Condition,
6978                                           Expr *LHSExpr,
6979                                           Expr *RHSExpr) {
6980   BinaryOperatorKind CondOpcode;
6981   Expr *CondRHS;
6982 
6983   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6984     return;
6985   if (!ExprLooksBoolean(CondRHS))
6986     return;
6987 
6988   // The condition is an arithmetic binary expression, with a right-
6989   // hand side that looks boolean, so warn.
6990 
6991   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6992       << Condition->getSourceRange()
6993       << BinaryOperator::getOpcodeStr(CondOpcode);
6994 
6995   SuggestParentheses(Self, OpLoc,
6996     Self.PDiag(diag::note_precedence_silence)
6997       << BinaryOperator::getOpcodeStr(CondOpcode),
6998     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6999 
7000   SuggestParentheses(Self, OpLoc,
7001     Self.PDiag(diag::note_precedence_conditional_first),
7002     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7003 }
7004 
7005 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7006 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)7007 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7008                                     SourceLocation ColonLoc,
7009                                     Expr *CondExpr, Expr *LHSExpr,
7010                                     Expr *RHSExpr) {
7011   if (!getLangOpts().CPlusPlus) {
7012     // C cannot handle TypoExpr nodes in the condition because it
7013     // doesn't handle dependent types properly, so make sure any TypoExprs have
7014     // been dealt with before checking the operands.
7015     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7016     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7017     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7018 
7019     if (!CondResult.isUsable())
7020       return ExprError();
7021 
7022     if (LHSExpr) {
7023       if (!LHSResult.isUsable())
7024         return ExprError();
7025     }
7026 
7027     if (!RHSResult.isUsable())
7028       return ExprError();
7029 
7030     CondExpr = CondResult.get();
7031     LHSExpr = LHSResult.get();
7032     RHSExpr = RHSResult.get();
7033   }
7034 
7035   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7036   // was the condition.
7037   OpaqueValueExpr *opaqueValue = nullptr;
7038   Expr *commonExpr = nullptr;
7039   if (!LHSExpr) {
7040     commonExpr = CondExpr;
7041     // Lower out placeholder types first.  This is important so that we don't
7042     // try to capture a placeholder. This happens in few cases in C++; such
7043     // as Objective-C++'s dictionary subscripting syntax.
7044     if (commonExpr->hasPlaceholderType()) {
7045       ExprResult result = CheckPlaceholderExpr(commonExpr);
7046       if (!result.isUsable()) return ExprError();
7047       commonExpr = result.get();
7048     }
7049     // We usually want to apply unary conversions *before* saving, except
7050     // in the special case of a C++ l-value conditional.
7051     if (!(getLangOpts().CPlusPlus
7052           && !commonExpr->isTypeDependent()
7053           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7054           && commonExpr->isGLValue()
7055           && commonExpr->isOrdinaryOrBitFieldObject()
7056           && RHSExpr->isOrdinaryOrBitFieldObject()
7057           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7058       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7059       if (commonRes.isInvalid())
7060         return ExprError();
7061       commonExpr = commonRes.get();
7062     }
7063 
7064     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7065                                                 commonExpr->getType(),
7066                                                 commonExpr->getValueKind(),
7067                                                 commonExpr->getObjectKind(),
7068                                                 commonExpr);
7069     LHSExpr = CondExpr = opaqueValue;
7070   }
7071 
7072   ExprValueKind VK = VK_RValue;
7073   ExprObjectKind OK = OK_Ordinary;
7074   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7075   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7076                                              VK, OK, QuestionLoc);
7077   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7078       RHS.isInvalid())
7079     return ExprError();
7080 
7081   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7082                                 RHS.get());
7083 
7084   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7085 
7086   if (!commonExpr)
7087     return new (Context)
7088         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7089                             RHS.get(), result, VK, OK);
7090 
7091   return new (Context) BinaryConditionalOperator(
7092       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7093       ColonLoc, result, VK, OK);
7094 }
7095 
7096 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7097 // being closely modeled after the C99 spec:-). The odd characteristic of this
7098 // routine is it effectively iqnores the qualifiers on the top level pointee.
7099 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7100 // FIXME: add a couple examples in this comment.
7101 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7102 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7103   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7104   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7105 
7106   // get the "pointed to" type (ignoring qualifiers at the top level)
7107   const Type *lhptee, *rhptee;
7108   Qualifiers lhq, rhq;
7109   std::tie(lhptee, lhq) =
7110       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7111   std::tie(rhptee, rhq) =
7112       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7113 
7114   Sema::AssignConvertType ConvTy = Sema::Compatible;
7115 
7116   // C99 6.5.16.1p1: This following citation is common to constraints
7117   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7118   // qualifiers of the type *pointed to* by the right;
7119 
7120   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7121   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7122       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7123     // Ignore lifetime for further calculation.
7124     lhq.removeObjCLifetime();
7125     rhq.removeObjCLifetime();
7126   }
7127 
7128   if (!lhq.compatiblyIncludes(rhq)) {
7129     // Treat address-space mismatches as fatal.  TODO: address subspaces
7130     if (!lhq.isAddressSpaceSupersetOf(rhq))
7131       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7132 
7133     // It's okay to add or remove GC or lifetime qualifiers when converting to
7134     // and from void*.
7135     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7136                         .compatiblyIncludes(
7137                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7138              && (lhptee->isVoidType() || rhptee->isVoidType()))
7139       ; // keep old
7140 
7141     // Treat lifetime mismatches as fatal.
7142     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7143       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7144 
7145     // For GCC/MS compatibility, other qualifier mismatches are treated
7146     // as still compatible in C.
7147     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7148   }
7149 
7150   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7151   // incomplete type and the other is a pointer to a qualified or unqualified
7152   // version of void...
7153   if (lhptee->isVoidType()) {
7154     if (rhptee->isIncompleteOrObjectType())
7155       return ConvTy;
7156 
7157     // As an extension, we allow cast to/from void* to function pointer.
7158     assert(rhptee->isFunctionType());
7159     return Sema::FunctionVoidPointer;
7160   }
7161 
7162   if (rhptee->isVoidType()) {
7163     if (lhptee->isIncompleteOrObjectType())
7164       return ConvTy;
7165 
7166     // As an extension, we allow cast to/from void* to function pointer.
7167     assert(lhptee->isFunctionType());
7168     return Sema::FunctionVoidPointer;
7169   }
7170 
7171   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7172   // unqualified versions of compatible types, ...
7173   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7174   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7175     // Check if the pointee types are compatible ignoring the sign.
7176     // We explicitly check for char so that we catch "char" vs
7177     // "unsigned char" on systems where "char" is unsigned.
7178     if (lhptee->isCharType())
7179       ltrans = S.Context.UnsignedCharTy;
7180     else if (lhptee->hasSignedIntegerRepresentation())
7181       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7182 
7183     if (rhptee->isCharType())
7184       rtrans = S.Context.UnsignedCharTy;
7185     else if (rhptee->hasSignedIntegerRepresentation())
7186       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7187 
7188     if (ltrans == rtrans) {
7189       // Types are compatible ignoring the sign. Qualifier incompatibility
7190       // takes priority over sign incompatibility because the sign
7191       // warning can be disabled.
7192       if (ConvTy != Sema::Compatible)
7193         return ConvTy;
7194 
7195       return Sema::IncompatiblePointerSign;
7196     }
7197 
7198     // If we are a multi-level pointer, it's possible that our issue is simply
7199     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7200     // the eventual target type is the same and the pointers have the same
7201     // level of indirection, this must be the issue.
7202     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7203       do {
7204         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7205         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7206       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7207 
7208       if (lhptee == rhptee)
7209         return Sema::IncompatibleNestedPointerQualifiers;
7210     }
7211 
7212     // General pointer incompatibility takes priority over qualifiers.
7213     return Sema::IncompatiblePointer;
7214   }
7215   if (!S.getLangOpts().CPlusPlus &&
7216       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7217     return Sema::IncompatiblePointer;
7218   return ConvTy;
7219 }
7220 
7221 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7222 /// block pointer types are compatible or whether a block and normal pointer
7223 /// are compatible. It is more restrict than comparing two function pointer
7224 // types.
7225 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7226 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7227                                     QualType RHSType) {
7228   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7229   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7230 
7231   QualType lhptee, rhptee;
7232 
7233   // get the "pointed to" type (ignoring qualifiers at the top level)
7234   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7235   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7236 
7237   // In C++, the types have to match exactly.
7238   if (S.getLangOpts().CPlusPlus)
7239     return Sema::IncompatibleBlockPointer;
7240 
7241   Sema::AssignConvertType ConvTy = Sema::Compatible;
7242 
7243   // For blocks we enforce that qualifiers are identical.
7244   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7245     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7246 
7247   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7248     return Sema::IncompatibleBlockPointer;
7249 
7250   return ConvTy;
7251 }
7252 
7253 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7254 /// for assignment compatibility.
7255 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)7256 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7257                                    QualType RHSType) {
7258   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7259   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7260 
7261   if (LHSType->isObjCBuiltinType()) {
7262     // Class is not compatible with ObjC object pointers.
7263     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7264         !RHSType->isObjCQualifiedClassType())
7265       return Sema::IncompatiblePointer;
7266     return Sema::Compatible;
7267   }
7268   if (RHSType->isObjCBuiltinType()) {
7269     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7270         !LHSType->isObjCQualifiedClassType())
7271       return Sema::IncompatiblePointer;
7272     return Sema::Compatible;
7273   }
7274   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7275   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7276 
7277   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7278       // make an exception for id<P>
7279       !LHSType->isObjCQualifiedIdType())
7280     return Sema::CompatiblePointerDiscardsQualifiers;
7281 
7282   if (S.Context.typesAreCompatible(LHSType, RHSType))
7283     return Sema::Compatible;
7284   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7285     return Sema::IncompatibleObjCQualifiedId;
7286   return Sema::IncompatiblePointer;
7287 }
7288 
7289 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)7290 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7291                                  QualType LHSType, QualType RHSType) {
7292   // Fake up an opaque expression.  We don't actually care about what
7293   // cast operations are required, so if CheckAssignmentConstraints
7294   // adds casts to this they'll be wasted, but fortunately that doesn't
7295   // usually happen on valid code.
7296   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7297   ExprResult RHSPtr = &RHSExpr;
7298   CastKind K = CK_Invalid;
7299 
7300   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7301 }
7302 
7303 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7304 /// has code to accommodate several GCC extensions when type checking
7305 /// pointers. Here are some objectionable examples that GCC considers warnings:
7306 ///
7307 ///  int a, *pint;
7308 ///  short *pshort;
7309 ///  struct foo *pfoo;
7310 ///
7311 ///  pint = pshort; // warning: assignment from incompatible pointer type
7312 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7313 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7314 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7315 ///
7316 /// As a result, the code for dealing with pointers is more complex than the
7317 /// C99 spec dictates.
7318 ///
7319 /// Sets 'Kind' for any result kind except Incompatible.
7320 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)7321 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7322                                  CastKind &Kind, bool ConvertRHS) {
7323   QualType RHSType = RHS.get()->getType();
7324   QualType OrigLHSType = LHSType;
7325 
7326   // Get canonical types.  We're not formatting these types, just comparing
7327   // them.
7328   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7329   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7330 
7331   // Common case: no conversion required.
7332   if (LHSType == RHSType) {
7333     Kind = CK_NoOp;
7334     return Compatible;
7335   }
7336 
7337   // If we have an atomic type, try a non-atomic assignment, then just add an
7338   // atomic qualification step.
7339   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7340     Sema::AssignConvertType result =
7341       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7342     if (result != Compatible)
7343       return result;
7344     if (Kind != CK_NoOp && ConvertRHS)
7345       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7346     Kind = CK_NonAtomicToAtomic;
7347     return Compatible;
7348   }
7349 
7350   // If the left-hand side is a reference type, then we are in a
7351   // (rare!) case where we've allowed the use of references in C,
7352   // e.g., as a parameter type in a built-in function. In this case,
7353   // just make sure that the type referenced is compatible with the
7354   // right-hand side type. The caller is responsible for adjusting
7355   // LHSType so that the resulting expression does not have reference
7356   // type.
7357   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7358     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7359       Kind = CK_LValueBitCast;
7360       return Compatible;
7361     }
7362     return Incompatible;
7363   }
7364 
7365   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7366   // to the same ExtVector type.
7367   if (LHSType->isExtVectorType()) {
7368     if (RHSType->isExtVectorType())
7369       return Incompatible;
7370     if (RHSType->isArithmeticType()) {
7371       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7372       if (ConvertRHS)
7373         RHS = prepareVectorSplat(LHSType, RHS.get());
7374       Kind = CK_VectorSplat;
7375       return Compatible;
7376     }
7377   }
7378 
7379   // Conversions to or from vector type.
7380   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7381     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7382       // Allow assignments of an AltiVec vector type to an equivalent GCC
7383       // vector type and vice versa
7384       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7385         Kind = CK_BitCast;
7386         return Compatible;
7387       }
7388 
7389       // If we are allowing lax vector conversions, and LHS and RHS are both
7390       // vectors, the total size only needs to be the same. This is a bitcast;
7391       // no bits are changed but the result type is different.
7392       if (isLaxVectorConversion(RHSType, LHSType)) {
7393         Kind = CK_BitCast;
7394         return IncompatibleVectors;
7395       }
7396     }
7397 
7398     // When the RHS comes from another lax conversion (e.g. binops between
7399     // scalars and vectors) the result is canonicalized as a vector. When the
7400     // LHS is also a vector, the lax is allowed by the condition above. Handle
7401     // the case where LHS is a scalar.
7402     if (LHSType->isScalarType()) {
7403       const VectorType *VecType = RHSType->getAs<VectorType>();
7404       if (VecType && VecType->getNumElements() == 1 &&
7405           isLaxVectorConversion(RHSType, LHSType)) {
7406         ExprResult *VecExpr = &RHS;
7407         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7408         Kind = CK_BitCast;
7409         return Compatible;
7410       }
7411     }
7412 
7413     return Incompatible;
7414   }
7415 
7416   // Diagnose attempts to convert between __float128 and long double where
7417   // such conversions currently can't be handled.
7418   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7419     return Incompatible;
7420 
7421   // Arithmetic conversions.
7422   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7423       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7424     if (ConvertRHS)
7425       Kind = PrepareScalarCast(RHS, LHSType);
7426     return Compatible;
7427   }
7428 
7429   // Conversions to normal pointers.
7430   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7431     // U* -> T*
7432     if (isa<PointerType>(RHSType)) {
7433       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7434       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7435       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7436       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7437     }
7438 
7439     // int -> T*
7440     if (RHSType->isIntegerType()) {
7441       Kind = CK_IntegralToPointer; // FIXME: null?
7442       return IntToPointer;
7443     }
7444 
7445     // C pointers are not compatible with ObjC object pointers,
7446     // with two exceptions:
7447     if (isa<ObjCObjectPointerType>(RHSType)) {
7448       //  - conversions to void*
7449       if (LHSPointer->getPointeeType()->isVoidType()) {
7450         Kind = CK_BitCast;
7451         return Compatible;
7452       }
7453 
7454       //  - conversions from 'Class' to the redefinition type
7455       if (RHSType->isObjCClassType() &&
7456           Context.hasSameType(LHSType,
7457                               Context.getObjCClassRedefinitionType())) {
7458         Kind = CK_BitCast;
7459         return Compatible;
7460       }
7461 
7462       Kind = CK_BitCast;
7463       return IncompatiblePointer;
7464     }
7465 
7466     // U^ -> void*
7467     if (RHSType->getAs<BlockPointerType>()) {
7468       if (LHSPointer->getPointeeType()->isVoidType()) {
7469         Kind = CK_BitCast;
7470         return Compatible;
7471       }
7472     }
7473 
7474     return Incompatible;
7475   }
7476 
7477   // Conversions to block pointers.
7478   if (isa<BlockPointerType>(LHSType)) {
7479     // U^ -> T^
7480     if (RHSType->isBlockPointerType()) {
7481       Kind = CK_BitCast;
7482       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7483     }
7484 
7485     // int or null -> T^
7486     if (RHSType->isIntegerType()) {
7487       Kind = CK_IntegralToPointer; // FIXME: null
7488       return IntToBlockPointer;
7489     }
7490 
7491     // id -> T^
7492     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7493       Kind = CK_AnyPointerToBlockPointerCast;
7494       return Compatible;
7495     }
7496 
7497     // void* -> T^
7498     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7499       if (RHSPT->getPointeeType()->isVoidType()) {
7500         Kind = CK_AnyPointerToBlockPointerCast;
7501         return Compatible;
7502       }
7503 
7504     return Incompatible;
7505   }
7506 
7507   // Conversions to Objective-C pointers.
7508   if (isa<ObjCObjectPointerType>(LHSType)) {
7509     // A* -> B*
7510     if (RHSType->isObjCObjectPointerType()) {
7511       Kind = CK_BitCast;
7512       Sema::AssignConvertType result =
7513         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7514       if (getLangOpts().ObjCAutoRefCount &&
7515           result == Compatible &&
7516           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7517         result = IncompatibleObjCWeakRef;
7518       return result;
7519     }
7520 
7521     // int or null -> A*
7522     if (RHSType->isIntegerType()) {
7523       Kind = CK_IntegralToPointer; // FIXME: null
7524       return IntToPointer;
7525     }
7526 
7527     // In general, C pointers are not compatible with ObjC object pointers,
7528     // with two exceptions:
7529     if (isa<PointerType>(RHSType)) {
7530       Kind = CK_CPointerToObjCPointerCast;
7531 
7532       //  - conversions from 'void*'
7533       if (RHSType->isVoidPointerType()) {
7534         return Compatible;
7535       }
7536 
7537       //  - conversions to 'Class' from its redefinition type
7538       if (LHSType->isObjCClassType() &&
7539           Context.hasSameType(RHSType,
7540                               Context.getObjCClassRedefinitionType())) {
7541         return Compatible;
7542       }
7543 
7544       return IncompatiblePointer;
7545     }
7546 
7547     // Only under strict condition T^ is compatible with an Objective-C pointer.
7548     if (RHSType->isBlockPointerType() &&
7549         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7550       if (ConvertRHS)
7551         maybeExtendBlockObject(RHS);
7552       Kind = CK_BlockPointerToObjCPointerCast;
7553       return Compatible;
7554     }
7555 
7556     return Incompatible;
7557   }
7558 
7559   // Conversions from pointers that are not covered by the above.
7560   if (isa<PointerType>(RHSType)) {
7561     // T* -> _Bool
7562     if (LHSType == Context.BoolTy) {
7563       Kind = CK_PointerToBoolean;
7564       return Compatible;
7565     }
7566 
7567     // T* -> int
7568     if (LHSType->isIntegerType()) {
7569       Kind = CK_PointerToIntegral;
7570       return PointerToInt;
7571     }
7572 
7573     return Incompatible;
7574   }
7575 
7576   // Conversions from Objective-C pointers that are not covered by the above.
7577   if (isa<ObjCObjectPointerType>(RHSType)) {
7578     // T* -> _Bool
7579     if (LHSType == Context.BoolTy) {
7580       Kind = CK_PointerToBoolean;
7581       return Compatible;
7582     }
7583 
7584     // T* -> int
7585     if (LHSType->isIntegerType()) {
7586       Kind = CK_PointerToIntegral;
7587       return PointerToInt;
7588     }
7589 
7590     return Incompatible;
7591   }
7592 
7593   // struct A -> struct B
7594   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7595     if (Context.typesAreCompatible(LHSType, RHSType)) {
7596       Kind = CK_NoOp;
7597       return Compatible;
7598     }
7599   }
7600 
7601   return Incompatible;
7602 }
7603 
7604 /// \brief Constructs a transparent union from an expression that is
7605 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)7606 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7607                                       ExprResult &EResult, QualType UnionType,
7608                                       FieldDecl *Field) {
7609   // Build an initializer list that designates the appropriate member
7610   // of the transparent union.
7611   Expr *E = EResult.get();
7612   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7613                                                    E, SourceLocation());
7614   Initializer->setType(UnionType);
7615   Initializer->setInitializedFieldInUnion(Field);
7616 
7617   // Build a compound literal constructing a value of the transparent
7618   // union type from this initializer list.
7619   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7620   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7621                                         VK_RValue, Initializer, false);
7622 }
7623 
7624 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)7625 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7626                                                ExprResult &RHS) {
7627   QualType RHSType = RHS.get()->getType();
7628 
7629   // If the ArgType is a Union type, we want to handle a potential
7630   // transparent_union GCC extension.
7631   const RecordType *UT = ArgType->getAsUnionType();
7632   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7633     return Incompatible;
7634 
7635   // The field to initialize within the transparent union.
7636   RecordDecl *UD = UT->getDecl();
7637   FieldDecl *InitField = nullptr;
7638   // It's compatible if the expression matches any of the fields.
7639   for (auto *it : UD->fields()) {
7640     if (it->getType()->isPointerType()) {
7641       // If the transparent union contains a pointer type, we allow:
7642       // 1) void pointer
7643       // 2) null pointer constant
7644       if (RHSType->isPointerType())
7645         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7646           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7647           InitField = it;
7648           break;
7649         }
7650 
7651       if (RHS.get()->isNullPointerConstant(Context,
7652                                            Expr::NPC_ValueDependentIsNull)) {
7653         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7654                                 CK_NullToPointer);
7655         InitField = it;
7656         break;
7657       }
7658     }
7659 
7660     CastKind Kind = CK_Invalid;
7661     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7662           == Compatible) {
7663       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7664       InitField = it;
7665       break;
7666     }
7667   }
7668 
7669   if (!InitField)
7670     return Incompatible;
7671 
7672   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7673   return Compatible;
7674 }
7675 
7676 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)7677 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7678                                        bool Diagnose,
7679                                        bool DiagnoseCFAudited,
7680                                        bool ConvertRHS) {
7681   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7682   // we can't avoid *all* modifications at the moment, so we need some somewhere
7683   // to put the updated value.
7684   ExprResult LocalRHS = CallerRHS;
7685   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7686 
7687   if (getLangOpts().CPlusPlus) {
7688     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7689       // C++ 5.17p3: If the left operand is not of class type, the
7690       // expression is implicitly converted (C++ 4) to the
7691       // cv-unqualified type of the left operand.
7692       ExprResult Res;
7693       if (Diagnose) {
7694         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7695                                         AA_Assigning);
7696       } else {
7697         ImplicitConversionSequence ICS =
7698             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7699                                   /*SuppressUserConversions=*/false,
7700                                   /*AllowExplicit=*/false,
7701                                   /*InOverloadResolution=*/false,
7702                                   /*CStyle=*/false,
7703                                   /*AllowObjCWritebackConversion=*/false);
7704         if (ICS.isFailure())
7705           return Incompatible;
7706         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7707                                         ICS, AA_Assigning);
7708       }
7709       if (Res.isInvalid())
7710         return Incompatible;
7711       Sema::AssignConvertType result = Compatible;
7712       if (getLangOpts().ObjCAutoRefCount &&
7713           !CheckObjCARCUnavailableWeakConversion(LHSType,
7714                                                  RHS.get()->getType()))
7715         result = IncompatibleObjCWeakRef;
7716       RHS = Res;
7717       return result;
7718     }
7719 
7720     // FIXME: Currently, we fall through and treat C++ classes like C
7721     // structures.
7722     // FIXME: We also fall through for atomics; not sure what should
7723     // happen there, though.
7724   } else if (RHS.get()->getType() == Context.OverloadTy) {
7725     // As a set of extensions to C, we support overloading on functions. These
7726     // functions need to be resolved here.
7727     DeclAccessPair DAP;
7728     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7729             RHS.get(), LHSType, /*Complain=*/false, DAP))
7730       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7731     else
7732       return Incompatible;
7733   }
7734 
7735   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7736   // a null pointer constant.
7737   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7738        LHSType->isBlockPointerType()) &&
7739       RHS.get()->isNullPointerConstant(Context,
7740                                        Expr::NPC_ValueDependentIsNull)) {
7741     if (Diagnose || ConvertRHS) {
7742       CastKind Kind;
7743       CXXCastPath Path;
7744       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7745                              /*IgnoreBaseAccess=*/false, Diagnose);
7746       if (ConvertRHS)
7747         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7748     }
7749     return Compatible;
7750   }
7751 
7752   // This check seems unnatural, however it is necessary to ensure the proper
7753   // conversion of functions/arrays. If the conversion were done for all
7754   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7755   // expressions that suppress this implicit conversion (&, sizeof).
7756   //
7757   // Suppress this for references: C++ 8.5.3p5.
7758   if (!LHSType->isReferenceType()) {
7759     // FIXME: We potentially allocate here even if ConvertRHS is false.
7760     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7761     if (RHS.isInvalid())
7762       return Incompatible;
7763   }
7764 
7765   Expr *PRE = RHS.get()->IgnoreParenCasts();
7766   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7767     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7768     if (PDecl && !PDecl->hasDefinition()) {
7769       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7770       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7771     }
7772   }
7773 
7774   CastKind Kind = CK_Invalid;
7775   Sema::AssignConvertType result =
7776     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7777 
7778   // C99 6.5.16.1p2: The value of the right operand is converted to the
7779   // type of the assignment expression.
7780   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7781   // so that we can use references in built-in functions even in C.
7782   // The getNonReferenceType() call makes sure that the resulting expression
7783   // does not have reference type.
7784   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7785     QualType Ty = LHSType.getNonLValueExprType(Context);
7786     Expr *E = RHS.get();
7787 
7788     // Check for various Objective-C errors. If we are not reporting
7789     // diagnostics and just checking for errors, e.g., during overload
7790     // resolution, return Incompatible to indicate the failure.
7791     if (getLangOpts().ObjCAutoRefCount &&
7792         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7793                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7794       if (!Diagnose)
7795         return Incompatible;
7796     }
7797     if (getLangOpts().ObjC1 &&
7798         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7799                                            E->getType(), E, Diagnose) ||
7800          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7801       if (!Diagnose)
7802         return Incompatible;
7803       // Replace the expression with a corrected version and continue so we
7804       // can find further errors.
7805       RHS = E;
7806       return Compatible;
7807     }
7808 
7809     if (ConvertRHS)
7810       RHS = ImpCastExprToType(E, Ty, Kind);
7811   }
7812   return result;
7813 }
7814 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)7815 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7816                                ExprResult &RHS) {
7817   Diag(Loc, diag::err_typecheck_invalid_operands)
7818     << LHS.get()->getType() << RHS.get()->getType()
7819     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7820   return QualType();
7821 }
7822 
7823 /// Try to convert a value of non-vector type to a vector type by converting
7824 /// the type to the element type of the vector and then performing a splat.
7825 /// If the language is OpenCL, we only use conversions that promote scalar
7826 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7827 /// for float->int.
7828 ///
7829 /// \param scalar - if non-null, actually perform the conversions
7830 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy)7831 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7832                                      QualType scalarTy,
7833                                      QualType vectorEltTy,
7834                                      QualType vectorTy) {
7835   // The conversion to apply to the scalar before splatting it,
7836   // if necessary.
7837   CastKind scalarCast = CK_Invalid;
7838 
7839   if (vectorEltTy->isIntegralType(S.Context)) {
7840     if (!scalarTy->isIntegralType(S.Context))
7841       return true;
7842     if (S.getLangOpts().OpenCL &&
7843         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7844       return true;
7845     scalarCast = CK_IntegralCast;
7846   } else if (vectorEltTy->isRealFloatingType()) {
7847     if (scalarTy->isRealFloatingType()) {
7848       if (S.getLangOpts().OpenCL &&
7849           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7850         return true;
7851       scalarCast = CK_FloatingCast;
7852     }
7853     else if (scalarTy->isIntegralType(S.Context))
7854       scalarCast = CK_IntegralToFloating;
7855     else
7856       return true;
7857   } else {
7858     return true;
7859   }
7860 
7861   // Adjust scalar if desired.
7862   if (scalar) {
7863     if (scalarCast != CK_Invalid)
7864       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7865     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7866   }
7867   return false;
7868 }
7869 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)7870 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7871                                    SourceLocation Loc, bool IsCompAssign,
7872                                    bool AllowBothBool,
7873                                    bool AllowBoolConversions) {
7874   if (!IsCompAssign) {
7875     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7876     if (LHS.isInvalid())
7877       return QualType();
7878   }
7879   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7880   if (RHS.isInvalid())
7881     return QualType();
7882 
7883   // For conversion purposes, we ignore any qualifiers.
7884   // For example, "const float" and "float" are equivalent.
7885   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7886   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7887 
7888   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7889   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7890   assert(LHSVecType || RHSVecType);
7891 
7892   // AltiVec-style "vector bool op vector bool" combinations are allowed
7893   // for some operators but not others.
7894   if (!AllowBothBool &&
7895       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7896       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7897     return InvalidOperands(Loc, LHS, RHS);
7898 
7899   // If the vector types are identical, return.
7900   if (Context.hasSameType(LHSType, RHSType))
7901     return LHSType;
7902 
7903   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7904   if (LHSVecType && RHSVecType &&
7905       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7906     if (isa<ExtVectorType>(LHSVecType)) {
7907       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7908       return LHSType;
7909     }
7910 
7911     if (!IsCompAssign)
7912       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7913     return RHSType;
7914   }
7915 
7916   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7917   // can be mixed, with the result being the non-bool type.  The non-bool
7918   // operand must have integer element type.
7919   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7920       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7921       (Context.getTypeSize(LHSVecType->getElementType()) ==
7922        Context.getTypeSize(RHSVecType->getElementType()))) {
7923     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7924         LHSVecType->getElementType()->isIntegerType() &&
7925         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7926       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7927       return LHSType;
7928     }
7929     if (!IsCompAssign &&
7930         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7931         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7932         RHSVecType->getElementType()->isIntegerType()) {
7933       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7934       return RHSType;
7935     }
7936   }
7937 
7938   // If there's an ext-vector type and a scalar, try to convert the scalar to
7939   // the vector element type and splat.
7940   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7941     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7942                                   LHSVecType->getElementType(), LHSType))
7943       return LHSType;
7944   }
7945   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7946     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7947                                   LHSType, RHSVecType->getElementType(),
7948                                   RHSType))
7949       return RHSType;
7950   }
7951 
7952   // If we're allowing lax vector conversions, only the total (data) size needs
7953   // to be the same. If one of the types is scalar, the result is always the
7954   // vector type. Don't allow this if the scalar operand is an lvalue.
7955   QualType VecType = LHSVecType ? LHSType : RHSType;
7956   QualType ScalarType = LHSVecType ? RHSType : LHSType;
7957   ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
7958   if (isLaxVectorConversion(ScalarType, VecType) &&
7959       !ScalarExpr->get()->isLValue()) {
7960     *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
7961     return VecType;
7962   }
7963 
7964   // Okay, the expression is invalid.
7965 
7966   // If there's a non-vector, non-real operand, diagnose that.
7967   if ((!RHSVecType && !RHSType->isRealType()) ||
7968       (!LHSVecType && !LHSType->isRealType())) {
7969     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7970       << LHSType << RHSType
7971       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7972     return QualType();
7973   }
7974 
7975   // OpenCL V1.1 6.2.6.p1:
7976   // If the operands are of more than one vector type, then an error shall
7977   // occur. Implicit conversions between vector types are not permitted, per
7978   // section 6.2.1.
7979   if (getLangOpts().OpenCL &&
7980       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7981       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7982     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7983                                                            << RHSType;
7984     return QualType();
7985   }
7986 
7987   // Otherwise, use the generic diagnostic.
7988   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7989     << LHSType << RHSType
7990     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7991   return QualType();
7992 }
7993 
7994 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7995 // expression.  These are mainly cases where the null pointer is used as an
7996 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)7997 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7998                                 SourceLocation Loc, bool IsCompare) {
7999   // The canonical way to check for a GNU null is with isNullPointerConstant,
8000   // but we use a bit of a hack here for speed; this is a relatively
8001   // hot path, and isNullPointerConstant is slow.
8002   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8003   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8004 
8005   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8006 
8007   // Avoid analyzing cases where the result will either be invalid (and
8008   // diagnosed as such) or entirely valid and not something to warn about.
8009   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8010       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8011     return;
8012 
8013   // Comparison operations would not make sense with a null pointer no matter
8014   // what the other expression is.
8015   if (!IsCompare) {
8016     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8017         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8018         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8019     return;
8020   }
8021 
8022   // The rest of the operations only make sense with a null pointer
8023   // if the other expression is a pointer.
8024   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8025       NonNullType->canDecayToPointerType())
8026     return;
8027 
8028   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8029       << LHSNull /* LHS is NULL */ << NonNullType
8030       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8031 }
8032 
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)8033 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8034                                                ExprResult &RHS,
8035                                                SourceLocation Loc, bool IsDiv) {
8036   // Check for division/remainder by zero.
8037   llvm::APSInt RHSValue;
8038   if (!RHS.get()->isValueDependent() &&
8039       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8040     S.DiagRuntimeBehavior(Loc, RHS.get(),
8041                           S.PDiag(diag::warn_remainder_division_by_zero)
8042                             << IsDiv << RHS.get()->getSourceRange());
8043 }
8044 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)8045 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8046                                            SourceLocation Loc,
8047                                            bool IsCompAssign, bool IsDiv) {
8048   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8049 
8050   if (LHS.get()->getType()->isVectorType() ||
8051       RHS.get()->getType()->isVectorType())
8052     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8053                                /*AllowBothBool*/getLangOpts().AltiVec,
8054                                /*AllowBoolConversions*/false);
8055 
8056   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8057   if (LHS.isInvalid() || RHS.isInvalid())
8058     return QualType();
8059 
8060 
8061   if (compType.isNull() || !compType->isArithmeticType())
8062     return InvalidOperands(Loc, LHS, RHS);
8063   if (IsDiv)
8064     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8065   return compType;
8066 }
8067 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8068 QualType Sema::CheckRemainderOperands(
8069   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8070   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8071 
8072   if (LHS.get()->getType()->isVectorType() ||
8073       RHS.get()->getType()->isVectorType()) {
8074     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8075         RHS.get()->getType()->hasIntegerRepresentation())
8076       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8077                                  /*AllowBothBool*/getLangOpts().AltiVec,
8078                                  /*AllowBoolConversions*/false);
8079     return InvalidOperands(Loc, LHS, RHS);
8080   }
8081 
8082   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8083   if (LHS.isInvalid() || RHS.isInvalid())
8084     return QualType();
8085 
8086   if (compType.isNull() || !compType->isIntegerType())
8087     return InvalidOperands(Loc, LHS, RHS);
8088   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8089   return compType;
8090 }
8091 
8092 /// \brief Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8093 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8094                                                 Expr *LHSExpr, Expr *RHSExpr) {
8095   S.Diag(Loc, S.getLangOpts().CPlusPlus
8096                 ? diag::err_typecheck_pointer_arith_void_type
8097                 : diag::ext_gnu_void_ptr)
8098     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8099                             << RHSExpr->getSourceRange();
8100 }
8101 
8102 /// \brief Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)8103 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8104                                             Expr *Pointer) {
8105   S.Diag(Loc, S.getLangOpts().CPlusPlus
8106                 ? diag::err_typecheck_pointer_arith_void_type
8107                 : diag::ext_gnu_void_ptr)
8108     << 0 /* one pointer */ << Pointer->getSourceRange();
8109 }
8110 
8111 /// \brief Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8112 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8113                                                     Expr *LHS, Expr *RHS) {
8114   assert(LHS->getType()->isAnyPointerType());
8115   assert(RHS->getType()->isAnyPointerType());
8116   S.Diag(Loc, S.getLangOpts().CPlusPlus
8117                 ? diag::err_typecheck_pointer_arith_function_type
8118                 : diag::ext_gnu_ptr_func_arith)
8119     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8120     // We only show the second type if it differs from the first.
8121     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8122                                                    RHS->getType())
8123     << RHS->getType()->getPointeeType()
8124     << LHS->getSourceRange() << RHS->getSourceRange();
8125 }
8126 
8127 /// \brief Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)8128 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8129                                                 Expr *Pointer) {
8130   assert(Pointer->getType()->isAnyPointerType());
8131   S.Diag(Loc, S.getLangOpts().CPlusPlus
8132                 ? diag::err_typecheck_pointer_arith_function_type
8133                 : diag::ext_gnu_ptr_func_arith)
8134     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8135     << 0 /* one pointer, so only one type */
8136     << Pointer->getSourceRange();
8137 }
8138 
8139 /// \brief Emit error if Operand is incomplete pointer type
8140 ///
8141 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)8142 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8143                                                  Expr *Operand) {
8144   QualType ResType = Operand->getType();
8145   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8146     ResType = ResAtomicType->getValueType();
8147 
8148   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8149   QualType PointeeTy = ResType->getPointeeType();
8150   return S.RequireCompleteType(Loc, PointeeTy,
8151                                diag::err_typecheck_arithmetic_incomplete_type,
8152                                PointeeTy, Operand->getSourceRange());
8153 }
8154 
8155 /// \brief Check the validity of an arithmetic pointer operand.
8156 ///
8157 /// If the operand has pointer type, this code will check for pointer types
8158 /// which are invalid in arithmetic operations. These will be diagnosed
8159 /// appropriately, including whether or not the use is supported as an
8160 /// extension.
8161 ///
8162 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)8163 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8164                                             Expr *Operand) {
8165   QualType ResType = Operand->getType();
8166   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8167     ResType = ResAtomicType->getValueType();
8168 
8169   if (!ResType->isAnyPointerType()) return true;
8170 
8171   QualType PointeeTy = ResType->getPointeeType();
8172   if (PointeeTy->isVoidType()) {
8173     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8174     return !S.getLangOpts().CPlusPlus;
8175   }
8176   if (PointeeTy->isFunctionType()) {
8177     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8178     return !S.getLangOpts().CPlusPlus;
8179   }
8180 
8181   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8182 
8183   return true;
8184 }
8185 
8186 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8187 /// operands.
8188 ///
8189 /// This routine will diagnose any invalid arithmetic on pointer operands much
8190 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8191 /// for emitting a single diagnostic even for operations where both LHS and RHS
8192 /// are (potentially problematic) pointers.
8193 ///
8194 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8195 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8196                                                 Expr *LHSExpr, Expr *RHSExpr) {
8197   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8198   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8199   if (!isLHSPointer && !isRHSPointer) return true;
8200 
8201   QualType LHSPointeeTy, RHSPointeeTy;
8202   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8203   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8204 
8205   // if both are pointers check if operation is valid wrt address spaces
8206   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8207     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8208     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8209     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8210       S.Diag(Loc,
8211              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8212           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8213           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8214       return false;
8215     }
8216   }
8217 
8218   // Check for arithmetic on pointers to incomplete types.
8219   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8220   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8221   if (isLHSVoidPtr || isRHSVoidPtr) {
8222     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8223     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8224     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8225 
8226     return !S.getLangOpts().CPlusPlus;
8227   }
8228 
8229   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8230   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8231   if (isLHSFuncPtr || isRHSFuncPtr) {
8232     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8233     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8234                                                                 RHSExpr);
8235     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8236 
8237     return !S.getLangOpts().CPlusPlus;
8238   }
8239 
8240   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8241     return false;
8242   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8243     return false;
8244 
8245   return true;
8246 }
8247 
8248 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8249 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)8250 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8251                                   Expr *LHSExpr, Expr *RHSExpr) {
8252   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8253   Expr* IndexExpr = RHSExpr;
8254   if (!StrExpr) {
8255     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8256     IndexExpr = LHSExpr;
8257   }
8258 
8259   bool IsStringPlusInt = StrExpr &&
8260       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8261   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8262     return;
8263 
8264   llvm::APSInt index;
8265   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8266     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8267     if (index.isNonNegative() &&
8268         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8269                               index.isUnsigned()))
8270       return;
8271   }
8272 
8273   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8274   Self.Diag(OpLoc, diag::warn_string_plus_int)
8275       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8276 
8277   // Only print a fixit for "str" + int, not for int + "str".
8278   if (IndexExpr == RHSExpr) {
8279     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8280     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8281         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8282         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8283         << FixItHint::CreateInsertion(EndLoc, "]");
8284   } else
8285     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8286 }
8287 
8288 /// \brief Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)8289 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8290                                    Expr *LHSExpr, Expr *RHSExpr) {
8291   const Expr *StringRefExpr = LHSExpr;
8292   const CharacterLiteral *CharExpr =
8293       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8294 
8295   if (!CharExpr) {
8296     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8297     StringRefExpr = RHSExpr;
8298   }
8299 
8300   if (!CharExpr || !StringRefExpr)
8301     return;
8302 
8303   const QualType StringType = StringRefExpr->getType();
8304 
8305   // Return if not a PointerType.
8306   if (!StringType->isAnyPointerType())
8307     return;
8308 
8309   // Return if not a CharacterType.
8310   if (!StringType->getPointeeType()->isAnyCharacterType())
8311     return;
8312 
8313   ASTContext &Ctx = Self.getASTContext();
8314   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8315 
8316   const QualType CharType = CharExpr->getType();
8317   if (!CharType->isAnyCharacterType() &&
8318       CharType->isIntegerType() &&
8319       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8320     Self.Diag(OpLoc, diag::warn_string_plus_char)
8321         << DiagRange << Ctx.CharTy;
8322   } else {
8323     Self.Diag(OpLoc, diag::warn_string_plus_char)
8324         << DiagRange << CharExpr->getType();
8325   }
8326 
8327   // Only print a fixit for str + char, not for char + str.
8328   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8329     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8330     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8331         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8332         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8333         << FixItHint::CreateInsertion(EndLoc, "]");
8334   } else {
8335     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8336   }
8337 }
8338 
8339 /// \brief Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)8340 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8341                                            Expr *LHSExpr, Expr *RHSExpr) {
8342   assert(LHSExpr->getType()->isAnyPointerType());
8343   assert(RHSExpr->getType()->isAnyPointerType());
8344   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8345     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8346     << RHSExpr->getSourceRange();
8347 }
8348 
8349 // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)8350 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8351                                      SourceLocation Loc, BinaryOperatorKind Opc,
8352                                      QualType* CompLHSTy) {
8353   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8354 
8355   if (LHS.get()->getType()->isVectorType() ||
8356       RHS.get()->getType()->isVectorType()) {
8357     QualType compType = CheckVectorOperands(
8358         LHS, RHS, Loc, CompLHSTy,
8359         /*AllowBothBool*/getLangOpts().AltiVec,
8360         /*AllowBoolConversions*/getLangOpts().ZVector);
8361     if (CompLHSTy) *CompLHSTy = compType;
8362     return compType;
8363   }
8364 
8365   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8366   if (LHS.isInvalid() || RHS.isInvalid())
8367     return QualType();
8368 
8369   // Diagnose "string literal" '+' int and string '+' "char literal".
8370   if (Opc == BO_Add) {
8371     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8372     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8373   }
8374 
8375   // handle the common case first (both operands are arithmetic).
8376   if (!compType.isNull() && compType->isArithmeticType()) {
8377     if (CompLHSTy) *CompLHSTy = compType;
8378     return compType;
8379   }
8380 
8381   // Type-checking.  Ultimately the pointer's going to be in PExp;
8382   // note that we bias towards the LHS being the pointer.
8383   Expr *PExp = LHS.get(), *IExp = RHS.get();
8384 
8385   bool isObjCPointer;
8386   if (PExp->getType()->isPointerType()) {
8387     isObjCPointer = false;
8388   } else if (PExp->getType()->isObjCObjectPointerType()) {
8389     isObjCPointer = true;
8390   } else {
8391     std::swap(PExp, IExp);
8392     if (PExp->getType()->isPointerType()) {
8393       isObjCPointer = false;
8394     } else if (PExp->getType()->isObjCObjectPointerType()) {
8395       isObjCPointer = true;
8396     } else {
8397       return InvalidOperands(Loc, LHS, RHS);
8398     }
8399   }
8400   assert(PExp->getType()->isAnyPointerType());
8401 
8402   if (!IExp->getType()->isIntegerType())
8403     return InvalidOperands(Loc, LHS, RHS);
8404 
8405   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8406     return QualType();
8407 
8408   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8409     return QualType();
8410 
8411   // Check array bounds for pointer arithemtic
8412   CheckArrayAccess(PExp, IExp);
8413 
8414   if (CompLHSTy) {
8415     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8416     if (LHSTy.isNull()) {
8417       LHSTy = LHS.get()->getType();
8418       if (LHSTy->isPromotableIntegerType())
8419         LHSTy = Context.getPromotedIntegerType(LHSTy);
8420     }
8421     *CompLHSTy = LHSTy;
8422   }
8423 
8424   return PExp->getType();
8425 }
8426 
8427 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)8428 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8429                                         SourceLocation Loc,
8430                                         QualType* CompLHSTy) {
8431   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8432 
8433   if (LHS.get()->getType()->isVectorType() ||
8434       RHS.get()->getType()->isVectorType()) {
8435     QualType compType = CheckVectorOperands(
8436         LHS, RHS, Loc, CompLHSTy,
8437         /*AllowBothBool*/getLangOpts().AltiVec,
8438         /*AllowBoolConversions*/getLangOpts().ZVector);
8439     if (CompLHSTy) *CompLHSTy = compType;
8440     return compType;
8441   }
8442 
8443   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8444   if (LHS.isInvalid() || RHS.isInvalid())
8445     return QualType();
8446 
8447   // Enforce type constraints: C99 6.5.6p3.
8448 
8449   // Handle the common case first (both operands are arithmetic).
8450   if (!compType.isNull() && compType->isArithmeticType()) {
8451     if (CompLHSTy) *CompLHSTy = compType;
8452     return compType;
8453   }
8454 
8455   // Either ptr - int   or   ptr - ptr.
8456   if (LHS.get()->getType()->isAnyPointerType()) {
8457     QualType lpointee = LHS.get()->getType()->getPointeeType();
8458 
8459     // Diagnose bad cases where we step over interface counts.
8460     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8461         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8462       return QualType();
8463 
8464     // The result type of a pointer-int computation is the pointer type.
8465     if (RHS.get()->getType()->isIntegerType()) {
8466       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8467         return QualType();
8468 
8469       // Check array bounds for pointer arithemtic
8470       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8471                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8472 
8473       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8474       return LHS.get()->getType();
8475     }
8476 
8477     // Handle pointer-pointer subtractions.
8478     if (const PointerType *RHSPTy
8479           = RHS.get()->getType()->getAs<PointerType>()) {
8480       QualType rpointee = RHSPTy->getPointeeType();
8481 
8482       if (getLangOpts().CPlusPlus) {
8483         // Pointee types must be the same: C++ [expr.add]
8484         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8485           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8486         }
8487       } else {
8488         // Pointee types must be compatible C99 6.5.6p3
8489         if (!Context.typesAreCompatible(
8490                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8491                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8492           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8493           return QualType();
8494         }
8495       }
8496 
8497       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8498                                                LHS.get(), RHS.get()))
8499         return QualType();
8500 
8501       // The pointee type may have zero size.  As an extension, a structure or
8502       // union may have zero size or an array may have zero length.  In this
8503       // case subtraction does not make sense.
8504       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8505         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8506         if (ElementSize.isZero()) {
8507           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8508             << rpointee.getUnqualifiedType()
8509             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8510         }
8511       }
8512 
8513       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8514       return Context.getPointerDiffType();
8515     }
8516   }
8517 
8518   return InvalidOperands(Loc, LHS, RHS);
8519 }
8520 
isScopedEnumerationType(QualType T)8521 static bool isScopedEnumerationType(QualType T) {
8522   if (const EnumType *ET = T->getAs<EnumType>())
8523     return ET->getDecl()->isScoped();
8524   return false;
8525 }
8526 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)8527 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8528                                    SourceLocation Loc, BinaryOperatorKind Opc,
8529                                    QualType LHSType) {
8530   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8531   // so skip remaining warnings as we don't want to modify values within Sema.
8532   if (S.getLangOpts().OpenCL)
8533     return;
8534 
8535   llvm::APSInt Right;
8536   // Check right/shifter operand
8537   if (RHS.get()->isValueDependent() ||
8538       !RHS.get()->EvaluateAsInt(Right, S.Context))
8539     return;
8540 
8541   if (Right.isNegative()) {
8542     S.DiagRuntimeBehavior(Loc, RHS.get(),
8543                           S.PDiag(diag::warn_shift_negative)
8544                             << RHS.get()->getSourceRange());
8545     return;
8546   }
8547   llvm::APInt LeftBits(Right.getBitWidth(),
8548                        S.Context.getTypeSize(LHS.get()->getType()));
8549   if (Right.uge(LeftBits)) {
8550     S.DiagRuntimeBehavior(Loc, RHS.get(),
8551                           S.PDiag(diag::warn_shift_gt_typewidth)
8552                             << RHS.get()->getSourceRange());
8553     return;
8554   }
8555   if (Opc != BO_Shl)
8556     return;
8557 
8558   // When left shifting an ICE which is signed, we can check for overflow which
8559   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8560   // integers have defined behavior modulo one more than the maximum value
8561   // representable in the result type, so never warn for those.
8562   llvm::APSInt Left;
8563   if (LHS.get()->isValueDependent() ||
8564       LHSType->hasUnsignedIntegerRepresentation() ||
8565       !LHS.get()->EvaluateAsInt(Left, S.Context))
8566     return;
8567 
8568   // If LHS does not have a signed type and non-negative value
8569   // then, the behavior is undefined. Warn about it.
8570   if (Left.isNegative()) {
8571     S.DiagRuntimeBehavior(Loc, LHS.get(),
8572                           S.PDiag(diag::warn_shift_lhs_negative)
8573                             << LHS.get()->getSourceRange());
8574     return;
8575   }
8576 
8577   llvm::APInt ResultBits =
8578       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8579   if (LeftBits.uge(ResultBits))
8580     return;
8581   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8582   Result = Result.shl(Right);
8583 
8584   // Print the bit representation of the signed integer as an unsigned
8585   // hexadecimal number.
8586   SmallString<40> HexResult;
8587   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8588 
8589   // If we are only missing a sign bit, this is less likely to result in actual
8590   // bugs -- if the result is cast back to an unsigned type, it will have the
8591   // expected value. Thus we place this behind a different warning that can be
8592   // turned off separately if needed.
8593   if (LeftBits == ResultBits - 1) {
8594     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8595         << HexResult << LHSType
8596         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8597     return;
8598   }
8599 
8600   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8601     << HexResult.str() << Result.getMinSignedBits() << LHSType
8602     << Left.getBitWidth() << LHS.get()->getSourceRange()
8603     << RHS.get()->getSourceRange();
8604 }
8605 
8606 /// \brief Return the resulting type when an OpenCL vector is shifted
8607 ///        by a scalar or vector shift amount.
checkOpenCLVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8608 static QualType checkOpenCLVectorShift(Sema &S,
8609                                        ExprResult &LHS, ExprResult &RHS,
8610                                        SourceLocation Loc, bool IsCompAssign) {
8611   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8612   if (!LHS.get()->getType()->isVectorType()) {
8613     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8614       << RHS.get()->getType() << LHS.get()->getType()
8615       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8616     return QualType();
8617   }
8618 
8619   if (!IsCompAssign) {
8620     LHS = S.UsualUnaryConversions(LHS.get());
8621     if (LHS.isInvalid()) return QualType();
8622   }
8623 
8624   RHS = S.UsualUnaryConversions(RHS.get());
8625   if (RHS.isInvalid()) return QualType();
8626 
8627   QualType LHSType = LHS.get()->getType();
8628   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8629   QualType LHSEleType = LHSVecTy->getElementType();
8630 
8631   // Note that RHS might not be a vector.
8632   QualType RHSType = RHS.get()->getType();
8633   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8634   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8635 
8636   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8637   if (!LHSEleType->isIntegerType()) {
8638     S.Diag(Loc, diag::err_typecheck_expect_int)
8639       << LHS.get()->getType() << LHS.get()->getSourceRange();
8640     return QualType();
8641   }
8642 
8643   if (!RHSEleType->isIntegerType()) {
8644     S.Diag(Loc, diag::err_typecheck_expect_int)
8645       << RHS.get()->getType() << RHS.get()->getSourceRange();
8646     return QualType();
8647   }
8648 
8649   if (RHSVecTy) {
8650     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8651     // are applied component-wise. So if RHS is a vector, then ensure
8652     // that the number of elements is the same as LHS...
8653     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8654       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8655         << LHS.get()->getType() << RHS.get()->getType()
8656         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8657       return QualType();
8658     }
8659   } else {
8660     // ...else expand RHS to match the number of elements in LHS.
8661     QualType VecTy =
8662       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8663     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8664   }
8665 
8666   return LHSType;
8667 }
8668 
8669 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)8670 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8671                                   SourceLocation Loc, BinaryOperatorKind Opc,
8672                                   bool IsCompAssign) {
8673   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8674 
8675   // Vector shifts promote their scalar inputs to vector type.
8676   if (LHS.get()->getType()->isVectorType() ||
8677       RHS.get()->getType()->isVectorType()) {
8678     if (LangOpts.OpenCL)
8679       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8680     if (LangOpts.ZVector) {
8681       // The shift operators for the z vector extensions work basically
8682       // like OpenCL shifts, except that neither the LHS nor the RHS is
8683       // allowed to be a "vector bool".
8684       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8685         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8686           return InvalidOperands(Loc, LHS, RHS);
8687       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8688         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8689           return InvalidOperands(Loc, LHS, RHS);
8690       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8691     }
8692     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8693                                /*AllowBothBool*/true,
8694                                /*AllowBoolConversions*/false);
8695   }
8696 
8697   // Shifts don't perform usual arithmetic conversions, they just do integer
8698   // promotions on each operand. C99 6.5.7p3
8699 
8700   // For the LHS, do usual unary conversions, but then reset them away
8701   // if this is a compound assignment.
8702   ExprResult OldLHS = LHS;
8703   LHS = UsualUnaryConversions(LHS.get());
8704   if (LHS.isInvalid())
8705     return QualType();
8706   QualType LHSType = LHS.get()->getType();
8707   if (IsCompAssign) LHS = OldLHS;
8708 
8709   // The RHS is simpler.
8710   RHS = UsualUnaryConversions(RHS.get());
8711   if (RHS.isInvalid())
8712     return QualType();
8713   QualType RHSType = RHS.get()->getType();
8714 
8715   // C99 6.5.7p2: Each of the operands shall have integer type.
8716   if (!LHSType->hasIntegerRepresentation() ||
8717       !RHSType->hasIntegerRepresentation())
8718     return InvalidOperands(Loc, LHS, RHS);
8719 
8720   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8721   // hasIntegerRepresentation() above instead of this.
8722   if (isScopedEnumerationType(LHSType) ||
8723       isScopedEnumerationType(RHSType)) {
8724     return InvalidOperands(Loc, LHS, RHS);
8725   }
8726   // Sanity-check shift operands
8727   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8728 
8729   // "The type of the result is that of the promoted left operand."
8730   return LHSType;
8731 }
8732 
IsWithinTemplateSpecialization(Decl * D)8733 static bool IsWithinTemplateSpecialization(Decl *D) {
8734   if (DeclContext *DC = D->getDeclContext()) {
8735     if (isa<ClassTemplateSpecializationDecl>(DC))
8736       return true;
8737     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8738       return FD->isFunctionTemplateSpecialization();
8739   }
8740   return false;
8741 }
8742 
8743 /// If two different enums are compared, raise a warning.
checkEnumComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8744 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8745                                 Expr *RHS) {
8746   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8747   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8748 
8749   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8750   if (!LHSEnumType)
8751     return;
8752   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8753   if (!RHSEnumType)
8754     return;
8755 
8756   // Ignore anonymous enums.
8757   if (!LHSEnumType->getDecl()->getIdentifier())
8758     return;
8759   if (!RHSEnumType->getDecl()->getIdentifier())
8760     return;
8761 
8762   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8763     return;
8764 
8765   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8766       << LHSStrippedType << RHSStrippedType
8767       << LHS->getSourceRange() << RHS->getSourceRange();
8768 }
8769 
8770 /// \brief Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8771 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8772                                               ExprResult &LHS, ExprResult &RHS,
8773                                               bool IsError) {
8774   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8775                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8776     << LHS.get()->getType() << RHS.get()->getType()
8777     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8778 }
8779 
8780 /// \brief Returns false if the pointers are converted to a composite type,
8781 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)8782 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8783                                            ExprResult &LHS, ExprResult &RHS) {
8784   // C++ [expr.rel]p2:
8785   //   [...] Pointer conversions (4.10) and qualification
8786   //   conversions (4.4) are performed on pointer operands (or on
8787   //   a pointer operand and a null pointer constant) to bring
8788   //   them to their composite pointer type. [...]
8789   //
8790   // C++ [expr.eq]p1 uses the same notion for (in)equality
8791   // comparisons of pointers.
8792 
8793   // C++ [expr.eq]p2:
8794   //   In addition, pointers to members can be compared, or a pointer to
8795   //   member and a null pointer constant. Pointer to member conversions
8796   //   (4.11) and qualification conversions (4.4) are performed to bring
8797   //   them to a common type. If one operand is a null pointer constant,
8798   //   the common type is the type of the other operand. Otherwise, the
8799   //   common type is a pointer to member type similar (4.4) to the type
8800   //   of one of the operands, with a cv-qualification signature (4.4)
8801   //   that is the union of the cv-qualification signatures of the operand
8802   //   types.
8803 
8804   QualType LHSType = LHS.get()->getType();
8805   QualType RHSType = RHS.get()->getType();
8806   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8807          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8808 
8809   bool NonStandardCompositeType = false;
8810   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8811   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8812   if (T.isNull()) {
8813     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8814     return true;
8815   }
8816 
8817   if (NonStandardCompositeType)
8818     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8819       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8820       << RHS.get()->getSourceRange();
8821 
8822   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8823   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8824   return false;
8825 }
8826 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8827 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8828                                                     ExprResult &LHS,
8829                                                     ExprResult &RHS,
8830                                                     bool IsError) {
8831   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8832                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8833     << LHS.get()->getType() << RHS.get()->getType()
8834     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8835 }
8836 
isObjCObjectLiteral(ExprResult & E)8837 static bool isObjCObjectLiteral(ExprResult &E) {
8838   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8839   case Stmt::ObjCArrayLiteralClass:
8840   case Stmt::ObjCDictionaryLiteralClass:
8841   case Stmt::ObjCStringLiteralClass:
8842   case Stmt::ObjCBoxedExprClass:
8843     return true;
8844   default:
8845     // Note that ObjCBoolLiteral is NOT an object literal!
8846     return false;
8847   }
8848 }
8849 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)8850 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8851   const ObjCObjectPointerType *Type =
8852     LHS->getType()->getAs<ObjCObjectPointerType>();
8853 
8854   // If this is not actually an Objective-C object, bail out.
8855   if (!Type)
8856     return false;
8857 
8858   // Get the LHS object's interface type.
8859   QualType InterfaceType = Type->getPointeeType();
8860 
8861   // If the RHS isn't an Objective-C object, bail out.
8862   if (!RHS->getType()->isObjCObjectPointerType())
8863     return false;
8864 
8865   // Try to find the -isEqual: method.
8866   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8867   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8868                                                       InterfaceType,
8869                                                       /*instance=*/true);
8870   if (!Method) {
8871     if (Type->isObjCIdType()) {
8872       // For 'id', just check the global pool.
8873       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8874                                                   /*receiverId=*/true);
8875     } else {
8876       // Check protocols.
8877       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8878                                              /*instance=*/true);
8879     }
8880   }
8881 
8882   if (!Method)
8883     return false;
8884 
8885   QualType T = Method->parameters()[0]->getType();
8886   if (!T->isObjCObjectPointerType())
8887     return false;
8888 
8889   QualType R = Method->getReturnType();
8890   if (!R->isScalarType())
8891     return false;
8892 
8893   return true;
8894 }
8895 
CheckLiteralKind(Expr * FromE)8896 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8897   FromE = FromE->IgnoreParenImpCasts();
8898   switch (FromE->getStmtClass()) {
8899     default:
8900       break;
8901     case Stmt::ObjCStringLiteralClass:
8902       // "string literal"
8903       return LK_String;
8904     case Stmt::ObjCArrayLiteralClass:
8905       // "array literal"
8906       return LK_Array;
8907     case Stmt::ObjCDictionaryLiteralClass:
8908       // "dictionary literal"
8909       return LK_Dictionary;
8910     case Stmt::BlockExprClass:
8911       return LK_Block;
8912     case Stmt::ObjCBoxedExprClass: {
8913       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8914       switch (Inner->getStmtClass()) {
8915         case Stmt::IntegerLiteralClass:
8916         case Stmt::FloatingLiteralClass:
8917         case Stmt::CharacterLiteralClass:
8918         case Stmt::ObjCBoolLiteralExprClass:
8919         case Stmt::CXXBoolLiteralExprClass:
8920           // "numeric literal"
8921           return LK_Numeric;
8922         case Stmt::ImplicitCastExprClass: {
8923           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8924           // Boolean literals can be represented by implicit casts.
8925           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8926             return LK_Numeric;
8927           break;
8928         }
8929         default:
8930           break;
8931       }
8932       return LK_Boxed;
8933     }
8934   }
8935   return LK_None;
8936 }
8937 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)8938 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8939                                           ExprResult &LHS, ExprResult &RHS,
8940                                           BinaryOperator::Opcode Opc){
8941   Expr *Literal;
8942   Expr *Other;
8943   if (isObjCObjectLiteral(LHS)) {
8944     Literal = LHS.get();
8945     Other = RHS.get();
8946   } else {
8947     Literal = RHS.get();
8948     Other = LHS.get();
8949   }
8950 
8951   // Don't warn on comparisons against nil.
8952   Other = Other->IgnoreParenCasts();
8953   if (Other->isNullPointerConstant(S.getASTContext(),
8954                                    Expr::NPC_ValueDependentIsNotNull))
8955     return;
8956 
8957   // This should be kept in sync with warn_objc_literal_comparison.
8958   // LK_String should always be after the other literals, since it has its own
8959   // warning flag.
8960   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8961   assert(LiteralKind != Sema::LK_Block);
8962   if (LiteralKind == Sema::LK_None) {
8963     llvm_unreachable("Unknown Objective-C object literal kind");
8964   }
8965 
8966   if (LiteralKind == Sema::LK_String)
8967     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8968       << Literal->getSourceRange();
8969   else
8970     S.Diag(Loc, diag::warn_objc_literal_comparison)
8971       << LiteralKind << Literal->getSourceRange();
8972 
8973   if (BinaryOperator::isEqualityOp(Opc) &&
8974       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8975     SourceLocation Start = LHS.get()->getLocStart();
8976     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8977     CharSourceRange OpRange =
8978       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8979 
8980     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8981       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8982       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8983       << FixItHint::CreateInsertion(End, "]");
8984   }
8985 }
8986 
diagnoseLogicalNotOnLHSofComparison(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)8987 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8988                                                 ExprResult &RHS,
8989                                                 SourceLocation Loc,
8990                                                 BinaryOperatorKind Opc) {
8991   // Check that left hand side is !something.
8992   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8993   if (!UO || UO->getOpcode() != UO_LNot) return;
8994 
8995   // Only check if the right hand side is non-bool arithmetic type.
8996   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8997 
8998   // Make sure that the something in !something is not bool.
8999   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9000   if (SubExpr->isKnownToHaveBooleanValue()) return;
9001 
9002   // Emit warning.
9003   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9004       << Loc;
9005 
9006   // First note suggest !(x < y)
9007   SourceLocation FirstOpen = SubExpr->getLocStart();
9008   SourceLocation FirstClose = RHS.get()->getLocEnd();
9009   FirstClose = S.getLocForEndOfToken(FirstClose);
9010   if (FirstClose.isInvalid())
9011     FirstOpen = SourceLocation();
9012   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9013       << FixItHint::CreateInsertion(FirstOpen, "(")
9014       << FixItHint::CreateInsertion(FirstClose, ")");
9015 
9016   // Second note suggests (!x) < y
9017   SourceLocation SecondOpen = LHS.get()->getLocStart();
9018   SourceLocation SecondClose = LHS.get()->getLocEnd();
9019   SecondClose = S.getLocForEndOfToken(SecondClose);
9020   if (SecondClose.isInvalid())
9021     SecondOpen = SourceLocation();
9022   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9023       << FixItHint::CreateInsertion(SecondOpen, "(")
9024       << FixItHint::CreateInsertion(SecondClose, ")");
9025 }
9026 
9027 // Get the decl for a simple expression: a reference to a variable,
9028 // an implicit C++ field reference, or an implicit ObjC ivar reference.
getCompareDecl(Expr * E)9029 static ValueDecl *getCompareDecl(Expr *E) {
9030   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9031     return DR->getDecl();
9032   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9033     if (Ivar->isFreeIvar())
9034       return Ivar->getDecl();
9035   }
9036   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9037     if (Mem->isImplicitAccess())
9038       return Mem->getMemberDecl();
9039   }
9040   return nullptr;
9041 }
9042 
9043 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsRelational)9044 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9045                                     SourceLocation Loc, BinaryOperatorKind Opc,
9046                                     bool IsRelational) {
9047   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9048 
9049   // Handle vector comparisons separately.
9050   if (LHS.get()->getType()->isVectorType() ||
9051       RHS.get()->getType()->isVectorType())
9052     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9053 
9054   QualType LHSType = LHS.get()->getType();
9055   QualType RHSType = RHS.get()->getType();
9056 
9057   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9058   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9059 
9060   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9061   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9062 
9063   if (!LHSType->hasFloatingRepresentation() &&
9064       !(LHSType->isBlockPointerType() && IsRelational) &&
9065       !LHS.get()->getLocStart().isMacroID() &&
9066       !RHS.get()->getLocStart().isMacroID() &&
9067       ActiveTemplateInstantiations.empty()) {
9068     // For non-floating point types, check for self-comparisons of the form
9069     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9070     // often indicate logic errors in the program.
9071     //
9072     // NOTE: Don't warn about comparison expressions resulting from macro
9073     // expansion. Also don't warn about comparisons which are only self
9074     // comparisons within a template specialization. The warnings should catch
9075     // obvious cases in the definition of the template anyways. The idea is to
9076     // warn when the typed comparison operator will always evaluate to the same
9077     // result.
9078     ValueDecl *DL = getCompareDecl(LHSStripped);
9079     ValueDecl *DR = getCompareDecl(RHSStripped);
9080     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9081       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9082                           << 0 // self-
9083                           << (Opc == BO_EQ
9084                               || Opc == BO_LE
9085                               || Opc == BO_GE));
9086     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9087                !DL->getType()->isReferenceType() &&
9088                !DR->getType()->isReferenceType()) {
9089         // what is it always going to eval to?
9090         char always_evals_to;
9091         switch(Opc) {
9092         case BO_EQ: // e.g. array1 == array2
9093           always_evals_to = 0; // false
9094           break;
9095         case BO_NE: // e.g. array1 != array2
9096           always_evals_to = 1; // true
9097           break;
9098         default:
9099           // best we can say is 'a constant'
9100           always_evals_to = 2; // e.g. array1 <= array2
9101           break;
9102         }
9103         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9104                             << 1 // array
9105                             << always_evals_to);
9106     }
9107 
9108     if (isa<CastExpr>(LHSStripped))
9109       LHSStripped = LHSStripped->IgnoreParenCasts();
9110     if (isa<CastExpr>(RHSStripped))
9111       RHSStripped = RHSStripped->IgnoreParenCasts();
9112 
9113     // Warn about comparisons against a string constant (unless the other
9114     // operand is null), the user probably wants strcmp.
9115     Expr *literalString = nullptr;
9116     Expr *literalStringStripped = nullptr;
9117     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9118         !RHSStripped->isNullPointerConstant(Context,
9119                                             Expr::NPC_ValueDependentIsNull)) {
9120       literalString = LHS.get();
9121       literalStringStripped = LHSStripped;
9122     } else if ((isa<StringLiteral>(RHSStripped) ||
9123                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9124                !LHSStripped->isNullPointerConstant(Context,
9125                                             Expr::NPC_ValueDependentIsNull)) {
9126       literalString = RHS.get();
9127       literalStringStripped = RHSStripped;
9128     }
9129 
9130     if (literalString) {
9131       DiagRuntimeBehavior(Loc, nullptr,
9132         PDiag(diag::warn_stringcompare)
9133           << isa<ObjCEncodeExpr>(literalStringStripped)
9134           << literalString->getSourceRange());
9135     }
9136   }
9137 
9138   // C99 6.5.8p3 / C99 6.5.9p4
9139   UsualArithmeticConversions(LHS, RHS);
9140   if (LHS.isInvalid() || RHS.isInvalid())
9141     return QualType();
9142 
9143   LHSType = LHS.get()->getType();
9144   RHSType = RHS.get()->getType();
9145 
9146   // The result of comparisons is 'bool' in C++, 'int' in C.
9147   QualType ResultTy = Context.getLogicalOperationType();
9148 
9149   if (IsRelational) {
9150     if (LHSType->isRealType() && RHSType->isRealType())
9151       return ResultTy;
9152   } else {
9153     // Check for comparisons of floating point operands using != and ==.
9154     if (LHSType->hasFloatingRepresentation())
9155       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9156 
9157     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9158       return ResultTy;
9159   }
9160 
9161   const Expr::NullPointerConstantKind LHSNullKind =
9162       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9163   const Expr::NullPointerConstantKind RHSNullKind =
9164       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9165   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9166   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9167 
9168   if (!IsRelational && LHSIsNull != RHSIsNull) {
9169     bool IsEquality = Opc == BO_EQ;
9170     if (RHSIsNull)
9171       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9172                                    RHS.get()->getSourceRange());
9173     else
9174       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9175                                    LHS.get()->getSourceRange());
9176   }
9177 
9178   // All of the following pointer-related warnings are GCC extensions, except
9179   // when handling null pointer constants.
9180   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9181     QualType LCanPointeeTy =
9182       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9183     QualType RCanPointeeTy =
9184       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9185 
9186     if (getLangOpts().CPlusPlus) {
9187       if (LCanPointeeTy == RCanPointeeTy)
9188         return ResultTy;
9189       if (!IsRelational &&
9190           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9191         // Valid unless comparison between non-null pointer and function pointer
9192         // This is a gcc extension compatibility comparison.
9193         // In a SFINAE context, we treat this as a hard error to maintain
9194         // conformance with the C++ standard.
9195         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9196             && !LHSIsNull && !RHSIsNull) {
9197           diagnoseFunctionPointerToVoidComparison(
9198               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9199 
9200           if (isSFINAEContext())
9201             return QualType();
9202 
9203           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9204           return ResultTy;
9205         }
9206       }
9207 
9208       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9209         return QualType();
9210       else
9211         return ResultTy;
9212     }
9213     // C99 6.5.9p2 and C99 6.5.8p2
9214     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9215                                    RCanPointeeTy.getUnqualifiedType())) {
9216       // Valid unless a relational comparison of function pointers
9217       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9218         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9219           << LHSType << RHSType << LHS.get()->getSourceRange()
9220           << RHS.get()->getSourceRange();
9221       }
9222     } else if (!IsRelational &&
9223                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9224       // Valid unless comparison between non-null pointer and function pointer
9225       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9226           && !LHSIsNull && !RHSIsNull)
9227         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9228                                                 /*isError*/false);
9229     } else {
9230       // Invalid
9231       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9232     }
9233     if (LCanPointeeTy != RCanPointeeTy) {
9234       // Treat NULL constant as a special case in OpenCL.
9235       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9236         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9237         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9238           Diag(Loc,
9239                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9240               << LHSType << RHSType << 0 /* comparison */
9241               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9242         }
9243       }
9244       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9245       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9246       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9247                                                : CK_BitCast;
9248       if (LHSIsNull && !RHSIsNull)
9249         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9250       else
9251         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9252     }
9253     return ResultTy;
9254   }
9255 
9256   if (getLangOpts().CPlusPlus) {
9257     // Comparison of nullptr_t with itself.
9258     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9259       return ResultTy;
9260 
9261     // Comparison of pointers with null pointer constants and equality
9262     // comparisons of member pointers to null pointer constants.
9263     if (RHSIsNull &&
9264         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9265          (!IsRelational &&
9266           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9267       RHS = ImpCastExprToType(RHS.get(), LHSType,
9268                         LHSType->isMemberPointerType()
9269                           ? CK_NullToMemberPointer
9270                           : CK_NullToPointer);
9271       return ResultTy;
9272     }
9273     if (LHSIsNull &&
9274         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9275          (!IsRelational &&
9276           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9277       LHS = ImpCastExprToType(LHS.get(), RHSType,
9278                         RHSType->isMemberPointerType()
9279                           ? CK_NullToMemberPointer
9280                           : CK_NullToPointer);
9281       return ResultTy;
9282     }
9283 
9284     // Comparison of member pointers.
9285     if (!IsRelational &&
9286         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9287       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9288         return QualType();
9289       else
9290         return ResultTy;
9291     }
9292 
9293     // Handle scoped enumeration types specifically, since they don't promote
9294     // to integers.
9295     if (LHS.get()->getType()->isEnumeralType() &&
9296         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9297                                        RHS.get()->getType()))
9298       return ResultTy;
9299   }
9300 
9301   // Handle block pointer types.
9302   if (!IsRelational && LHSType->isBlockPointerType() &&
9303       RHSType->isBlockPointerType()) {
9304     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9305     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9306 
9307     if (!LHSIsNull && !RHSIsNull &&
9308         !Context.typesAreCompatible(lpointee, rpointee)) {
9309       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9310         << LHSType << RHSType << LHS.get()->getSourceRange()
9311         << RHS.get()->getSourceRange();
9312     }
9313     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9314     return ResultTy;
9315   }
9316 
9317   // Allow block pointers to be compared with null pointer constants.
9318   if (!IsRelational
9319       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9320           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9321     if (!LHSIsNull && !RHSIsNull) {
9322       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9323              ->getPointeeType()->isVoidType())
9324             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9325                 ->getPointeeType()->isVoidType())))
9326         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9327           << LHSType << RHSType << LHS.get()->getSourceRange()
9328           << RHS.get()->getSourceRange();
9329     }
9330     if (LHSIsNull && !RHSIsNull)
9331       LHS = ImpCastExprToType(LHS.get(), RHSType,
9332                               RHSType->isPointerType() ? CK_BitCast
9333                                 : CK_AnyPointerToBlockPointerCast);
9334     else
9335       RHS = ImpCastExprToType(RHS.get(), LHSType,
9336                               LHSType->isPointerType() ? CK_BitCast
9337                                 : CK_AnyPointerToBlockPointerCast);
9338     return ResultTy;
9339   }
9340 
9341   if (LHSType->isObjCObjectPointerType() ||
9342       RHSType->isObjCObjectPointerType()) {
9343     const PointerType *LPT = LHSType->getAs<PointerType>();
9344     const PointerType *RPT = RHSType->getAs<PointerType>();
9345     if (LPT || RPT) {
9346       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9347       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9348 
9349       if (!LPtrToVoid && !RPtrToVoid &&
9350           !Context.typesAreCompatible(LHSType, RHSType)) {
9351         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9352                                           /*isError*/false);
9353       }
9354       if (LHSIsNull && !RHSIsNull) {
9355         Expr *E = LHS.get();
9356         if (getLangOpts().ObjCAutoRefCount)
9357           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9358         LHS = ImpCastExprToType(E, RHSType,
9359                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9360       }
9361       else {
9362         Expr *E = RHS.get();
9363         if (getLangOpts().ObjCAutoRefCount)
9364           CheckObjCARCConversion(SourceRange(), LHSType, E,
9365                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9366                                  /*DiagnoseCFAudited=*/false, Opc);
9367         RHS = ImpCastExprToType(E, LHSType,
9368                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9369       }
9370       return ResultTy;
9371     }
9372     if (LHSType->isObjCObjectPointerType() &&
9373         RHSType->isObjCObjectPointerType()) {
9374       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9375         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9376                                           /*isError*/false);
9377       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9378         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9379 
9380       if (LHSIsNull && !RHSIsNull)
9381         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9382       else
9383         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9384       return ResultTy;
9385     }
9386   }
9387   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9388       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9389     unsigned DiagID = 0;
9390     bool isError = false;
9391     if (LangOpts.DebuggerSupport) {
9392       // Under a debugger, allow the comparison of pointers to integers,
9393       // since users tend to want to compare addresses.
9394     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9395         (RHSIsNull && RHSType->isIntegerType())) {
9396       if (IsRelational && !getLangOpts().CPlusPlus)
9397         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9398     } else if (IsRelational && !getLangOpts().CPlusPlus)
9399       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9400     else if (getLangOpts().CPlusPlus) {
9401       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9402       isError = true;
9403     } else
9404       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9405 
9406     if (DiagID) {
9407       Diag(Loc, DiagID)
9408         << LHSType << RHSType << LHS.get()->getSourceRange()
9409         << RHS.get()->getSourceRange();
9410       if (isError)
9411         return QualType();
9412     }
9413 
9414     if (LHSType->isIntegerType())
9415       LHS = ImpCastExprToType(LHS.get(), RHSType,
9416                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9417     else
9418       RHS = ImpCastExprToType(RHS.get(), LHSType,
9419                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9420     return ResultTy;
9421   }
9422 
9423   // Handle block pointers.
9424   if (!IsRelational && RHSIsNull
9425       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9426     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9427     return ResultTy;
9428   }
9429   if (!IsRelational && LHSIsNull
9430       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9431     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9432     return ResultTy;
9433   }
9434 
9435   return InvalidOperands(Loc, LHS, RHS);
9436 }
9437 
9438 
9439 // Return a signed type that is of identical size and number of elements.
9440 // For floating point vectors, return an integer type of identical size
9441 // and number of elements.
GetSignedVectorType(QualType V)9442 QualType Sema::GetSignedVectorType(QualType V) {
9443   const VectorType *VTy = V->getAs<VectorType>();
9444   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9445   if (TypeSize == Context.getTypeSize(Context.CharTy))
9446     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9447   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9448     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9449   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9450     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9451   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9452     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9453   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9454          "Unhandled vector element size in vector compare");
9455   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9456 }
9457 
9458 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9459 /// operates on extended vector types.  Instead of producing an IntTy result,
9460 /// like a scalar comparison, a vector comparison produces a vector of integer
9461 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsRelational)9462 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9463                                           SourceLocation Loc,
9464                                           bool IsRelational) {
9465   // Check to make sure we're operating on vectors of the same type and width,
9466   // Allowing one side to be a scalar of element type.
9467   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9468                               /*AllowBothBool*/true,
9469                               /*AllowBoolConversions*/getLangOpts().ZVector);
9470   if (vType.isNull())
9471     return vType;
9472 
9473   QualType LHSType = LHS.get()->getType();
9474 
9475   // If AltiVec, the comparison results in a numeric type, i.e.
9476   // bool for C++, int for C
9477   if (getLangOpts().AltiVec &&
9478       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9479     return Context.getLogicalOperationType();
9480 
9481   // For non-floating point types, check for self-comparisons of the form
9482   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9483   // often indicate logic errors in the program.
9484   if (!LHSType->hasFloatingRepresentation() &&
9485       ActiveTemplateInstantiations.empty()) {
9486     if (DeclRefExpr* DRL
9487           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9488       if (DeclRefExpr* DRR
9489             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9490         if (DRL->getDecl() == DRR->getDecl())
9491           DiagRuntimeBehavior(Loc, nullptr,
9492                               PDiag(diag::warn_comparison_always)
9493                                 << 0 // self-
9494                                 << 2 // "a constant"
9495                               );
9496   }
9497 
9498   // Check for comparisons of floating point operands using != and ==.
9499   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9500     assert (RHS.get()->getType()->hasFloatingRepresentation());
9501     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9502   }
9503 
9504   // Return a signed type for the vector.
9505   return GetSignedVectorType(vType);
9506 }
9507 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)9508 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9509                                           SourceLocation Loc) {
9510   // Ensure that either both operands are of the same vector type, or
9511   // one operand is of a vector type and the other is of its element type.
9512   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9513                                        /*AllowBothBool*/true,
9514                                        /*AllowBoolConversions*/false);
9515   if (vType.isNull())
9516     return InvalidOperands(Loc, LHS, RHS);
9517   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9518       vType->hasFloatingRepresentation())
9519     return InvalidOperands(Loc, LHS, RHS);
9520 
9521   return GetSignedVectorType(LHS.get()->getType());
9522 }
9523 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)9524 inline QualType Sema::CheckBitwiseOperands(
9525   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9526   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9527 
9528   if (LHS.get()->getType()->isVectorType() ||
9529       RHS.get()->getType()->isVectorType()) {
9530     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9531         RHS.get()->getType()->hasIntegerRepresentation())
9532       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9533                         /*AllowBothBool*/true,
9534                         /*AllowBoolConversions*/getLangOpts().ZVector);
9535     return InvalidOperands(Loc, LHS, RHS);
9536   }
9537 
9538   ExprResult LHSResult = LHS, RHSResult = RHS;
9539   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9540                                                  IsCompAssign);
9541   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9542     return QualType();
9543   LHS = LHSResult.get();
9544   RHS = RHSResult.get();
9545 
9546   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9547     return compType;
9548   return InvalidOperands(Loc, LHS, RHS);
9549 }
9550 
9551 // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)9552 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9553                                            SourceLocation Loc,
9554                                            BinaryOperatorKind Opc) {
9555   // Check vector operands differently.
9556   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9557     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9558 
9559   // Diagnose cases where the user write a logical and/or but probably meant a
9560   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9561   // is a constant.
9562   if (LHS.get()->getType()->isIntegerType() &&
9563       !LHS.get()->getType()->isBooleanType() &&
9564       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9565       // Don't warn in macros or template instantiations.
9566       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9567     // If the RHS can be constant folded, and if it constant folds to something
9568     // that isn't 0 or 1 (which indicate a potential logical operation that
9569     // happened to fold to true/false) then warn.
9570     // Parens on the RHS are ignored.
9571     llvm::APSInt Result;
9572     if (RHS.get()->EvaluateAsInt(Result, Context))
9573       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9574            !RHS.get()->getExprLoc().isMacroID()) ||
9575           (Result != 0 && Result != 1)) {
9576         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9577           << RHS.get()->getSourceRange()
9578           << (Opc == BO_LAnd ? "&&" : "||");
9579         // Suggest replacing the logical operator with the bitwise version
9580         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9581             << (Opc == BO_LAnd ? "&" : "|")
9582             << FixItHint::CreateReplacement(SourceRange(
9583                                                  Loc, getLocForEndOfToken(Loc)),
9584                                             Opc == BO_LAnd ? "&" : "|");
9585         if (Opc == BO_LAnd)
9586           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9587           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9588               << FixItHint::CreateRemoval(
9589                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9590                               RHS.get()->getLocEnd()));
9591       }
9592   }
9593 
9594   if (!Context.getLangOpts().CPlusPlus) {
9595     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9596     // not operate on the built-in scalar and vector float types.
9597     if (Context.getLangOpts().OpenCL &&
9598         Context.getLangOpts().OpenCLVersion < 120) {
9599       if (LHS.get()->getType()->isFloatingType() ||
9600           RHS.get()->getType()->isFloatingType())
9601         return InvalidOperands(Loc, LHS, RHS);
9602     }
9603 
9604     LHS = UsualUnaryConversions(LHS.get());
9605     if (LHS.isInvalid())
9606       return QualType();
9607 
9608     RHS = UsualUnaryConversions(RHS.get());
9609     if (RHS.isInvalid())
9610       return QualType();
9611 
9612     if (!LHS.get()->getType()->isScalarType() ||
9613         !RHS.get()->getType()->isScalarType())
9614       return InvalidOperands(Loc, LHS, RHS);
9615 
9616     return Context.IntTy;
9617   }
9618 
9619   // The following is safe because we only use this method for
9620   // non-overloadable operands.
9621 
9622   // C++ [expr.log.and]p1
9623   // C++ [expr.log.or]p1
9624   // The operands are both contextually converted to type bool.
9625   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9626   if (LHSRes.isInvalid())
9627     return InvalidOperands(Loc, LHS, RHS);
9628   LHS = LHSRes;
9629 
9630   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9631   if (RHSRes.isInvalid())
9632     return InvalidOperands(Loc, LHS, RHS);
9633   RHS = RHSRes;
9634 
9635   // C++ [expr.log.and]p2
9636   // C++ [expr.log.or]p2
9637   // The result is a bool.
9638   return Context.BoolTy;
9639 }
9640 
IsReadonlyMessage(Expr * E,Sema & S)9641 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9642   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9643   if (!ME) return false;
9644   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9645   ObjCMessageExpr *Base =
9646     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9647   if (!Base) return false;
9648   return Base->getMethodDecl() != nullptr;
9649 }
9650 
9651 /// Is the given expression (which must be 'const') a reference to a
9652 /// variable which was originally non-const, but which has become
9653 /// 'const' due to being captured within a block?
9654 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)9655 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9656   assert(E->isLValue() && E->getType().isConstQualified());
9657   E = E->IgnoreParens();
9658 
9659   // Must be a reference to a declaration from an enclosing scope.
9660   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9661   if (!DRE) return NCCK_None;
9662   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9663 
9664   // The declaration must be a variable which is not declared 'const'.
9665   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9666   if (!var) return NCCK_None;
9667   if (var->getType().isConstQualified()) return NCCK_None;
9668   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9669 
9670   // Decide whether the first capture was for a block or a lambda.
9671   DeclContext *DC = S.CurContext, *Prev = nullptr;
9672   // Decide whether the first capture was for a block or a lambda.
9673   while (DC) {
9674     // For init-capture, it is possible that the variable belongs to the
9675     // template pattern of the current context.
9676     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9677       if (var->isInitCapture() &&
9678           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9679         break;
9680     if (DC == var->getDeclContext())
9681       break;
9682     Prev = DC;
9683     DC = DC->getParent();
9684   }
9685   // Unless we have an init-capture, we've gone one step too far.
9686   if (!var->isInitCapture())
9687     DC = Prev;
9688   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9689 }
9690 
IsTypeModifiable(QualType Ty,bool IsDereference)9691 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9692   Ty = Ty.getNonReferenceType();
9693   if (IsDereference && Ty->isPointerType())
9694     Ty = Ty->getPointeeType();
9695   return !Ty.isConstQualified();
9696 }
9697 
9698 /// Emit the "read-only variable not assignable" error and print notes to give
9699 /// more information about why the variable is not assignable, such as pointing
9700 /// to the declaration of a const variable, showing that a method is const, or
9701 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)9702 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9703                                     SourceLocation Loc) {
9704   // Update err_typecheck_assign_const and note_typecheck_assign_const
9705   // when this enum is changed.
9706   enum {
9707     ConstFunction,
9708     ConstVariable,
9709     ConstMember,
9710     ConstMethod,
9711     ConstUnknown,  // Keep as last element
9712   };
9713 
9714   SourceRange ExprRange = E->getSourceRange();
9715 
9716   // Only emit one error on the first const found.  All other consts will emit
9717   // a note to the error.
9718   bool DiagnosticEmitted = false;
9719 
9720   // Track if the current expression is the result of a derefence, and if the
9721   // next checked expression is the result of a derefence.
9722   bool IsDereference = false;
9723   bool NextIsDereference = false;
9724 
9725   // Loop to process MemberExpr chains.
9726   while (true) {
9727     IsDereference = NextIsDereference;
9728     NextIsDereference = false;
9729 
9730     E = E->IgnoreParenImpCasts();
9731     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9732       NextIsDereference = ME->isArrow();
9733       const ValueDecl *VD = ME->getMemberDecl();
9734       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9735         // Mutable fields can be modified even if the class is const.
9736         if (Field->isMutable()) {
9737           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9738           break;
9739         }
9740 
9741         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9742           if (!DiagnosticEmitted) {
9743             S.Diag(Loc, diag::err_typecheck_assign_const)
9744                 << ExprRange << ConstMember << false /*static*/ << Field
9745                 << Field->getType();
9746             DiagnosticEmitted = true;
9747           }
9748           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9749               << ConstMember << false /*static*/ << Field << Field->getType()
9750               << Field->getSourceRange();
9751         }
9752         E = ME->getBase();
9753         continue;
9754       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9755         if (VDecl->getType().isConstQualified()) {
9756           if (!DiagnosticEmitted) {
9757             S.Diag(Loc, diag::err_typecheck_assign_const)
9758                 << ExprRange << ConstMember << true /*static*/ << VDecl
9759                 << VDecl->getType();
9760             DiagnosticEmitted = true;
9761           }
9762           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9763               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9764               << VDecl->getSourceRange();
9765         }
9766         // Static fields do not inherit constness from parents.
9767         break;
9768       }
9769       break;
9770     } // End MemberExpr
9771     break;
9772   }
9773 
9774   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9775     // Function calls
9776     const FunctionDecl *FD = CE->getDirectCallee();
9777     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9778       if (!DiagnosticEmitted) {
9779         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9780                                                       << ConstFunction << FD;
9781         DiagnosticEmitted = true;
9782       }
9783       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9784              diag::note_typecheck_assign_const)
9785           << ConstFunction << FD << FD->getReturnType()
9786           << FD->getReturnTypeSourceRange();
9787     }
9788   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9789     // Point to variable declaration.
9790     if (const ValueDecl *VD = DRE->getDecl()) {
9791       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9792         if (!DiagnosticEmitted) {
9793           S.Diag(Loc, diag::err_typecheck_assign_const)
9794               << ExprRange << ConstVariable << VD << VD->getType();
9795           DiagnosticEmitted = true;
9796         }
9797         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9798             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9799       }
9800     }
9801   } else if (isa<CXXThisExpr>(E)) {
9802     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9803       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9804         if (MD->isConst()) {
9805           if (!DiagnosticEmitted) {
9806             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9807                                                           << ConstMethod << MD;
9808             DiagnosticEmitted = true;
9809           }
9810           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9811               << ConstMethod << MD << MD->getSourceRange();
9812         }
9813       }
9814     }
9815   }
9816 
9817   if (DiagnosticEmitted)
9818     return;
9819 
9820   // Can't determine a more specific message, so display the generic error.
9821   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9822 }
9823 
9824 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9825 /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)9826 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9827   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9828 
9829   S.CheckShadowingDeclModification(E, Loc);
9830 
9831   SourceLocation OrigLoc = Loc;
9832   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9833                                                               &Loc);
9834   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9835     IsLV = Expr::MLV_InvalidMessageExpression;
9836   if (IsLV == Expr::MLV_Valid)
9837     return false;
9838 
9839   unsigned DiagID = 0;
9840   bool NeedType = false;
9841   switch (IsLV) { // C99 6.5.16p2
9842   case Expr::MLV_ConstQualified:
9843     // Use a specialized diagnostic when we're assigning to an object
9844     // from an enclosing function or block.
9845     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9846       if (NCCK == NCCK_Block)
9847         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9848       else
9849         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9850       break;
9851     }
9852 
9853     // In ARC, use some specialized diagnostics for occasions where we
9854     // infer 'const'.  These are always pseudo-strong variables.
9855     if (S.getLangOpts().ObjCAutoRefCount) {
9856       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9857       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9858         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9859 
9860         // Use the normal diagnostic if it's pseudo-__strong but the
9861         // user actually wrote 'const'.
9862         if (var->isARCPseudoStrong() &&
9863             (!var->getTypeSourceInfo() ||
9864              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9865           // There are two pseudo-strong cases:
9866           //  - self
9867           ObjCMethodDecl *method = S.getCurMethodDecl();
9868           if (method && var == method->getSelfDecl())
9869             DiagID = method->isClassMethod()
9870               ? diag::err_typecheck_arc_assign_self_class_method
9871               : diag::err_typecheck_arc_assign_self;
9872 
9873           //  - fast enumeration variables
9874           else
9875             DiagID = diag::err_typecheck_arr_assign_enumeration;
9876 
9877           SourceRange Assign;
9878           if (Loc != OrigLoc)
9879             Assign = SourceRange(OrigLoc, OrigLoc);
9880           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9881           // We need to preserve the AST regardless, so migration tool
9882           // can do its job.
9883           return false;
9884         }
9885       }
9886     }
9887 
9888     // If none of the special cases above are triggered, then this is a
9889     // simple const assignment.
9890     if (DiagID == 0) {
9891       DiagnoseConstAssignment(S, E, Loc);
9892       return true;
9893     }
9894 
9895     break;
9896   case Expr::MLV_ConstAddrSpace:
9897     DiagnoseConstAssignment(S, E, Loc);
9898     return true;
9899   case Expr::MLV_ArrayType:
9900   case Expr::MLV_ArrayTemporary:
9901     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9902     NeedType = true;
9903     break;
9904   case Expr::MLV_NotObjectType:
9905     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9906     NeedType = true;
9907     break;
9908   case Expr::MLV_LValueCast:
9909     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9910     break;
9911   case Expr::MLV_Valid:
9912     llvm_unreachable("did not take early return for MLV_Valid");
9913   case Expr::MLV_InvalidExpression:
9914   case Expr::MLV_MemberFunction:
9915   case Expr::MLV_ClassTemporary:
9916     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9917     break;
9918   case Expr::MLV_IncompleteType:
9919   case Expr::MLV_IncompleteVoidType:
9920     return S.RequireCompleteType(Loc, E->getType(),
9921              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9922   case Expr::MLV_DuplicateVectorComponents:
9923     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9924     break;
9925   case Expr::MLV_NoSetterProperty:
9926     llvm_unreachable("readonly properties should be processed differently");
9927   case Expr::MLV_InvalidMessageExpression:
9928     DiagID = diag::error_readonly_message_assignment;
9929     break;
9930   case Expr::MLV_SubObjCPropertySetting:
9931     DiagID = diag::error_no_subobject_property_setting;
9932     break;
9933   }
9934 
9935   SourceRange Assign;
9936   if (Loc != OrigLoc)
9937     Assign = SourceRange(OrigLoc, OrigLoc);
9938   if (NeedType)
9939     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9940   else
9941     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9942   return true;
9943 }
9944 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)9945 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9946                                          SourceLocation Loc,
9947                                          Sema &Sema) {
9948   // C / C++ fields
9949   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9950   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9951   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9952     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9953       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9954   }
9955 
9956   // Objective-C instance variables
9957   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9958   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9959   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9960     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9961     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9962     if (RL && RR && RL->getDecl() == RR->getDecl())
9963       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9964   }
9965 }
9966 
9967 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)9968 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9969                                        SourceLocation Loc,
9970                                        QualType CompoundType) {
9971   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9972 
9973   // Verify that LHS is a modifiable lvalue, and emit error if not.
9974   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9975     return QualType();
9976 
9977   QualType LHSType = LHSExpr->getType();
9978   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9979                                              CompoundType;
9980   AssignConvertType ConvTy;
9981   if (CompoundType.isNull()) {
9982     Expr *RHSCheck = RHS.get();
9983 
9984     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9985 
9986     QualType LHSTy(LHSType);
9987     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9988     if (RHS.isInvalid())
9989       return QualType();
9990     // Special case of NSObject attributes on c-style pointer types.
9991     if (ConvTy == IncompatiblePointer &&
9992         ((Context.isObjCNSObjectType(LHSType) &&
9993           RHSType->isObjCObjectPointerType()) ||
9994          (Context.isObjCNSObjectType(RHSType) &&
9995           LHSType->isObjCObjectPointerType())))
9996       ConvTy = Compatible;
9997 
9998     if (ConvTy == Compatible &&
9999         LHSType->isObjCObjectType())
10000         Diag(Loc, diag::err_objc_object_assignment)
10001           << LHSType;
10002 
10003     // If the RHS is a unary plus or minus, check to see if they = and + are
10004     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10005     // instead of "x += 4".
10006     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10007       RHSCheck = ICE->getSubExpr();
10008     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10009       if ((UO->getOpcode() == UO_Plus ||
10010            UO->getOpcode() == UO_Minus) &&
10011           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10012           // Only if the two operators are exactly adjacent.
10013           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10014           // And there is a space or other character before the subexpr of the
10015           // unary +/-.  We don't want to warn on "x=-1".
10016           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10017           UO->getSubExpr()->getLocStart().isFileID()) {
10018         Diag(Loc, diag::warn_not_compound_assign)
10019           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10020           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10021       }
10022     }
10023 
10024     if (ConvTy == Compatible) {
10025       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10026         // Warn about retain cycles where a block captures the LHS, but
10027         // not if the LHS is a simple variable into which the block is
10028         // being stored...unless that variable can be captured by reference!
10029         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10030         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10031         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10032           checkRetainCycles(LHSExpr, RHS.get());
10033 
10034         // It is safe to assign a weak reference into a strong variable.
10035         // Although this code can still have problems:
10036         //   id x = self.weakProp;
10037         //   id y = self.weakProp;
10038         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10039         // paths through the function. This should be revisited if
10040         // -Wrepeated-use-of-weak is made flow-sensitive.
10041         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10042                              RHS.get()->getLocStart()))
10043           getCurFunction()->markSafeWeakUse(RHS.get());
10044 
10045       } else if (getLangOpts().ObjCAutoRefCount) {
10046         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10047       }
10048     }
10049   } else {
10050     // Compound assignment "x += y"
10051     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10052   }
10053 
10054   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10055                                RHS.get(), AA_Assigning))
10056     return QualType();
10057 
10058   CheckForNullPointerDereference(*this, LHSExpr);
10059 
10060   // C99 6.5.16p3: The type of an assignment expression is the type of the
10061   // left operand unless the left operand has qualified type, in which case
10062   // it is the unqualified version of the type of the left operand.
10063   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10064   // is converted to the type of the assignment expression (above).
10065   // C++ 5.17p1: the type of the assignment expression is that of its left
10066   // operand.
10067   return (getLangOpts().CPlusPlus
10068           ? LHSType : LHSType.getUnqualifiedType());
10069 }
10070 
10071 // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)10072 static bool IgnoreCommaOperand(const Expr *E) {
10073   E = E->IgnoreParens();
10074 
10075   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10076     if (CE->getCastKind() == CK_ToVoid) {
10077       return true;
10078     }
10079   }
10080 
10081   return false;
10082 }
10083 
10084 // Look for instances where it is likely the comma operator is confused with
10085 // another operator.  There is a whitelist of acceptable expressions for the
10086 // left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)10087 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10088   // No warnings in macros
10089   if (Loc.isMacroID())
10090     return;
10091 
10092   // Don't warn in template instantiations.
10093   if (!ActiveTemplateInstantiations.empty())
10094     return;
10095 
10096   // Scope isn't fine-grained enough to whitelist the specific cases, so
10097   // instead, skip more than needed, then call back into here with the
10098   // CommaVisitor in SemaStmt.cpp.
10099   // The whitelisted locations are the initialization and increment portions
10100   // of a for loop.  The additional checks are on the condition of
10101   // if statements, do/while loops, and for loops.
10102   const unsigned ForIncrementFlags =
10103       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10104   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10105   const unsigned ScopeFlags = getCurScope()->getFlags();
10106   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10107       (ScopeFlags & ForInitFlags) == ForInitFlags)
10108     return;
10109 
10110   // If there are multiple comma operators used together, get the RHS of the
10111   // of the comma operator as the LHS.
10112   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10113     if (BO->getOpcode() != BO_Comma)
10114       break;
10115     LHS = BO->getRHS();
10116   }
10117 
10118   // Only allow some expressions on LHS to not warn.
10119   if (IgnoreCommaOperand(LHS))
10120     return;
10121 
10122   Diag(Loc, diag::warn_comma_operator);
10123   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10124       << LHS->getSourceRange()
10125       << FixItHint::CreateInsertion(LHS->getLocStart(),
10126                                     LangOpts.CPlusPlus ? "static_cast<void>("
10127                                                        : "(void)(")
10128       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10129                                     ")");
10130 }
10131 
10132 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)10133 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10134                                    SourceLocation Loc) {
10135   LHS = S.CheckPlaceholderExpr(LHS.get());
10136   RHS = S.CheckPlaceholderExpr(RHS.get());
10137   if (LHS.isInvalid() || RHS.isInvalid())
10138     return QualType();
10139 
10140   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10141   // operands, but not unary promotions.
10142   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10143 
10144   // So we treat the LHS as a ignored value, and in C++ we allow the
10145   // containing site to determine what should be done with the RHS.
10146   LHS = S.IgnoredValueConversions(LHS.get());
10147   if (LHS.isInvalid())
10148     return QualType();
10149 
10150   S.DiagnoseUnusedExprResult(LHS.get());
10151 
10152   if (!S.getLangOpts().CPlusPlus) {
10153     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10154     if (RHS.isInvalid())
10155       return QualType();
10156     if (!RHS.get()->getType()->isVoidType())
10157       S.RequireCompleteType(Loc, RHS.get()->getType(),
10158                             diag::err_incomplete_type);
10159   }
10160 
10161   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10162     S.DiagnoseCommaOperator(LHS.get(), Loc);
10163 
10164   return RHS.get()->getType();
10165 }
10166 
10167 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10168 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)10169 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10170                                                ExprValueKind &VK,
10171                                                ExprObjectKind &OK,
10172                                                SourceLocation OpLoc,
10173                                                bool IsInc, bool IsPrefix) {
10174   if (Op->isTypeDependent())
10175     return S.Context.DependentTy;
10176 
10177   QualType ResType = Op->getType();
10178   // Atomic types can be used for increment / decrement where the non-atomic
10179   // versions can, so ignore the _Atomic() specifier for the purpose of
10180   // checking.
10181   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10182     ResType = ResAtomicType->getValueType();
10183 
10184   assert(!ResType.isNull() && "no type for increment/decrement expression");
10185 
10186   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10187     // Decrement of bool is not allowed.
10188     if (!IsInc) {
10189       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10190       return QualType();
10191     }
10192     // Increment of bool sets it to true, but is deprecated.
10193     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10194                                               : diag::warn_increment_bool)
10195       << Op->getSourceRange();
10196   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10197     // Error on enum increments and decrements in C++ mode
10198     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10199     return QualType();
10200   } else if (ResType->isRealType()) {
10201     // OK!
10202   } else if (ResType->isPointerType()) {
10203     // C99 6.5.2.4p2, 6.5.6p2
10204     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10205       return QualType();
10206   } else if (ResType->isObjCObjectPointerType()) {
10207     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10208     // Otherwise, we just need a complete type.
10209     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10210         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10211       return QualType();
10212   } else if (ResType->isAnyComplexType()) {
10213     // C99 does not support ++/-- on complex types, we allow as an extension.
10214     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10215       << ResType << Op->getSourceRange();
10216   } else if (ResType->isPlaceholderType()) {
10217     ExprResult PR = S.CheckPlaceholderExpr(Op);
10218     if (PR.isInvalid()) return QualType();
10219     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10220                                           IsInc, IsPrefix);
10221   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10222     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10223   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10224              (ResType->getAs<VectorType>()->getVectorKind() !=
10225               VectorType::AltiVecBool)) {
10226     // The z vector extensions allow ++ and -- for non-bool vectors.
10227   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10228             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10229     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10230   } else {
10231     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10232       << ResType << int(IsInc) << Op->getSourceRange();
10233     return QualType();
10234   }
10235   // At this point, we know we have a real, complex or pointer type.
10236   // Now make sure the operand is a modifiable lvalue.
10237   if (CheckForModifiableLvalue(Op, OpLoc, S))
10238     return QualType();
10239   // In C++, a prefix increment is the same type as the operand. Otherwise
10240   // (in C or with postfix), the increment is the unqualified type of the
10241   // operand.
10242   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10243     VK = VK_LValue;
10244     OK = Op->getObjectKind();
10245     return ResType;
10246   } else {
10247     VK = VK_RValue;
10248     return ResType.getUnqualifiedType();
10249   }
10250 }
10251 
10252 
10253 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10254 /// This routine allows us to typecheck complex/recursive expressions
10255 /// where the declaration is needed for type checking. We only need to
10256 /// handle cases when the expression references a function designator
10257 /// or is an lvalue. Here are some examples:
10258 ///  - &(x) => x
10259 ///  - &*****f => f for f a function designator.
10260 ///  - &s.xx => s
10261 ///  - &s.zz[1].yy -> s, if zz is an array
10262 ///  - *(x + 1) -> x, if x is an array
10263 ///  - &"123"[2] -> 0
10264 ///  - & __real__ x -> x
getPrimaryDecl(Expr * E)10265 static ValueDecl *getPrimaryDecl(Expr *E) {
10266   switch (E->getStmtClass()) {
10267   case Stmt::DeclRefExprClass:
10268     return cast<DeclRefExpr>(E)->getDecl();
10269   case Stmt::MemberExprClass:
10270     // If this is an arrow operator, the address is an offset from
10271     // the base's value, so the object the base refers to is
10272     // irrelevant.
10273     if (cast<MemberExpr>(E)->isArrow())
10274       return nullptr;
10275     // Otherwise, the expression refers to a part of the base
10276     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10277   case Stmt::ArraySubscriptExprClass: {
10278     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10279     // promotion of register arrays earlier.
10280     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10281     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10282       if (ICE->getSubExpr()->getType()->isArrayType())
10283         return getPrimaryDecl(ICE->getSubExpr());
10284     }
10285     return nullptr;
10286   }
10287   case Stmt::UnaryOperatorClass: {
10288     UnaryOperator *UO = cast<UnaryOperator>(E);
10289 
10290     switch(UO->getOpcode()) {
10291     case UO_Real:
10292     case UO_Imag:
10293     case UO_Extension:
10294       return getPrimaryDecl(UO->getSubExpr());
10295     default:
10296       return nullptr;
10297     }
10298   }
10299   case Stmt::ParenExprClass:
10300     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10301   case Stmt::ImplicitCastExprClass:
10302     // If the result of an implicit cast is an l-value, we care about
10303     // the sub-expression; otherwise, the result here doesn't matter.
10304     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10305   default:
10306     return nullptr;
10307   }
10308 }
10309 
10310 namespace {
10311   enum {
10312     AO_Bit_Field = 0,
10313     AO_Vector_Element = 1,
10314     AO_Property_Expansion = 2,
10315     AO_Register_Variable = 3,
10316     AO_No_Error = 4
10317   };
10318 }
10319 /// \brief Diagnose invalid operand for address of operations.
10320 ///
10321 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)10322 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10323                                          Expr *E, unsigned Type) {
10324   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10325 }
10326 
10327 /// CheckAddressOfOperand - The operand of & must be either a function
10328 /// designator or an lvalue designating an object. If it is an lvalue, the
10329 /// object cannot be declared with storage class register or be a bit field.
10330 /// Note: The usual conversions are *not* applied to the operand of the &
10331 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10332 /// In C++, the operand might be an overloaded function name, in which case
10333 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)10334 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10335   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10336     if (PTy->getKind() == BuiltinType::Overload) {
10337       Expr *E = OrigOp.get()->IgnoreParens();
10338       if (!isa<OverloadExpr>(E)) {
10339         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10340         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10341           << OrigOp.get()->getSourceRange();
10342         return QualType();
10343       }
10344 
10345       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10346       if (isa<UnresolvedMemberExpr>(Ovl))
10347         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10348           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10349             << OrigOp.get()->getSourceRange();
10350           return QualType();
10351         }
10352 
10353       return Context.OverloadTy;
10354     }
10355 
10356     if (PTy->getKind() == BuiltinType::UnknownAny)
10357       return Context.UnknownAnyTy;
10358 
10359     if (PTy->getKind() == BuiltinType::BoundMember) {
10360       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10361         << OrigOp.get()->getSourceRange();
10362       return QualType();
10363     }
10364 
10365     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10366     if (OrigOp.isInvalid()) return QualType();
10367   }
10368 
10369   if (OrigOp.get()->isTypeDependent())
10370     return Context.DependentTy;
10371 
10372   assert(!OrigOp.get()->getType()->isPlaceholderType());
10373 
10374   // Make sure to ignore parentheses in subsequent checks
10375   Expr *op = OrigOp.get()->IgnoreParens();
10376 
10377   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10378   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10379     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10380     return QualType();
10381   }
10382 
10383   if (getLangOpts().C99) {
10384     // Implement C99-only parts of addressof rules.
10385     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10386       if (uOp->getOpcode() == UO_Deref)
10387         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10388         // (assuming the deref expression is valid).
10389         return uOp->getSubExpr()->getType();
10390     }
10391     // Technically, there should be a check for array subscript
10392     // expressions here, but the result of one is always an lvalue anyway.
10393   }
10394   ValueDecl *dcl = getPrimaryDecl(op);
10395 
10396   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10397     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10398                                            op->getLocStart()))
10399       return QualType();
10400 
10401   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10402   unsigned AddressOfError = AO_No_Error;
10403 
10404   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10405     bool sfinae = (bool)isSFINAEContext();
10406     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10407                                   : diag::ext_typecheck_addrof_temporary)
10408       << op->getType() << op->getSourceRange();
10409     if (sfinae)
10410       return QualType();
10411     // Materialize the temporary as an lvalue so that we can take its address.
10412     OrigOp = op =
10413         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10414   } else if (isa<ObjCSelectorExpr>(op)) {
10415     return Context.getPointerType(op->getType());
10416   } else if (lval == Expr::LV_MemberFunction) {
10417     // If it's an instance method, make a member pointer.
10418     // The expression must have exactly the form &A::foo.
10419 
10420     // If the underlying expression isn't a decl ref, give up.
10421     if (!isa<DeclRefExpr>(op)) {
10422       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10423         << OrigOp.get()->getSourceRange();
10424       return QualType();
10425     }
10426     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10427     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10428 
10429     // The id-expression was parenthesized.
10430     if (OrigOp.get() != DRE) {
10431       Diag(OpLoc, diag::err_parens_pointer_member_function)
10432         << OrigOp.get()->getSourceRange();
10433 
10434     // The method was named without a qualifier.
10435     } else if (!DRE->getQualifier()) {
10436       if (MD->getParent()->getName().empty())
10437         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10438           << op->getSourceRange();
10439       else {
10440         SmallString<32> Str;
10441         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10442         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10443           << op->getSourceRange()
10444           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10445       }
10446     }
10447 
10448     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10449     if (isa<CXXDestructorDecl>(MD))
10450       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10451 
10452     QualType MPTy = Context.getMemberPointerType(
10453         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10454     // Under the MS ABI, lock down the inheritance model now.
10455     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10456       (void)isCompleteType(OpLoc, MPTy);
10457     return MPTy;
10458   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10459     // C99 6.5.3.2p1
10460     // The operand must be either an l-value or a function designator
10461     if (!op->getType()->isFunctionType()) {
10462       // Use a special diagnostic for loads from property references.
10463       if (isa<PseudoObjectExpr>(op)) {
10464         AddressOfError = AO_Property_Expansion;
10465       } else {
10466         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10467           << op->getType() << op->getSourceRange();
10468         return QualType();
10469       }
10470     }
10471   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10472     // The operand cannot be a bit-field
10473     AddressOfError = AO_Bit_Field;
10474   } else if (op->getObjectKind() == OK_VectorComponent) {
10475     // The operand cannot be an element of a vector
10476     AddressOfError = AO_Vector_Element;
10477   } else if (dcl) { // C99 6.5.3.2p1
10478     // We have an lvalue with a decl. Make sure the decl is not declared
10479     // with the register storage-class specifier.
10480     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10481       // in C++ it is not error to take address of a register
10482       // variable (c++03 7.1.1P3)
10483       if (vd->getStorageClass() == SC_Register &&
10484           !getLangOpts().CPlusPlus) {
10485         AddressOfError = AO_Register_Variable;
10486       }
10487     } else if (isa<MSPropertyDecl>(dcl)) {
10488       AddressOfError = AO_Property_Expansion;
10489     } else if (isa<FunctionTemplateDecl>(dcl)) {
10490       return Context.OverloadTy;
10491     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10492       // Okay: we can take the address of a field.
10493       // Could be a pointer to member, though, if there is an explicit
10494       // scope qualifier for the class.
10495       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10496         DeclContext *Ctx = dcl->getDeclContext();
10497         if (Ctx && Ctx->isRecord()) {
10498           if (dcl->getType()->isReferenceType()) {
10499             Diag(OpLoc,
10500                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10501               << dcl->getDeclName() << dcl->getType();
10502             return QualType();
10503           }
10504 
10505           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10506             Ctx = Ctx->getParent();
10507 
10508           QualType MPTy = Context.getMemberPointerType(
10509               op->getType(),
10510               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10511           // Under the MS ABI, lock down the inheritance model now.
10512           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10513             (void)isCompleteType(OpLoc, MPTy);
10514           return MPTy;
10515         }
10516       }
10517     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10518       llvm_unreachable("Unknown/unexpected decl type");
10519   }
10520 
10521   if (AddressOfError != AO_No_Error) {
10522     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10523     return QualType();
10524   }
10525 
10526   if (lval == Expr::LV_IncompleteVoidType) {
10527     // Taking the address of a void variable is technically illegal, but we
10528     // allow it in cases which are otherwise valid.
10529     // Example: "extern void x; void* y = &x;".
10530     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10531   }
10532 
10533   // If the operand has type "type", the result has type "pointer to type".
10534   if (op->getType()->isObjCObjectType())
10535     return Context.getObjCObjectPointerType(op->getType());
10536 
10537   return Context.getPointerType(op->getType());
10538 }
10539 
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)10540 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10541   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10542   if (!DRE)
10543     return;
10544   const Decl *D = DRE->getDecl();
10545   if (!D)
10546     return;
10547   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10548   if (!Param)
10549     return;
10550   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10551     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10552       return;
10553   if (FunctionScopeInfo *FD = S.getCurFunction())
10554     if (!FD->ModifiedNonNullParams.count(Param))
10555       FD->ModifiedNonNullParams.insert(Param);
10556 }
10557 
10558 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)10559 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10560                                         SourceLocation OpLoc) {
10561   if (Op->isTypeDependent())
10562     return S.Context.DependentTy;
10563 
10564   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10565   if (ConvResult.isInvalid())
10566     return QualType();
10567   Op = ConvResult.get();
10568   QualType OpTy = Op->getType();
10569   QualType Result;
10570 
10571   if (isa<CXXReinterpretCastExpr>(Op)) {
10572     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10573     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10574                                      Op->getSourceRange());
10575   }
10576 
10577   if (const PointerType *PT = OpTy->getAs<PointerType>())
10578   {
10579     Result = PT->getPointeeType();
10580   }
10581   else if (const ObjCObjectPointerType *OPT =
10582              OpTy->getAs<ObjCObjectPointerType>())
10583     Result = OPT->getPointeeType();
10584   else {
10585     ExprResult PR = S.CheckPlaceholderExpr(Op);
10586     if (PR.isInvalid()) return QualType();
10587     if (PR.get() != Op)
10588       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10589   }
10590 
10591   if (Result.isNull()) {
10592     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10593       << OpTy << Op->getSourceRange();
10594     return QualType();
10595   }
10596 
10597   // Note that per both C89 and C99, indirection is always legal, even if Result
10598   // is an incomplete type or void.  It would be possible to warn about
10599   // dereferencing a void pointer, but it's completely well-defined, and such a
10600   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10601   // for pointers to 'void' but is fine for any other pointer type:
10602   //
10603   // C++ [expr.unary.op]p1:
10604   //   [...] the expression to which [the unary * operator] is applied shall
10605   //   be a pointer to an object type, or a pointer to a function type
10606   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10607     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10608       << OpTy << Op->getSourceRange();
10609 
10610   // Dereferences are usually l-values...
10611   VK = VK_LValue;
10612 
10613   // ...except that certain expressions are never l-values in C.
10614   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10615     VK = VK_RValue;
10616 
10617   return Result;
10618 }
10619 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)10620 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10621   BinaryOperatorKind Opc;
10622   switch (Kind) {
10623   default: llvm_unreachable("Unknown binop!");
10624   case tok::periodstar:           Opc = BO_PtrMemD; break;
10625   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10626   case tok::star:                 Opc = BO_Mul; break;
10627   case tok::slash:                Opc = BO_Div; break;
10628   case tok::percent:              Opc = BO_Rem; break;
10629   case tok::plus:                 Opc = BO_Add; break;
10630   case tok::minus:                Opc = BO_Sub; break;
10631   case tok::lessless:             Opc = BO_Shl; break;
10632   case tok::greatergreater:       Opc = BO_Shr; break;
10633   case tok::lessequal:            Opc = BO_LE; break;
10634   case tok::less:                 Opc = BO_LT; break;
10635   case tok::greaterequal:         Opc = BO_GE; break;
10636   case tok::greater:              Opc = BO_GT; break;
10637   case tok::exclaimequal:         Opc = BO_NE; break;
10638   case tok::equalequal:           Opc = BO_EQ; break;
10639   case tok::amp:                  Opc = BO_And; break;
10640   case tok::caret:                Opc = BO_Xor; break;
10641   case tok::pipe:                 Opc = BO_Or; break;
10642   case tok::ampamp:               Opc = BO_LAnd; break;
10643   case tok::pipepipe:             Opc = BO_LOr; break;
10644   case tok::equal:                Opc = BO_Assign; break;
10645   case tok::starequal:            Opc = BO_MulAssign; break;
10646   case tok::slashequal:           Opc = BO_DivAssign; break;
10647   case tok::percentequal:         Opc = BO_RemAssign; break;
10648   case tok::plusequal:            Opc = BO_AddAssign; break;
10649   case tok::minusequal:           Opc = BO_SubAssign; break;
10650   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10651   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10652   case tok::ampequal:             Opc = BO_AndAssign; break;
10653   case tok::caretequal:           Opc = BO_XorAssign; break;
10654   case tok::pipeequal:            Opc = BO_OrAssign; break;
10655   case tok::comma:                Opc = BO_Comma; break;
10656   }
10657   return Opc;
10658 }
10659 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)10660 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10661   tok::TokenKind Kind) {
10662   UnaryOperatorKind Opc;
10663   switch (Kind) {
10664   default: llvm_unreachable("Unknown unary op!");
10665   case tok::plusplus:     Opc = UO_PreInc; break;
10666   case tok::minusminus:   Opc = UO_PreDec; break;
10667   case tok::amp:          Opc = UO_AddrOf; break;
10668   case tok::star:         Opc = UO_Deref; break;
10669   case tok::plus:         Opc = UO_Plus; break;
10670   case tok::minus:        Opc = UO_Minus; break;
10671   case tok::tilde:        Opc = UO_Not; break;
10672   case tok::exclaim:      Opc = UO_LNot; break;
10673   case tok::kw___real:    Opc = UO_Real; break;
10674   case tok::kw___imag:    Opc = UO_Imag; break;
10675   case tok::kw___extension__: Opc = UO_Extension; break;
10676   }
10677   return Opc;
10678 }
10679 
10680 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10681 /// This warning is only emitted for builtin assignment operations. It is also
10682 /// suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc)10683 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10684                                    SourceLocation OpLoc) {
10685   if (!S.ActiveTemplateInstantiations.empty())
10686     return;
10687   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10688     return;
10689   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10690   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10691   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10692   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10693   if (!LHSDeclRef || !RHSDeclRef ||
10694       LHSDeclRef->getLocation().isMacroID() ||
10695       RHSDeclRef->getLocation().isMacroID())
10696     return;
10697   const ValueDecl *LHSDecl =
10698     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10699   const ValueDecl *RHSDecl =
10700     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10701   if (LHSDecl != RHSDecl)
10702     return;
10703   if (LHSDecl->getType().isVolatileQualified())
10704     return;
10705   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10706     if (RefTy->getPointeeType().isVolatileQualified())
10707       return;
10708 
10709   S.Diag(OpLoc, diag::warn_self_assignment)
10710       << LHSDeclRef->getType()
10711       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10712 }
10713 
10714 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10715 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)10716 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10717                                           SourceLocation OpLoc) {
10718   if (!S.getLangOpts().ObjC1)
10719     return;
10720 
10721   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10722   const Expr *LHS = L.get();
10723   const Expr *RHS = R.get();
10724 
10725   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10726     ObjCPointerExpr = LHS;
10727     OtherExpr = RHS;
10728   }
10729   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10730     ObjCPointerExpr = RHS;
10731     OtherExpr = LHS;
10732   }
10733 
10734   // This warning is deliberately made very specific to reduce false
10735   // positives with logic that uses '&' for hashing.  This logic mainly
10736   // looks for code trying to introspect into tagged pointers, which
10737   // code should generally never do.
10738   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10739     unsigned Diag = diag::warn_objc_pointer_masking;
10740     // Determine if we are introspecting the result of performSelectorXXX.
10741     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10742     // Special case messages to -performSelector and friends, which
10743     // can return non-pointer values boxed in a pointer value.
10744     // Some clients may wish to silence warnings in this subcase.
10745     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10746       Selector S = ME->getSelector();
10747       StringRef SelArg0 = S.getNameForSlot(0);
10748       if (SelArg0.startswith("performSelector"))
10749         Diag = diag::warn_objc_pointer_masking_performSelector;
10750     }
10751 
10752     S.Diag(OpLoc, Diag)
10753       << ObjCPointerExpr->getSourceRange();
10754   }
10755 }
10756 
getDeclFromExpr(Expr * E)10757 static NamedDecl *getDeclFromExpr(Expr *E) {
10758   if (!E)
10759     return nullptr;
10760   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10761     return DRE->getDecl();
10762   if (auto *ME = dyn_cast<MemberExpr>(E))
10763     return ME->getMemberDecl();
10764   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10765     return IRE->getDecl();
10766   return nullptr;
10767 }
10768 
10769 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10770 /// operator @p Opc at location @c TokLoc. This routine only supports
10771 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)10772 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10773                                     BinaryOperatorKind Opc,
10774                                     Expr *LHSExpr, Expr *RHSExpr) {
10775   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10776     // The syntax only allows initializer lists on the RHS of assignment,
10777     // so we don't need to worry about accepting invalid code for
10778     // non-assignment operators.
10779     // C++11 5.17p9:
10780     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10781     //   of x = {} is x = T().
10782     InitializationKind Kind =
10783         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10784     InitializedEntity Entity =
10785         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10786     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10787     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10788     if (Init.isInvalid())
10789       return Init;
10790     RHSExpr = Init.get();
10791   }
10792 
10793   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10794   QualType ResultTy;     // Result type of the binary operator.
10795   // The following two variables are used for compound assignment operators
10796   QualType CompLHSTy;    // Type of LHS after promotions for computation
10797   QualType CompResultTy; // Type of computation result
10798   ExprValueKind VK = VK_RValue;
10799   ExprObjectKind OK = OK_Ordinary;
10800 
10801   if (!getLangOpts().CPlusPlus) {
10802     // C cannot handle TypoExpr nodes on either side of a binop because it
10803     // doesn't handle dependent types properly, so make sure any TypoExprs have
10804     // been dealt with before checking the operands.
10805     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10806     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10807       if (Opc != BO_Assign)
10808         return ExprResult(E);
10809       // Avoid correcting the RHS to the same Expr as the LHS.
10810       Decl *D = getDeclFromExpr(E);
10811       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10812     });
10813     if (!LHS.isUsable() || !RHS.isUsable())
10814       return ExprError();
10815   }
10816 
10817   if (getLangOpts().OpenCL) {
10818     QualType LHSTy = LHSExpr->getType();
10819     QualType RHSTy = RHSExpr->getType();
10820     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10821     // the ATOMIC_VAR_INIT macro.
10822     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10823       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10824       if (BO_Assign == Opc)
10825         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10826       else
10827         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10828       return ExprError();
10829     }
10830 
10831     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10832     // only with a builtin functions and therefore should be disallowed here.
10833     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10834         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10835         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10836         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10837       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10838       return ExprError();
10839     }
10840   }
10841 
10842   switch (Opc) {
10843   case BO_Assign:
10844     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10845     if (getLangOpts().CPlusPlus &&
10846         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10847       VK = LHS.get()->getValueKind();
10848       OK = LHS.get()->getObjectKind();
10849     }
10850     if (!ResultTy.isNull()) {
10851       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10852       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10853     }
10854     RecordModifiableNonNullParam(*this, LHS.get());
10855     break;
10856   case BO_PtrMemD:
10857   case BO_PtrMemI:
10858     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10859                                             Opc == BO_PtrMemI);
10860     break;
10861   case BO_Mul:
10862   case BO_Div:
10863     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10864                                            Opc == BO_Div);
10865     break;
10866   case BO_Rem:
10867     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10868     break;
10869   case BO_Add:
10870     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10871     break;
10872   case BO_Sub:
10873     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10874     break;
10875   case BO_Shl:
10876   case BO_Shr:
10877     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10878     break;
10879   case BO_LE:
10880   case BO_LT:
10881   case BO_GE:
10882   case BO_GT:
10883     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10884     break;
10885   case BO_EQ:
10886   case BO_NE:
10887     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10888     break;
10889   case BO_And:
10890     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10891   case BO_Xor:
10892   case BO_Or:
10893     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10894     break;
10895   case BO_LAnd:
10896   case BO_LOr:
10897     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10898     break;
10899   case BO_MulAssign:
10900   case BO_DivAssign:
10901     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10902                                                Opc == BO_DivAssign);
10903     CompLHSTy = CompResultTy;
10904     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10905       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10906     break;
10907   case BO_RemAssign:
10908     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10909     CompLHSTy = CompResultTy;
10910     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10911       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10912     break;
10913   case BO_AddAssign:
10914     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10915     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10916       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10917     break;
10918   case BO_SubAssign:
10919     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10920     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10921       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10922     break;
10923   case BO_ShlAssign:
10924   case BO_ShrAssign:
10925     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10926     CompLHSTy = CompResultTy;
10927     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10928       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10929     break;
10930   case BO_AndAssign:
10931   case BO_OrAssign: // fallthrough
10932     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10933   case BO_XorAssign:
10934     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10935     CompLHSTy = CompResultTy;
10936     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10937       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10938     break;
10939   case BO_Comma:
10940     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10941     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10942       VK = RHS.get()->getValueKind();
10943       OK = RHS.get()->getObjectKind();
10944     }
10945     break;
10946   }
10947   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10948     return ExprError();
10949 
10950   // Check for array bounds violations for both sides of the BinaryOperator
10951   CheckArrayAccess(LHS.get());
10952   CheckArrayAccess(RHS.get());
10953 
10954   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10955     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10956                                                  &Context.Idents.get("object_setClass"),
10957                                                  SourceLocation(), LookupOrdinaryName);
10958     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10959       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10960       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10961       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10962       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10963       FixItHint::CreateInsertion(RHSLocEnd, ")");
10964     }
10965     else
10966       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10967   }
10968   else if (const ObjCIvarRefExpr *OIRE =
10969            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10970     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10971 
10972   if (CompResultTy.isNull())
10973     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10974                                         OK, OpLoc, FPFeatures.fp_contract);
10975   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10976       OK_ObjCProperty) {
10977     VK = VK_LValue;
10978     OK = LHS.get()->getObjectKind();
10979   }
10980   return new (Context) CompoundAssignOperator(
10981       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10982       OpLoc, FPFeatures.fp_contract);
10983 }
10984 
10985 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10986 /// operators are mixed in a way that suggests that the programmer forgot that
10987 /// comparison operators have higher precedence. The most typical example of
10988 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10989 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10990                                       SourceLocation OpLoc, Expr *LHSExpr,
10991                                       Expr *RHSExpr) {
10992   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10993   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10994 
10995   // Check that one of the sides is a comparison operator and the other isn't.
10996   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10997   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10998   if (isLeftComp == isRightComp)
10999     return;
11000 
11001   // Bitwise operations are sometimes used as eager logical ops.
11002   // Don't diagnose this.
11003   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11004   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11005   if (isLeftBitwise || isRightBitwise)
11006     return;
11007 
11008   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11009                                                    OpLoc)
11010                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11011   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11012   SourceRange ParensRange = isLeftComp ?
11013       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11014     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11015 
11016   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11017     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11018   SuggestParentheses(Self, OpLoc,
11019     Self.PDiag(diag::note_precedence_silence) << OpStr,
11020     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11021   SuggestParentheses(Self, OpLoc,
11022     Self.PDiag(diag::note_precedence_bitwise_first)
11023       << BinaryOperator::getOpcodeStr(Opc),
11024     ParensRange);
11025 }
11026 
11027 /// \brief It accepts a '&&' expr that is inside a '||' one.
11028 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11029 /// in parentheses.
11030 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)11031 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11032                                        BinaryOperator *Bop) {
11033   assert(Bop->getOpcode() == BO_LAnd);
11034   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11035       << Bop->getSourceRange() << OpLoc;
11036   SuggestParentheses(Self, Bop->getOperatorLoc(),
11037     Self.PDiag(diag::note_precedence_silence)
11038       << Bop->getOpcodeStr(),
11039     Bop->getSourceRange());
11040 }
11041 
11042 /// \brief Returns true if the given expression can be evaluated as a constant
11043 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)11044 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11045   bool Res;
11046   return !E->isValueDependent() &&
11047          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11048 }
11049 
11050 /// \brief Returns true if the given expression can be evaluated as a constant
11051 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)11052 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11053   bool Res;
11054   return !E->isValueDependent() &&
11055          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11056 }
11057 
11058 /// \brief Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11059 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11060                                              Expr *LHSExpr, Expr *RHSExpr) {
11061   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11062     if (Bop->getOpcode() == BO_LAnd) {
11063       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11064       if (EvaluatesAsFalse(S, RHSExpr))
11065         return;
11066       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11067       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11068         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11069     } else if (Bop->getOpcode() == BO_LOr) {
11070       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11071         // If it's "a || b && 1 || c" we didn't warn earlier for
11072         // "a || b && 1", but warn now.
11073         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11074           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11075       }
11076     }
11077   }
11078 }
11079 
11080 /// \brief Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11081 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11082                                              Expr *LHSExpr, Expr *RHSExpr) {
11083   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11084     if (Bop->getOpcode() == BO_LAnd) {
11085       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11086       if (EvaluatesAsFalse(S, LHSExpr))
11087         return;
11088       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11089       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11090         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11091     }
11092   }
11093 }
11094 
11095 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11096 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11097 /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)11098 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11099                                          SourceLocation OpLoc, Expr *SubExpr) {
11100   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11101     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11102       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11103         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11104         << Bop->getSourceRange() << OpLoc;
11105       SuggestParentheses(S, Bop->getOperatorLoc(),
11106         S.PDiag(diag::note_precedence_silence)
11107           << Bop->getOpcodeStr(),
11108         Bop->getSourceRange());
11109     }
11110   }
11111 }
11112 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)11113 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11114                                     Expr *SubExpr, StringRef Shift) {
11115   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11116     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11117       StringRef Op = Bop->getOpcodeStr();
11118       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11119           << Bop->getSourceRange() << OpLoc << Shift << Op;
11120       SuggestParentheses(S, Bop->getOperatorLoc(),
11121           S.PDiag(diag::note_precedence_silence) << Op,
11122           Bop->getSourceRange());
11123     }
11124   }
11125 }
11126 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11127 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11128                                  Expr *LHSExpr, Expr *RHSExpr) {
11129   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11130   if (!OCE)
11131     return;
11132 
11133   FunctionDecl *FD = OCE->getDirectCallee();
11134   if (!FD || !FD->isOverloadedOperator())
11135     return;
11136 
11137   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11138   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11139     return;
11140 
11141   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11142       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11143       << (Kind == OO_LessLess);
11144   SuggestParentheses(S, OCE->getOperatorLoc(),
11145                      S.PDiag(diag::note_precedence_silence)
11146                          << (Kind == OO_LessLess ? "<<" : ">>"),
11147                      OCE->getSourceRange());
11148   SuggestParentheses(S, OpLoc,
11149                      S.PDiag(diag::note_evaluate_comparison_first),
11150                      SourceRange(OCE->getArg(1)->getLocStart(),
11151                                  RHSExpr->getLocEnd()));
11152 }
11153 
11154 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11155 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)11156 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11157                                     SourceLocation OpLoc, Expr *LHSExpr,
11158                                     Expr *RHSExpr){
11159   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11160   if (BinaryOperator::isBitwiseOp(Opc))
11161     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11162 
11163   // Diagnose "arg1 & arg2 | arg3"
11164   if ((Opc == BO_Or || Opc == BO_Xor) &&
11165       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11166     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11167     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11168   }
11169 
11170   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11171   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11172   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11173     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11174     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11175   }
11176 
11177   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11178       || Opc == BO_Shr) {
11179     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11180     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11181     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11182   }
11183 
11184   // Warn on overloaded shift operators and comparisons, such as:
11185   // cout << 5 == 4;
11186   if (BinaryOperator::isComparisonOp(Opc))
11187     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11188 }
11189 
11190 // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)11191 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11192                             tok::TokenKind Kind,
11193                             Expr *LHSExpr, Expr *RHSExpr) {
11194   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11195   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11196   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11197 
11198   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11199   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11200 
11201   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11202 }
11203 
11204 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)11205 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11206                                        BinaryOperatorKind Opc,
11207                                        Expr *LHS, Expr *RHS) {
11208   // Find all of the overloaded operators visible from this
11209   // point. We perform both an operator-name lookup from the local
11210   // scope and an argument-dependent lookup based on the types of
11211   // the arguments.
11212   UnresolvedSet<16> Functions;
11213   OverloadedOperatorKind OverOp
11214     = BinaryOperator::getOverloadedOperator(Opc);
11215   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11216     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11217                                    RHS->getType(), Functions);
11218 
11219   // Build the (potentially-overloaded, potentially-dependent)
11220   // binary operation.
11221   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11222 }
11223 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)11224 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11225                             BinaryOperatorKind Opc,
11226                             Expr *LHSExpr, Expr *RHSExpr) {
11227   // We want to end up calling one of checkPseudoObjectAssignment
11228   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11229   // both expressions are overloadable or either is type-dependent),
11230   // or CreateBuiltinBinOp (in any other case).  We also want to get
11231   // any placeholder types out of the way.
11232 
11233   // Handle pseudo-objects in the LHS.
11234   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11235     // Assignments with a pseudo-object l-value need special analysis.
11236     if (pty->getKind() == BuiltinType::PseudoObject &&
11237         BinaryOperator::isAssignmentOp(Opc))
11238       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11239 
11240     // Don't resolve overloads if the other type is overloadable.
11241     if (pty->getKind() == BuiltinType::Overload) {
11242       // We can't actually test that if we still have a placeholder,
11243       // though.  Fortunately, none of the exceptions we see in that
11244       // code below are valid when the LHS is an overload set.  Note
11245       // that an overload set can be dependently-typed, but it never
11246       // instantiates to having an overloadable type.
11247       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11248       if (resolvedRHS.isInvalid()) return ExprError();
11249       RHSExpr = resolvedRHS.get();
11250 
11251       if (RHSExpr->isTypeDependent() ||
11252           RHSExpr->getType()->isOverloadableType())
11253         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11254     }
11255 
11256     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11257     if (LHS.isInvalid()) return ExprError();
11258     LHSExpr = LHS.get();
11259   }
11260 
11261   // Handle pseudo-objects in the RHS.
11262   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11263     // An overload in the RHS can potentially be resolved by the type
11264     // being assigned to.
11265     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11266       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11267         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11268 
11269       if (LHSExpr->getType()->isOverloadableType())
11270         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11271 
11272       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11273     }
11274 
11275     // Don't resolve overloads if the other type is overloadable.
11276     if (pty->getKind() == BuiltinType::Overload &&
11277         LHSExpr->getType()->isOverloadableType())
11278       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11279 
11280     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11281     if (!resolvedRHS.isUsable()) return ExprError();
11282     RHSExpr = resolvedRHS.get();
11283   }
11284 
11285   if (getLangOpts().CPlusPlus) {
11286     // If either expression is type-dependent, always build an
11287     // overloaded op.
11288     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11289       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11290 
11291     // Otherwise, build an overloaded op if either expression has an
11292     // overloadable type.
11293     if (LHSExpr->getType()->isOverloadableType() ||
11294         RHSExpr->getType()->isOverloadableType())
11295       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11296   }
11297 
11298   // Build a built-in binary operation.
11299   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11300 }
11301 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)11302 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11303                                       UnaryOperatorKind Opc,
11304                                       Expr *InputExpr) {
11305   ExprResult Input = InputExpr;
11306   ExprValueKind VK = VK_RValue;
11307   ExprObjectKind OK = OK_Ordinary;
11308   QualType resultType;
11309   if (getLangOpts().OpenCL) {
11310     QualType Ty = InputExpr->getType();
11311     // The only legal unary operation for atomics is '&'.
11312     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11313     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11314     // only with a builtin functions and therefore should be disallowed here.
11315         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11316         || Ty->isBlockPointerType())) {
11317       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11318                        << InputExpr->getType()
11319                        << Input.get()->getSourceRange());
11320     }
11321   }
11322   switch (Opc) {
11323   case UO_PreInc:
11324   case UO_PreDec:
11325   case UO_PostInc:
11326   case UO_PostDec:
11327     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11328                                                 OpLoc,
11329                                                 Opc == UO_PreInc ||
11330                                                 Opc == UO_PostInc,
11331                                                 Opc == UO_PreInc ||
11332                                                 Opc == UO_PreDec);
11333     break;
11334   case UO_AddrOf:
11335     resultType = CheckAddressOfOperand(Input, OpLoc);
11336     RecordModifiableNonNullParam(*this, InputExpr);
11337     break;
11338   case UO_Deref: {
11339     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11340     if (Input.isInvalid()) return ExprError();
11341     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11342     break;
11343   }
11344   case UO_Plus:
11345   case UO_Minus:
11346     Input = UsualUnaryConversions(Input.get());
11347     if (Input.isInvalid()) return ExprError();
11348     resultType = Input.get()->getType();
11349     if (resultType->isDependentType())
11350       break;
11351     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11352       break;
11353     else if (resultType->isVectorType() &&
11354              // The z vector extensions don't allow + or - with bool vectors.
11355              (!Context.getLangOpts().ZVector ||
11356               resultType->getAs<VectorType>()->getVectorKind() !=
11357               VectorType::AltiVecBool))
11358       break;
11359     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11360              Opc == UO_Plus &&
11361              resultType->isPointerType())
11362       break;
11363 
11364     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11365       << resultType << Input.get()->getSourceRange());
11366 
11367   case UO_Not: // bitwise complement
11368     Input = UsualUnaryConversions(Input.get());
11369     if (Input.isInvalid())
11370       return ExprError();
11371     resultType = Input.get()->getType();
11372     if (resultType->isDependentType())
11373       break;
11374     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11375     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11376       // C99 does not support '~' for complex conjugation.
11377       Diag(OpLoc, diag::ext_integer_complement_complex)
11378           << resultType << Input.get()->getSourceRange();
11379     else if (resultType->hasIntegerRepresentation())
11380       break;
11381     else if (resultType->isExtVectorType()) {
11382       if (Context.getLangOpts().OpenCL) {
11383         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11384         // on vector float types.
11385         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11386         if (!T->isIntegerType())
11387           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11388                            << resultType << Input.get()->getSourceRange());
11389       }
11390       break;
11391     } else {
11392       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11393                        << resultType << Input.get()->getSourceRange());
11394     }
11395     break;
11396 
11397   case UO_LNot: // logical negation
11398     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11399     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11400     if (Input.isInvalid()) return ExprError();
11401     resultType = Input.get()->getType();
11402 
11403     // Though we still have to promote half FP to float...
11404     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11405       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11406       resultType = Context.FloatTy;
11407     }
11408 
11409     if (resultType->isDependentType())
11410       break;
11411     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11412       // C99 6.5.3.3p1: ok, fallthrough;
11413       if (Context.getLangOpts().CPlusPlus) {
11414         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11415         // operand contextually converted to bool.
11416         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11417                                   ScalarTypeToBooleanCastKind(resultType));
11418       } else if (Context.getLangOpts().OpenCL &&
11419                  Context.getLangOpts().OpenCLVersion < 120) {
11420         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11421         // operate on scalar float types.
11422         if (!resultType->isIntegerType())
11423           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11424                            << resultType << Input.get()->getSourceRange());
11425       }
11426     } else if (resultType->isExtVectorType()) {
11427       if (Context.getLangOpts().OpenCL &&
11428           Context.getLangOpts().OpenCLVersion < 120) {
11429         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11430         // operate on vector float types.
11431         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11432         if (!T->isIntegerType())
11433           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11434                            << resultType << Input.get()->getSourceRange());
11435       }
11436       // Vector logical not returns the signed variant of the operand type.
11437       resultType = GetSignedVectorType(resultType);
11438       break;
11439     } else {
11440       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11441         << resultType << Input.get()->getSourceRange());
11442     }
11443 
11444     // LNot always has type int. C99 6.5.3.3p5.
11445     // In C++, it's bool. C++ 5.3.1p8
11446     resultType = Context.getLogicalOperationType();
11447     break;
11448   case UO_Real:
11449   case UO_Imag:
11450     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11451     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11452     // complex l-values to ordinary l-values and all other values to r-values.
11453     if (Input.isInvalid()) return ExprError();
11454     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11455       if (Input.get()->getValueKind() != VK_RValue &&
11456           Input.get()->getObjectKind() == OK_Ordinary)
11457         VK = Input.get()->getValueKind();
11458     } else if (!getLangOpts().CPlusPlus) {
11459       // In C, a volatile scalar is read by __imag. In C++, it is not.
11460       Input = DefaultLvalueConversion(Input.get());
11461     }
11462     break;
11463   case UO_Extension:
11464   case UO_Coawait:
11465     resultType = Input.get()->getType();
11466     VK = Input.get()->getValueKind();
11467     OK = Input.get()->getObjectKind();
11468     break;
11469   }
11470   if (resultType.isNull() || Input.isInvalid())
11471     return ExprError();
11472 
11473   // Check for array bounds violations in the operand of the UnaryOperator,
11474   // except for the '*' and '&' operators that have to be handled specially
11475   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11476   // that are explicitly defined as valid by the standard).
11477   if (Opc != UO_AddrOf && Opc != UO_Deref)
11478     CheckArrayAccess(Input.get());
11479 
11480   return new (Context)
11481       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11482 }
11483 
11484 /// \brief Determine whether the given expression is a qualified member
11485 /// access expression, of a form that could be turned into a pointer to member
11486 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)11487 static bool isQualifiedMemberAccess(Expr *E) {
11488   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11489     if (!DRE->getQualifier())
11490       return false;
11491 
11492     ValueDecl *VD = DRE->getDecl();
11493     if (!VD->isCXXClassMember())
11494       return false;
11495 
11496     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11497       return true;
11498     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11499       return Method->isInstance();
11500 
11501     return false;
11502   }
11503 
11504   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11505     if (!ULE->getQualifier())
11506       return false;
11507 
11508     for (NamedDecl *D : ULE->decls()) {
11509       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11510         if (Method->isInstance())
11511           return true;
11512       } else {
11513         // Overload set does not contain methods.
11514         break;
11515       }
11516     }
11517 
11518     return false;
11519   }
11520 
11521   return false;
11522 }
11523 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)11524 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11525                               UnaryOperatorKind Opc, Expr *Input) {
11526   // First things first: handle placeholders so that the
11527   // overloaded-operator check considers the right type.
11528   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11529     // Increment and decrement of pseudo-object references.
11530     if (pty->getKind() == BuiltinType::PseudoObject &&
11531         UnaryOperator::isIncrementDecrementOp(Opc))
11532       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11533 
11534     // extension is always a builtin operator.
11535     if (Opc == UO_Extension)
11536       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11537 
11538     // & gets special logic for several kinds of placeholder.
11539     // The builtin code knows what to do.
11540     if (Opc == UO_AddrOf &&
11541         (pty->getKind() == BuiltinType::Overload ||
11542          pty->getKind() == BuiltinType::UnknownAny ||
11543          pty->getKind() == BuiltinType::BoundMember))
11544       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11545 
11546     // Anything else needs to be handled now.
11547     ExprResult Result = CheckPlaceholderExpr(Input);
11548     if (Result.isInvalid()) return ExprError();
11549     Input = Result.get();
11550   }
11551 
11552   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11553       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11554       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11555     // Find all of the overloaded operators visible from this
11556     // point. We perform both an operator-name lookup from the local
11557     // scope and an argument-dependent lookup based on the types of
11558     // the arguments.
11559     UnresolvedSet<16> Functions;
11560     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11561     if (S && OverOp != OO_None)
11562       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11563                                    Functions);
11564 
11565     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11566   }
11567 
11568   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11569 }
11570 
11571 // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)11572 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11573                               tok::TokenKind Op, Expr *Input) {
11574   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11575 }
11576 
11577 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)11578 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11579                                 LabelDecl *TheDecl) {
11580   TheDecl->markUsed(Context);
11581   // Create the AST node.  The address of a label always has type 'void*'.
11582   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11583                                      Context.getPointerType(Context.VoidTy));
11584 }
11585 
11586 /// Given the last statement in a statement-expression, check whether
11587 /// the result is a producing expression (like a call to an
11588 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11589 /// release out of the full-expression.  Otherwise, return null.
11590 /// Cannot fail.
maybeRebuildARCConsumingStmt(Stmt * Statement)11591 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11592   // Should always be wrapped with one of these.
11593   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11594   if (!cleanups) return nullptr;
11595 
11596   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11597   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11598     return nullptr;
11599 
11600   // Splice out the cast.  This shouldn't modify any interesting
11601   // features of the statement.
11602   Expr *producer = cast->getSubExpr();
11603   assert(producer->getType() == cast->getType());
11604   assert(producer->getValueKind() == cast->getValueKind());
11605   cleanups->setSubExpr(producer);
11606   return cleanups;
11607 }
11608 
ActOnStartStmtExpr()11609 void Sema::ActOnStartStmtExpr() {
11610   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11611 }
11612 
ActOnStmtExprError()11613 void Sema::ActOnStmtExprError() {
11614   // Note that function is also called by TreeTransform when leaving a
11615   // StmtExpr scope without rebuilding anything.
11616 
11617   DiscardCleanupsInEvaluationContext();
11618   PopExpressionEvaluationContext();
11619 }
11620 
11621 ExprResult
ActOnStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)11622 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11623                     SourceLocation RPLoc) { // "({..})"
11624   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11625   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11626 
11627   if (hasAnyUnrecoverableErrorsInThisFunction())
11628     DiscardCleanupsInEvaluationContext();
11629   assert(!Cleanup.exprNeedsCleanups() &&
11630          "cleanups within StmtExpr not correctly bound!");
11631   PopExpressionEvaluationContext();
11632 
11633   // FIXME: there are a variety of strange constraints to enforce here, for
11634   // example, it is not possible to goto into a stmt expression apparently.
11635   // More semantic analysis is needed.
11636 
11637   // If there are sub-stmts in the compound stmt, take the type of the last one
11638   // as the type of the stmtexpr.
11639   QualType Ty = Context.VoidTy;
11640   bool StmtExprMayBindToTemp = false;
11641   if (!Compound->body_empty()) {
11642     Stmt *LastStmt = Compound->body_back();
11643     LabelStmt *LastLabelStmt = nullptr;
11644     // If LastStmt is a label, skip down through into the body.
11645     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11646       LastLabelStmt = Label;
11647       LastStmt = Label->getSubStmt();
11648     }
11649 
11650     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11651       // Do function/array conversion on the last expression, but not
11652       // lvalue-to-rvalue.  However, initialize an unqualified type.
11653       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11654       if (LastExpr.isInvalid())
11655         return ExprError();
11656       Ty = LastExpr.get()->getType().getUnqualifiedType();
11657 
11658       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11659         // In ARC, if the final expression ends in a consume, splice
11660         // the consume out and bind it later.  In the alternate case
11661         // (when dealing with a retainable type), the result
11662         // initialization will create a produce.  In both cases the
11663         // result will be +1, and we'll need to balance that out with
11664         // a bind.
11665         if (Expr *rebuiltLastStmt
11666               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11667           LastExpr = rebuiltLastStmt;
11668         } else {
11669           LastExpr = PerformCopyInitialization(
11670                             InitializedEntity::InitializeResult(LPLoc,
11671                                                                 Ty,
11672                                                                 false),
11673                                                    SourceLocation(),
11674                                                LastExpr);
11675         }
11676 
11677         if (LastExpr.isInvalid())
11678           return ExprError();
11679         if (LastExpr.get() != nullptr) {
11680           if (!LastLabelStmt)
11681             Compound->setLastStmt(LastExpr.get());
11682           else
11683             LastLabelStmt->setSubStmt(LastExpr.get());
11684           StmtExprMayBindToTemp = true;
11685         }
11686       }
11687     }
11688   }
11689 
11690   // FIXME: Check that expression type is complete/non-abstract; statement
11691   // expressions are not lvalues.
11692   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11693   if (StmtExprMayBindToTemp)
11694     return MaybeBindToTemporary(ResStmtExpr);
11695   return ResStmtExpr;
11696 }
11697 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11698 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11699                                       TypeSourceInfo *TInfo,
11700                                       ArrayRef<OffsetOfComponent> Components,
11701                                       SourceLocation RParenLoc) {
11702   QualType ArgTy = TInfo->getType();
11703   bool Dependent = ArgTy->isDependentType();
11704   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11705 
11706   // We must have at least one component that refers to the type, and the first
11707   // one is known to be a field designator.  Verify that the ArgTy represents
11708   // a struct/union/class.
11709   if (!Dependent && !ArgTy->isRecordType())
11710     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11711                        << ArgTy << TypeRange);
11712 
11713   // Type must be complete per C99 7.17p3 because a declaring a variable
11714   // with an incomplete type would be ill-formed.
11715   if (!Dependent
11716       && RequireCompleteType(BuiltinLoc, ArgTy,
11717                              diag::err_offsetof_incomplete_type, TypeRange))
11718     return ExprError();
11719 
11720   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11721   // GCC extension, diagnose them.
11722   // FIXME: This diagnostic isn't actually visible because the location is in
11723   // a system header!
11724   if (Components.size() != 1)
11725     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11726       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11727 
11728   bool DidWarnAboutNonPOD = false;
11729   QualType CurrentType = ArgTy;
11730   SmallVector<OffsetOfNode, 4> Comps;
11731   SmallVector<Expr*, 4> Exprs;
11732   for (const OffsetOfComponent &OC : Components) {
11733     if (OC.isBrackets) {
11734       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11735       if (!CurrentType->isDependentType()) {
11736         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11737         if(!AT)
11738           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11739                            << CurrentType);
11740         CurrentType = AT->getElementType();
11741       } else
11742         CurrentType = Context.DependentTy;
11743 
11744       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11745       if (IdxRval.isInvalid())
11746         return ExprError();
11747       Expr *Idx = IdxRval.get();
11748 
11749       // The expression must be an integral expression.
11750       // FIXME: An integral constant expression?
11751       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11752           !Idx->getType()->isIntegerType())
11753         return ExprError(Diag(Idx->getLocStart(),
11754                               diag::err_typecheck_subscript_not_integer)
11755                          << Idx->getSourceRange());
11756 
11757       // Record this array index.
11758       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11759       Exprs.push_back(Idx);
11760       continue;
11761     }
11762 
11763     // Offset of a field.
11764     if (CurrentType->isDependentType()) {
11765       // We have the offset of a field, but we can't look into the dependent
11766       // type. Just record the identifier of the field.
11767       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11768       CurrentType = Context.DependentTy;
11769       continue;
11770     }
11771 
11772     // We need to have a complete type to look into.
11773     if (RequireCompleteType(OC.LocStart, CurrentType,
11774                             diag::err_offsetof_incomplete_type))
11775       return ExprError();
11776 
11777     // Look for the designated field.
11778     const RecordType *RC = CurrentType->getAs<RecordType>();
11779     if (!RC)
11780       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11781                        << CurrentType);
11782     RecordDecl *RD = RC->getDecl();
11783 
11784     // C++ [lib.support.types]p5:
11785     //   The macro offsetof accepts a restricted set of type arguments in this
11786     //   International Standard. type shall be a POD structure or a POD union
11787     //   (clause 9).
11788     // C++11 [support.types]p4:
11789     //   If type is not a standard-layout class (Clause 9), the results are
11790     //   undefined.
11791     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11792       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11793       unsigned DiagID =
11794         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11795                             : diag::ext_offsetof_non_pod_type;
11796 
11797       if (!IsSafe && !DidWarnAboutNonPOD &&
11798           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11799                               PDiag(DiagID)
11800                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11801                               << CurrentType))
11802         DidWarnAboutNonPOD = true;
11803     }
11804 
11805     // Look for the field.
11806     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11807     LookupQualifiedName(R, RD);
11808     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11809     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11810     if (!MemberDecl) {
11811       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11812         MemberDecl = IndirectMemberDecl->getAnonField();
11813     }
11814 
11815     if (!MemberDecl)
11816       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11817                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11818                                                               OC.LocEnd));
11819 
11820     // C99 7.17p3:
11821     //   (If the specified member is a bit-field, the behavior is undefined.)
11822     //
11823     // We diagnose this as an error.
11824     if (MemberDecl->isBitField()) {
11825       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11826         << MemberDecl->getDeclName()
11827         << SourceRange(BuiltinLoc, RParenLoc);
11828       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11829       return ExprError();
11830     }
11831 
11832     RecordDecl *Parent = MemberDecl->getParent();
11833     if (IndirectMemberDecl)
11834       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11835 
11836     // If the member was found in a base class, introduce OffsetOfNodes for
11837     // the base class indirections.
11838     CXXBasePaths Paths;
11839     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11840                       Paths)) {
11841       if (Paths.getDetectedVirtual()) {
11842         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11843           << MemberDecl->getDeclName()
11844           << SourceRange(BuiltinLoc, RParenLoc);
11845         return ExprError();
11846       }
11847 
11848       CXXBasePath &Path = Paths.front();
11849       for (const CXXBasePathElement &B : Path)
11850         Comps.push_back(OffsetOfNode(B.Base));
11851     }
11852 
11853     if (IndirectMemberDecl) {
11854       for (auto *FI : IndirectMemberDecl->chain()) {
11855         assert(isa<FieldDecl>(FI));
11856         Comps.push_back(OffsetOfNode(OC.LocStart,
11857                                      cast<FieldDecl>(FI), OC.LocEnd));
11858       }
11859     } else
11860       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11861 
11862     CurrentType = MemberDecl->getType().getNonReferenceType();
11863   }
11864 
11865   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11866                               Comps, Exprs, RParenLoc);
11867 }
11868 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11869 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11870                                       SourceLocation BuiltinLoc,
11871                                       SourceLocation TypeLoc,
11872                                       ParsedType ParsedArgTy,
11873                                       ArrayRef<OffsetOfComponent> Components,
11874                                       SourceLocation RParenLoc) {
11875 
11876   TypeSourceInfo *ArgTInfo;
11877   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11878   if (ArgTy.isNull())
11879     return ExprError();
11880 
11881   if (!ArgTInfo)
11882     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11883 
11884   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11885 }
11886 
11887 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)11888 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11889                                  Expr *CondExpr,
11890                                  Expr *LHSExpr, Expr *RHSExpr,
11891                                  SourceLocation RPLoc) {
11892   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11893 
11894   ExprValueKind VK = VK_RValue;
11895   ExprObjectKind OK = OK_Ordinary;
11896   QualType resType;
11897   bool ValueDependent = false;
11898   bool CondIsTrue = false;
11899   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11900     resType = Context.DependentTy;
11901     ValueDependent = true;
11902   } else {
11903     // The conditional expression is required to be a constant expression.
11904     llvm::APSInt condEval(32);
11905     ExprResult CondICE
11906       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11907           diag::err_typecheck_choose_expr_requires_constant, false);
11908     if (CondICE.isInvalid())
11909       return ExprError();
11910     CondExpr = CondICE.get();
11911     CondIsTrue = condEval.getZExtValue();
11912 
11913     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11914     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11915 
11916     resType = ActiveExpr->getType();
11917     ValueDependent = ActiveExpr->isValueDependent();
11918     VK = ActiveExpr->getValueKind();
11919     OK = ActiveExpr->getObjectKind();
11920   }
11921 
11922   return new (Context)
11923       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11924                  CondIsTrue, resType->isDependentType(), ValueDependent);
11925 }
11926 
11927 //===----------------------------------------------------------------------===//
11928 // Clang Extensions.
11929 //===----------------------------------------------------------------------===//
11930 
11931 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)11932 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11933   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11934 
11935   if (LangOpts.CPlusPlus) {
11936     Decl *ManglingContextDecl;
11937     if (MangleNumberingContext *MCtx =
11938             getCurrentMangleNumberContext(Block->getDeclContext(),
11939                                           ManglingContextDecl)) {
11940       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11941       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11942     }
11943   }
11944 
11945   PushBlockScope(CurScope, Block);
11946   CurContext->addDecl(Block);
11947   if (CurScope)
11948     PushDeclContext(CurScope, Block);
11949   else
11950     CurContext = Block;
11951 
11952   getCurBlock()->HasImplicitReturnType = true;
11953 
11954   // Enter a new evaluation context to insulate the block from any
11955   // cleanups from the enclosing full-expression.
11956   PushExpressionEvaluationContext(PotentiallyEvaluated);
11957 }
11958 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)11959 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11960                                Scope *CurScope) {
11961   assert(ParamInfo.getIdentifier() == nullptr &&
11962          "block-id should have no identifier!");
11963   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11964   BlockScopeInfo *CurBlock = getCurBlock();
11965 
11966   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11967   QualType T = Sig->getType();
11968 
11969   // FIXME: We should allow unexpanded parameter packs here, but that would,
11970   // in turn, make the block expression contain unexpanded parameter packs.
11971   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11972     // Drop the parameters.
11973     FunctionProtoType::ExtProtoInfo EPI;
11974     EPI.HasTrailingReturn = false;
11975     EPI.TypeQuals |= DeclSpec::TQ_const;
11976     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11977     Sig = Context.getTrivialTypeSourceInfo(T);
11978   }
11979 
11980   // GetTypeForDeclarator always produces a function type for a block
11981   // literal signature.  Furthermore, it is always a FunctionProtoType
11982   // unless the function was written with a typedef.
11983   assert(T->isFunctionType() &&
11984          "GetTypeForDeclarator made a non-function block signature");
11985 
11986   // Look for an explicit signature in that function type.
11987   FunctionProtoTypeLoc ExplicitSignature;
11988 
11989   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11990   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11991 
11992     // Check whether that explicit signature was synthesized by
11993     // GetTypeForDeclarator.  If so, don't save that as part of the
11994     // written signature.
11995     if (ExplicitSignature.getLocalRangeBegin() ==
11996         ExplicitSignature.getLocalRangeEnd()) {
11997       // This would be much cheaper if we stored TypeLocs instead of
11998       // TypeSourceInfos.
11999       TypeLoc Result = ExplicitSignature.getReturnLoc();
12000       unsigned Size = Result.getFullDataSize();
12001       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12002       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12003 
12004       ExplicitSignature = FunctionProtoTypeLoc();
12005     }
12006   }
12007 
12008   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12009   CurBlock->FunctionType = T;
12010 
12011   const FunctionType *Fn = T->getAs<FunctionType>();
12012   QualType RetTy = Fn->getReturnType();
12013   bool isVariadic =
12014     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12015 
12016   CurBlock->TheDecl->setIsVariadic(isVariadic);
12017 
12018   // Context.DependentTy is used as a placeholder for a missing block
12019   // return type.  TODO:  what should we do with declarators like:
12020   //   ^ * { ... }
12021   // If the answer is "apply template argument deduction"....
12022   if (RetTy != Context.DependentTy) {
12023     CurBlock->ReturnType = RetTy;
12024     CurBlock->TheDecl->setBlockMissingReturnType(false);
12025     CurBlock->HasImplicitReturnType = false;
12026   }
12027 
12028   // Push block parameters from the declarator if we had them.
12029   SmallVector<ParmVarDecl*, 8> Params;
12030   if (ExplicitSignature) {
12031     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12032       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12033       if (Param->getIdentifier() == nullptr &&
12034           !Param->isImplicit() &&
12035           !Param->isInvalidDecl() &&
12036           !getLangOpts().CPlusPlus)
12037         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12038       Params.push_back(Param);
12039     }
12040 
12041   // Fake up parameter variables if we have a typedef, like
12042   //   ^ fntype { ... }
12043   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12044     for (const auto &I : Fn->param_types()) {
12045       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12046           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12047       Params.push_back(Param);
12048     }
12049   }
12050 
12051   // Set the parameters on the block decl.
12052   if (!Params.empty()) {
12053     CurBlock->TheDecl->setParams(Params);
12054     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12055                              /*CheckParameterNames=*/false);
12056   }
12057 
12058   // Finally we can process decl attributes.
12059   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12060 
12061   // Put the parameter variables in scope.
12062   for (auto AI : CurBlock->TheDecl->parameters()) {
12063     AI->setOwningFunction(CurBlock->TheDecl);
12064 
12065     // If this has an identifier, add it to the scope stack.
12066     if (AI->getIdentifier()) {
12067       CheckShadow(CurBlock->TheScope, AI);
12068 
12069       PushOnScopeChains(AI, CurBlock->TheScope);
12070     }
12071   }
12072 }
12073 
12074 /// ActOnBlockError - If there is an error parsing a block, this callback
12075 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)12076 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12077   // Leave the expression-evaluation context.
12078   DiscardCleanupsInEvaluationContext();
12079   PopExpressionEvaluationContext();
12080 
12081   // Pop off CurBlock, handle nested blocks.
12082   PopDeclContext();
12083   PopFunctionScopeInfo();
12084 }
12085 
12086 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12087 /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)12088 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12089                                     Stmt *Body, Scope *CurScope) {
12090   // If blocks are disabled, emit an error.
12091   if (!LangOpts.Blocks)
12092     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12093 
12094   // Leave the expression-evaluation context.
12095   if (hasAnyUnrecoverableErrorsInThisFunction())
12096     DiscardCleanupsInEvaluationContext();
12097   assert(!Cleanup.exprNeedsCleanups() &&
12098          "cleanups within block not correctly bound!");
12099   PopExpressionEvaluationContext();
12100 
12101   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12102 
12103   if (BSI->HasImplicitReturnType)
12104     deduceClosureReturnType(*BSI);
12105 
12106   PopDeclContext();
12107 
12108   QualType RetTy = Context.VoidTy;
12109   if (!BSI->ReturnType.isNull())
12110     RetTy = BSI->ReturnType;
12111 
12112   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12113   QualType BlockTy;
12114 
12115   // Set the captured variables on the block.
12116   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12117   SmallVector<BlockDecl::Capture, 4> Captures;
12118   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12119     if (Cap.isThisCapture())
12120       continue;
12121     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12122                               Cap.isNested(), Cap.getInitExpr());
12123     Captures.push_back(NewCap);
12124   }
12125   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12126 
12127   // If the user wrote a function type in some form, try to use that.
12128   if (!BSI->FunctionType.isNull()) {
12129     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12130 
12131     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12132     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12133 
12134     // Turn protoless block types into nullary block types.
12135     if (isa<FunctionNoProtoType>(FTy)) {
12136       FunctionProtoType::ExtProtoInfo EPI;
12137       EPI.ExtInfo = Ext;
12138       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12139 
12140     // Otherwise, if we don't need to change anything about the function type,
12141     // preserve its sugar structure.
12142     } else if (FTy->getReturnType() == RetTy &&
12143                (!NoReturn || FTy->getNoReturnAttr())) {
12144       BlockTy = BSI->FunctionType;
12145 
12146     // Otherwise, make the minimal modifications to the function type.
12147     } else {
12148       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12149       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12150       EPI.TypeQuals = 0; // FIXME: silently?
12151       EPI.ExtInfo = Ext;
12152       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12153     }
12154 
12155   // If we don't have a function type, just build one from nothing.
12156   } else {
12157     FunctionProtoType::ExtProtoInfo EPI;
12158     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12159     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12160   }
12161 
12162   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12163   BlockTy = Context.getBlockPointerType(BlockTy);
12164 
12165   // If needed, diagnose invalid gotos and switches in the block.
12166   if (getCurFunction()->NeedsScopeChecking() &&
12167       !PP.isCodeCompletionEnabled())
12168     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12169 
12170   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12171 
12172   // Try to apply the named return value optimization. We have to check again
12173   // if we can do this, though, because blocks keep return statements around
12174   // to deduce an implicit return type.
12175   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12176       !BSI->TheDecl->isDependentContext())
12177     computeNRVO(Body, BSI);
12178 
12179   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12180   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12181   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12182 
12183   // If the block isn't obviously global, i.e. it captures anything at
12184   // all, then we need to do a few things in the surrounding context:
12185   if (Result->getBlockDecl()->hasCaptures()) {
12186     // First, this expression has a new cleanup object.
12187     ExprCleanupObjects.push_back(Result->getBlockDecl());
12188     Cleanup.setExprNeedsCleanups(true);
12189 
12190     // It also gets a branch-protected scope if any of the captured
12191     // variables needs destruction.
12192     for (const auto &CI : Result->getBlockDecl()->captures()) {
12193       const VarDecl *var = CI.getVariable();
12194       if (var->getType().isDestructedType() != QualType::DK_none) {
12195         getCurFunction()->setHasBranchProtectedScope();
12196         break;
12197       }
12198     }
12199   }
12200 
12201   return Result;
12202 }
12203 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)12204 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12205                             SourceLocation RPLoc) {
12206   TypeSourceInfo *TInfo;
12207   GetTypeFromParser(Ty, &TInfo);
12208   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12209 }
12210 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)12211 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12212                                 Expr *E, TypeSourceInfo *TInfo,
12213                                 SourceLocation RPLoc) {
12214   Expr *OrigExpr = E;
12215   bool IsMS = false;
12216 
12217   // CUDA device code does not support varargs.
12218   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12219     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12220       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12221       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12222         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12223     }
12224   }
12225 
12226   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12227   // as Microsoft ABI on an actual Microsoft platform, where
12228   // __builtin_ms_va_list and __builtin_va_list are the same.)
12229   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12230       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12231     QualType MSVaListType = Context.getBuiltinMSVaListType();
12232     if (Context.hasSameType(MSVaListType, E->getType())) {
12233       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12234         return ExprError();
12235       IsMS = true;
12236     }
12237   }
12238 
12239   // Get the va_list type
12240   QualType VaListType = Context.getBuiltinVaListType();
12241   if (!IsMS) {
12242     if (VaListType->isArrayType()) {
12243       // Deal with implicit array decay; for example, on x86-64,
12244       // va_list is an array, but it's supposed to decay to
12245       // a pointer for va_arg.
12246       VaListType = Context.getArrayDecayedType(VaListType);
12247       // Make sure the input expression also decays appropriately.
12248       ExprResult Result = UsualUnaryConversions(E);
12249       if (Result.isInvalid())
12250         return ExprError();
12251       E = Result.get();
12252     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12253       // If va_list is a record type and we are compiling in C++ mode,
12254       // check the argument using reference binding.
12255       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12256           Context, Context.getLValueReferenceType(VaListType), false);
12257       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12258       if (Init.isInvalid())
12259         return ExprError();
12260       E = Init.getAs<Expr>();
12261     } else {
12262       // Otherwise, the va_list argument must be an l-value because
12263       // it is modified by va_arg.
12264       if (!E->isTypeDependent() &&
12265           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12266         return ExprError();
12267     }
12268   }
12269 
12270   if (!IsMS && !E->isTypeDependent() &&
12271       !Context.hasSameType(VaListType, E->getType()))
12272     return ExprError(Diag(E->getLocStart(),
12273                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12274       << OrigExpr->getType() << E->getSourceRange());
12275 
12276   if (!TInfo->getType()->isDependentType()) {
12277     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12278                             diag::err_second_parameter_to_va_arg_incomplete,
12279                             TInfo->getTypeLoc()))
12280       return ExprError();
12281 
12282     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12283                                TInfo->getType(),
12284                                diag::err_second_parameter_to_va_arg_abstract,
12285                                TInfo->getTypeLoc()))
12286       return ExprError();
12287 
12288     if (!TInfo->getType().isPODType(Context)) {
12289       Diag(TInfo->getTypeLoc().getBeginLoc(),
12290            TInfo->getType()->isObjCLifetimeType()
12291              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12292              : diag::warn_second_parameter_to_va_arg_not_pod)
12293         << TInfo->getType()
12294         << TInfo->getTypeLoc().getSourceRange();
12295     }
12296 
12297     // Check for va_arg where arguments of the given type will be promoted
12298     // (i.e. this va_arg is guaranteed to have undefined behavior).
12299     QualType PromoteType;
12300     if (TInfo->getType()->isPromotableIntegerType()) {
12301       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12302       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12303         PromoteType = QualType();
12304     }
12305     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12306       PromoteType = Context.DoubleTy;
12307     if (!PromoteType.isNull())
12308       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12309                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12310                           << TInfo->getType()
12311                           << PromoteType
12312                           << TInfo->getTypeLoc().getSourceRange());
12313   }
12314 
12315   QualType T = TInfo->getType().getNonLValueExprType(Context);
12316   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12317 }
12318 
ActOnGNUNullExpr(SourceLocation TokenLoc)12319 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12320   // The type of __null will be int or long, depending on the size of
12321   // pointers on the target.
12322   QualType Ty;
12323   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12324   if (pw == Context.getTargetInfo().getIntWidth())
12325     Ty = Context.IntTy;
12326   else if (pw == Context.getTargetInfo().getLongWidth())
12327     Ty = Context.LongTy;
12328   else if (pw == Context.getTargetInfo().getLongLongWidth())
12329     Ty = Context.LongLongTy;
12330   else {
12331     llvm_unreachable("I don't know size of pointer!");
12332   }
12333 
12334   return new (Context) GNUNullExpr(Ty, TokenLoc);
12335 }
12336 
ConversionToObjCStringLiteralCheck(QualType DstType,Expr * & Exp,bool Diagnose)12337 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12338                                               bool Diagnose) {
12339   if (!getLangOpts().ObjC1)
12340     return false;
12341 
12342   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12343   if (!PT)
12344     return false;
12345 
12346   if (!PT->isObjCIdType()) {
12347     // Check if the destination is the 'NSString' interface.
12348     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12349     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12350       return false;
12351   }
12352 
12353   // Ignore any parens, implicit casts (should only be
12354   // array-to-pointer decays), and not-so-opaque values.  The last is
12355   // important for making this trigger for property assignments.
12356   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12357   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12358     if (OV->getSourceExpr())
12359       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12360 
12361   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12362   if (!SL || !SL->isAscii())
12363     return false;
12364   if (Diagnose) {
12365     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12366       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12367     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12368   }
12369   return true;
12370 }
12371 
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)12372 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12373                                               const Expr *SrcExpr) {
12374   if (!DstType->isFunctionPointerType() ||
12375       !SrcExpr->getType()->isFunctionType())
12376     return false;
12377 
12378   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12379   if (!DRE)
12380     return false;
12381 
12382   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12383   if (!FD)
12384     return false;
12385 
12386   return !S.checkAddressOfFunctionIsAvailable(FD,
12387                                               /*Complain=*/true,
12388                                               SrcExpr->getLocStart());
12389 }
12390 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)12391 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12392                                     SourceLocation Loc,
12393                                     QualType DstType, QualType SrcType,
12394                                     Expr *SrcExpr, AssignmentAction Action,
12395                                     bool *Complained) {
12396   if (Complained)
12397     *Complained = false;
12398 
12399   // Decode the result (notice that AST's are still created for extensions).
12400   bool CheckInferredResultType = false;
12401   bool isInvalid = false;
12402   unsigned DiagKind = 0;
12403   FixItHint Hint;
12404   ConversionFixItGenerator ConvHints;
12405   bool MayHaveConvFixit = false;
12406   bool MayHaveFunctionDiff = false;
12407   const ObjCInterfaceDecl *IFace = nullptr;
12408   const ObjCProtocolDecl *PDecl = nullptr;
12409 
12410   switch (ConvTy) {
12411   case Compatible:
12412       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12413       return false;
12414 
12415   case PointerToInt:
12416     DiagKind = diag::ext_typecheck_convert_pointer_int;
12417     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12418     MayHaveConvFixit = true;
12419     break;
12420   case IntToPointer:
12421     DiagKind = diag::ext_typecheck_convert_int_pointer;
12422     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12423     MayHaveConvFixit = true;
12424     break;
12425   case IncompatiblePointer:
12426       DiagKind =
12427         (Action == AA_Passing_CFAudited ?
12428           diag::err_arc_typecheck_convert_incompatible_pointer :
12429           diag::ext_typecheck_convert_incompatible_pointer);
12430     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12431       SrcType->isObjCObjectPointerType();
12432     if (Hint.isNull() && !CheckInferredResultType) {
12433       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12434     }
12435     else if (CheckInferredResultType) {
12436       SrcType = SrcType.getUnqualifiedType();
12437       DstType = DstType.getUnqualifiedType();
12438     }
12439     MayHaveConvFixit = true;
12440     break;
12441   case IncompatiblePointerSign:
12442     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12443     break;
12444   case FunctionVoidPointer:
12445     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12446     break;
12447   case IncompatiblePointerDiscardsQualifiers: {
12448     // Perform array-to-pointer decay if necessary.
12449     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12450 
12451     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12452     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12453     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12454       DiagKind = diag::err_typecheck_incompatible_address_space;
12455       break;
12456 
12457 
12458     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12459       DiagKind = diag::err_typecheck_incompatible_ownership;
12460       break;
12461     }
12462 
12463     llvm_unreachable("unknown error case for discarding qualifiers!");
12464     // fallthrough
12465   }
12466   case CompatiblePointerDiscardsQualifiers:
12467     // If the qualifiers lost were because we were applying the
12468     // (deprecated) C++ conversion from a string literal to a char*
12469     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12470     // Ideally, this check would be performed in
12471     // checkPointerTypesForAssignment. However, that would require a
12472     // bit of refactoring (so that the second argument is an
12473     // expression, rather than a type), which should be done as part
12474     // of a larger effort to fix checkPointerTypesForAssignment for
12475     // C++ semantics.
12476     if (getLangOpts().CPlusPlus &&
12477         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12478       return false;
12479     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12480     break;
12481   case IncompatibleNestedPointerQualifiers:
12482     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12483     break;
12484   case IntToBlockPointer:
12485     DiagKind = diag::err_int_to_block_pointer;
12486     break;
12487   case IncompatibleBlockPointer:
12488     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12489     break;
12490   case IncompatibleObjCQualifiedId: {
12491     if (SrcType->isObjCQualifiedIdType()) {
12492       const ObjCObjectPointerType *srcOPT =
12493                 SrcType->getAs<ObjCObjectPointerType>();
12494       for (auto *srcProto : srcOPT->quals()) {
12495         PDecl = srcProto;
12496         break;
12497       }
12498       if (const ObjCInterfaceType *IFaceT =
12499             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12500         IFace = IFaceT->getDecl();
12501     }
12502     else if (DstType->isObjCQualifiedIdType()) {
12503       const ObjCObjectPointerType *dstOPT =
12504         DstType->getAs<ObjCObjectPointerType>();
12505       for (auto *dstProto : dstOPT->quals()) {
12506         PDecl = dstProto;
12507         break;
12508       }
12509       if (const ObjCInterfaceType *IFaceT =
12510             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12511         IFace = IFaceT->getDecl();
12512     }
12513     DiagKind = diag::warn_incompatible_qualified_id;
12514     break;
12515   }
12516   case IncompatibleVectors:
12517     DiagKind = diag::warn_incompatible_vectors;
12518     break;
12519   case IncompatibleObjCWeakRef:
12520     DiagKind = diag::err_arc_weak_unavailable_assign;
12521     break;
12522   case Incompatible:
12523     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12524       if (Complained)
12525         *Complained = true;
12526       return true;
12527     }
12528 
12529     DiagKind = diag::err_typecheck_convert_incompatible;
12530     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12531     MayHaveConvFixit = true;
12532     isInvalid = true;
12533     MayHaveFunctionDiff = true;
12534     break;
12535   }
12536 
12537   QualType FirstType, SecondType;
12538   switch (Action) {
12539   case AA_Assigning:
12540   case AA_Initializing:
12541     // The destination type comes first.
12542     FirstType = DstType;
12543     SecondType = SrcType;
12544     break;
12545 
12546   case AA_Returning:
12547   case AA_Passing:
12548   case AA_Passing_CFAudited:
12549   case AA_Converting:
12550   case AA_Sending:
12551   case AA_Casting:
12552     // The source type comes first.
12553     FirstType = SrcType;
12554     SecondType = DstType;
12555     break;
12556   }
12557 
12558   PartialDiagnostic FDiag = PDiag(DiagKind);
12559   if (Action == AA_Passing_CFAudited)
12560     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12561   else
12562     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12563 
12564   // If we can fix the conversion, suggest the FixIts.
12565   assert(ConvHints.isNull() || Hint.isNull());
12566   if (!ConvHints.isNull()) {
12567     for (FixItHint &H : ConvHints.Hints)
12568       FDiag << H;
12569   } else {
12570     FDiag << Hint;
12571   }
12572   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12573 
12574   if (MayHaveFunctionDiff)
12575     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12576 
12577   Diag(Loc, FDiag);
12578   if (DiagKind == diag::warn_incompatible_qualified_id &&
12579       PDecl && IFace && !IFace->hasDefinition())
12580       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12581         << IFace->getName() << PDecl->getName();
12582 
12583   if (SecondType == Context.OverloadTy)
12584     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12585                               FirstType, /*TakingAddress=*/true);
12586 
12587   if (CheckInferredResultType)
12588     EmitRelatedResultTypeNote(SrcExpr);
12589 
12590   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12591     EmitRelatedResultTypeNoteForReturn(DstType);
12592 
12593   if (Complained)
12594     *Complained = true;
12595   return isInvalid;
12596 }
12597 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)12598 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12599                                                  llvm::APSInt *Result) {
12600   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12601   public:
12602     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12603       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12604     }
12605   } Diagnoser;
12606 
12607   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12608 }
12609 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)12610 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12611                                                  llvm::APSInt *Result,
12612                                                  unsigned DiagID,
12613                                                  bool AllowFold) {
12614   class IDDiagnoser : public VerifyICEDiagnoser {
12615     unsigned DiagID;
12616 
12617   public:
12618     IDDiagnoser(unsigned DiagID)
12619       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12620 
12621     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12622       S.Diag(Loc, DiagID) << SR;
12623     }
12624   } Diagnoser(DiagID);
12625 
12626   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12627 }
12628 
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)12629 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12630                                             SourceRange SR) {
12631   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12632 }
12633 
12634 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)12635 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12636                                       VerifyICEDiagnoser &Diagnoser,
12637                                       bool AllowFold) {
12638   SourceLocation DiagLoc = E->getLocStart();
12639 
12640   if (getLangOpts().CPlusPlus11) {
12641     // C++11 [expr.const]p5:
12642     //   If an expression of literal class type is used in a context where an
12643     //   integral constant expression is required, then that class type shall
12644     //   have a single non-explicit conversion function to an integral or
12645     //   unscoped enumeration type
12646     ExprResult Converted;
12647     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12648     public:
12649       CXX11ConvertDiagnoser(bool Silent)
12650           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12651                                 Silent, true) {}
12652 
12653       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12654                                            QualType T) override {
12655         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12656       }
12657 
12658       SemaDiagnosticBuilder diagnoseIncomplete(
12659           Sema &S, SourceLocation Loc, QualType T) override {
12660         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12661       }
12662 
12663       SemaDiagnosticBuilder diagnoseExplicitConv(
12664           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12665         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12666       }
12667 
12668       SemaDiagnosticBuilder noteExplicitConv(
12669           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12670         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12671                  << ConvTy->isEnumeralType() << ConvTy;
12672       }
12673 
12674       SemaDiagnosticBuilder diagnoseAmbiguous(
12675           Sema &S, SourceLocation Loc, QualType T) override {
12676         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12677       }
12678 
12679       SemaDiagnosticBuilder noteAmbiguous(
12680           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12681         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12682                  << ConvTy->isEnumeralType() << ConvTy;
12683       }
12684 
12685       SemaDiagnosticBuilder diagnoseConversion(
12686           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12687         llvm_unreachable("conversion functions are permitted");
12688       }
12689     } ConvertDiagnoser(Diagnoser.Suppress);
12690 
12691     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12692                                                     ConvertDiagnoser);
12693     if (Converted.isInvalid())
12694       return Converted;
12695     E = Converted.get();
12696     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12697       return ExprError();
12698   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12699     // An ICE must be of integral or unscoped enumeration type.
12700     if (!Diagnoser.Suppress)
12701       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12702     return ExprError();
12703   }
12704 
12705   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12706   // in the non-ICE case.
12707   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12708     if (Result)
12709       *Result = E->EvaluateKnownConstInt(Context);
12710     return E;
12711   }
12712 
12713   Expr::EvalResult EvalResult;
12714   SmallVector<PartialDiagnosticAt, 8> Notes;
12715   EvalResult.Diag = &Notes;
12716 
12717   // Try to evaluate the expression, and produce diagnostics explaining why it's
12718   // not a constant expression as a side-effect.
12719   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12720                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12721 
12722   // In C++11, we can rely on diagnostics being produced for any expression
12723   // which is not a constant expression. If no diagnostics were produced, then
12724   // this is a constant expression.
12725   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12726     if (Result)
12727       *Result = EvalResult.Val.getInt();
12728     return E;
12729   }
12730 
12731   // If our only note is the usual "invalid subexpression" note, just point
12732   // the caret at its location rather than producing an essentially
12733   // redundant note.
12734   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12735         diag::note_invalid_subexpr_in_const_expr) {
12736     DiagLoc = Notes[0].first;
12737     Notes.clear();
12738   }
12739 
12740   if (!Folded || !AllowFold) {
12741     if (!Diagnoser.Suppress) {
12742       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12743       for (const PartialDiagnosticAt &Note : Notes)
12744         Diag(Note.first, Note.second);
12745     }
12746 
12747     return ExprError();
12748   }
12749 
12750   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12751   for (const PartialDiagnosticAt &Note : Notes)
12752     Diag(Note.first, Note.second);
12753 
12754   if (Result)
12755     *Result = EvalResult.Val.getInt();
12756   return E;
12757 }
12758 
12759 namespace {
12760   // Handle the case where we conclude a expression which we speculatively
12761   // considered to be unevaluated is actually evaluated.
12762   class TransformToPE : public TreeTransform<TransformToPE> {
12763     typedef TreeTransform<TransformToPE> BaseTransform;
12764 
12765   public:
TransformToPE(Sema & SemaRef)12766     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12767 
12768     // Make sure we redo semantic analysis
AlwaysRebuild()12769     bool AlwaysRebuild() { return true; }
12770 
12771     // Make sure we handle LabelStmts correctly.
12772     // FIXME: This does the right thing, but maybe we need a more general
12773     // fix to TreeTransform?
TransformLabelStmt(LabelStmt * S)12774     StmtResult TransformLabelStmt(LabelStmt *S) {
12775       S->getDecl()->setStmt(nullptr);
12776       return BaseTransform::TransformLabelStmt(S);
12777     }
12778 
12779     // We need to special-case DeclRefExprs referring to FieldDecls which
12780     // are not part of a member pointer formation; normal TreeTransforming
12781     // doesn't catch this case because of the way we represent them in the AST.
12782     // FIXME: This is a bit ugly; is it really the best way to handle this
12783     // case?
12784     //
12785     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)12786     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12787       if (isa<FieldDecl>(E->getDecl()) &&
12788           !SemaRef.isUnevaluatedContext())
12789         return SemaRef.Diag(E->getLocation(),
12790                             diag::err_invalid_non_static_member_use)
12791             << E->getDecl() << E->getSourceRange();
12792 
12793       return BaseTransform::TransformDeclRefExpr(E);
12794     }
12795 
12796     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)12797     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12798       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12799         return E;
12800 
12801       return BaseTransform::TransformUnaryOperator(E);
12802     }
12803 
TransformLambdaExpr(LambdaExpr * E)12804     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12805       // Lambdas never need to be transformed.
12806       return E;
12807     }
12808   };
12809 }
12810 
TransformToPotentiallyEvaluated(Expr * E)12811 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12812   assert(isUnevaluatedContext() &&
12813          "Should only transform unevaluated expressions");
12814   ExprEvalContexts.back().Context =
12815       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12816   if (isUnevaluatedContext())
12817     return E;
12818   return TransformToPE(*this).TransformExpr(E);
12819 }
12820 
12821 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,bool IsDecltype)12822 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12823                                       Decl *LambdaContextDecl,
12824                                       bool IsDecltype) {
12825   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12826                                 LambdaContextDecl, IsDecltype);
12827   Cleanup.reset();
12828   if (!MaybeODRUseExprs.empty())
12829     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12830 }
12831 
12832 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,bool IsDecltype)12833 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12834                                       ReuseLambdaContextDecl_t,
12835                                       bool IsDecltype) {
12836   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12837   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12838 }
12839 
PopExpressionEvaluationContext()12840 void Sema::PopExpressionEvaluationContext() {
12841   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12842   unsigned NumTypos = Rec.NumTypos;
12843 
12844   if (!Rec.Lambdas.empty()) {
12845     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12846       unsigned D;
12847       if (Rec.isUnevaluated()) {
12848         // C++11 [expr.prim.lambda]p2:
12849         //   A lambda-expression shall not appear in an unevaluated operand
12850         //   (Clause 5).
12851         D = diag::err_lambda_unevaluated_operand;
12852       } else {
12853         // C++1y [expr.const]p2:
12854         //   A conditional-expression e is a core constant expression unless the
12855         //   evaluation of e, following the rules of the abstract machine, would
12856         //   evaluate [...] a lambda-expression.
12857         D = diag::err_lambda_in_constant_expression;
12858       }
12859       for (const auto *L : Rec.Lambdas)
12860         Diag(L->getLocStart(), D);
12861     } else {
12862       // Mark the capture expressions odr-used. This was deferred
12863       // during lambda expression creation.
12864       for (auto *Lambda : Rec.Lambdas) {
12865         for (auto *C : Lambda->capture_inits())
12866           MarkDeclarationsReferencedInExpr(C);
12867       }
12868     }
12869   }
12870 
12871   // When are coming out of an unevaluated context, clear out any
12872   // temporaries that we may have created as part of the evaluation of
12873   // the expression in that context: they aren't relevant because they
12874   // will never be constructed.
12875   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12876     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12877                              ExprCleanupObjects.end());
12878     Cleanup = Rec.ParentCleanup;
12879     CleanupVarDeclMarking();
12880     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12881   // Otherwise, merge the contexts together.
12882   } else {
12883     Cleanup.mergeFrom(Rec.ParentCleanup);
12884     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12885                             Rec.SavedMaybeODRUseExprs.end());
12886   }
12887 
12888   // Pop the current expression evaluation context off the stack.
12889   ExprEvalContexts.pop_back();
12890 
12891   if (!ExprEvalContexts.empty())
12892     ExprEvalContexts.back().NumTypos += NumTypos;
12893   else
12894     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12895                             "last ExpressionEvaluationContextRecord");
12896 }
12897 
DiscardCleanupsInEvaluationContext()12898 void Sema::DiscardCleanupsInEvaluationContext() {
12899   ExprCleanupObjects.erase(
12900          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12901          ExprCleanupObjects.end());
12902   Cleanup.reset();
12903   MaybeODRUseExprs.clear();
12904 }
12905 
HandleExprEvaluationContextForTypeof(Expr * E)12906 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12907   if (!E->getType()->isVariablyModifiedType())
12908     return E;
12909   return TransformToPotentiallyEvaluated(E);
12910 }
12911 
IsPotentiallyEvaluatedContext(Sema & SemaRef)12912 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12913   // Do not mark anything as "used" within a dependent context; wait for
12914   // an instantiation.
12915   if (SemaRef.CurContext->isDependentContext())
12916     return false;
12917 
12918   switch (SemaRef.ExprEvalContexts.back().Context) {
12919     case Sema::Unevaluated:
12920     case Sema::UnevaluatedAbstract:
12921       // We are in an expression that is not potentially evaluated; do nothing.
12922       // (Depending on how you read the standard, we actually do need to do
12923       // something here for null pointer constants, but the standard's
12924       // definition of a null pointer constant is completely crazy.)
12925       return false;
12926 
12927     case Sema::DiscardedStatement:
12928       // These are technically a potentially evaluated but they have the effect
12929       // of suppressing use marking.
12930       return false;
12931 
12932     case Sema::ConstantEvaluated:
12933     case Sema::PotentiallyEvaluated:
12934       // We are in a potentially evaluated expression (or a constant-expression
12935       // in C++03); we need to do implicit template instantiation, implicitly
12936       // define class members, and mark most declarations as used.
12937       return true;
12938 
12939     case Sema::PotentiallyEvaluatedIfUsed:
12940       // Referenced declarations will only be used if the construct in the
12941       // containing expression is used.
12942       return false;
12943   }
12944   llvm_unreachable("Invalid context");
12945 }
12946 
12947 /// \brief Mark a function referenced, and check whether it is odr-used
12948 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)12949 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12950                                   bool MightBeOdrUse) {
12951   assert(Func && "No function?");
12952 
12953   Func->setReferenced();
12954 
12955   // C++11 [basic.def.odr]p3:
12956   //   A function whose name appears as a potentially-evaluated expression is
12957   //   odr-used if it is the unique lookup result or the selected member of a
12958   //   set of overloaded functions [...].
12959   //
12960   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12961   // can just check that here.
12962   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
12963 
12964   // Determine whether we require a function definition to exist, per
12965   // C++11 [temp.inst]p3:
12966   //   Unless a function template specialization has been explicitly
12967   //   instantiated or explicitly specialized, the function template
12968   //   specialization is implicitly instantiated when the specialization is
12969   //   referenced in a context that requires a function definition to exist.
12970   //
12971   // We consider constexpr function templates to be referenced in a context
12972   // that requires a definition to exist whenever they are referenced.
12973   //
12974   // FIXME: This instantiates constexpr functions too frequently. If this is
12975   // really an unevaluated context (and we're not just in the definition of a
12976   // function template or overload resolution or other cases which we
12977   // incorrectly consider to be unevaluated contexts), and we're not in a
12978   // subexpression which we actually need to evaluate (for instance, a
12979   // template argument, array bound or an expression in a braced-init-list),
12980   // we are not permitted to instantiate this constexpr function definition.
12981   //
12982   // FIXME: This also implicitly defines special members too frequently. They
12983   // are only supposed to be implicitly defined if they are odr-used, but they
12984   // are not odr-used from constant expressions in unevaluated contexts.
12985   // However, they cannot be referenced if they are deleted, and they are
12986   // deleted whenever the implicit definition of the special member would
12987   // fail (with very few exceptions).
12988   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12989   bool NeedDefinition =
12990       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
12991                                          (MD && !MD->isUserProvided())));
12992 
12993   // C++14 [temp.expl.spec]p6:
12994   //   If a template [...] is explicitly specialized then that specialization
12995   //   shall be declared before the first use of that specialization that would
12996   //   cause an implicit instantiation to take place, in every translation unit
12997   //   in which such a use occurs
12998   if (NeedDefinition &&
12999       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13000        Func->getMemberSpecializationInfo()))
13001     checkSpecializationVisibility(Loc, Func);
13002 
13003   // If we don't need to mark the function as used, and we don't need to
13004   // try to provide a definition, there's nothing more to do.
13005   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13006       (!NeedDefinition || Func->getBody()))
13007     return;
13008 
13009   // Note that this declaration has been used.
13010   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13011     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13012     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13013       if (Constructor->isDefaultConstructor()) {
13014         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13015           return;
13016         DefineImplicitDefaultConstructor(Loc, Constructor);
13017       } else if (Constructor->isCopyConstructor()) {
13018         DefineImplicitCopyConstructor(Loc, Constructor);
13019       } else if (Constructor->isMoveConstructor()) {
13020         DefineImplicitMoveConstructor(Loc, Constructor);
13021       }
13022     } else if (Constructor->getInheritedConstructor()) {
13023       DefineInheritingConstructor(Loc, Constructor);
13024     }
13025   } else if (CXXDestructorDecl *Destructor =
13026                  dyn_cast<CXXDestructorDecl>(Func)) {
13027     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13028     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13029       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13030         return;
13031       DefineImplicitDestructor(Loc, Destructor);
13032     }
13033     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13034       MarkVTableUsed(Loc, Destructor->getParent());
13035   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13036     if (MethodDecl->isOverloadedOperator() &&
13037         MethodDecl->getOverloadedOperator() == OO_Equal) {
13038       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13039       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13040         if (MethodDecl->isCopyAssignmentOperator())
13041           DefineImplicitCopyAssignment(Loc, MethodDecl);
13042         else if (MethodDecl->isMoveAssignmentOperator())
13043           DefineImplicitMoveAssignment(Loc, MethodDecl);
13044       }
13045     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13046                MethodDecl->getParent()->isLambda()) {
13047       CXXConversionDecl *Conversion =
13048           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13049       if (Conversion->isLambdaToBlockPointerConversion())
13050         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13051       else
13052         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13053     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13054       MarkVTableUsed(Loc, MethodDecl->getParent());
13055   }
13056 
13057   // Recursive functions should be marked when used from another function.
13058   // FIXME: Is this really right?
13059   if (CurContext == Func) return;
13060 
13061   // Resolve the exception specification for any function which is
13062   // used: CodeGen will need it.
13063   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13064   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13065     ResolveExceptionSpec(Loc, FPT);
13066 
13067   // Implicit instantiation of function templates and member functions of
13068   // class templates.
13069   if (Func->isImplicitlyInstantiable()) {
13070     bool AlreadyInstantiated = false;
13071     SourceLocation PointOfInstantiation = Loc;
13072     if (FunctionTemplateSpecializationInfo *SpecInfo
13073                               = Func->getTemplateSpecializationInfo()) {
13074       if (SpecInfo->getPointOfInstantiation().isInvalid())
13075         SpecInfo->setPointOfInstantiation(Loc);
13076       else if (SpecInfo->getTemplateSpecializationKind()
13077                  == TSK_ImplicitInstantiation) {
13078         AlreadyInstantiated = true;
13079         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13080       }
13081     } else if (MemberSpecializationInfo *MSInfo
13082                                 = Func->getMemberSpecializationInfo()) {
13083       if (MSInfo->getPointOfInstantiation().isInvalid())
13084         MSInfo->setPointOfInstantiation(Loc);
13085       else if (MSInfo->getTemplateSpecializationKind()
13086                  == TSK_ImplicitInstantiation) {
13087         AlreadyInstantiated = true;
13088         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13089       }
13090     }
13091 
13092     if (!AlreadyInstantiated || Func->isConstexpr()) {
13093       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13094           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13095           ActiveTemplateInstantiations.size())
13096         PendingLocalImplicitInstantiations.push_back(
13097             std::make_pair(Func, PointOfInstantiation));
13098       else if (Func->isConstexpr())
13099         // Do not defer instantiations of constexpr functions, to avoid the
13100         // expression evaluator needing to call back into Sema if it sees a
13101         // call to such a function.
13102         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13103       else {
13104         PendingInstantiations.push_back(std::make_pair(Func,
13105                                                        PointOfInstantiation));
13106         // Notify the consumer that a function was implicitly instantiated.
13107         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13108       }
13109     }
13110   } else {
13111     // Walk redefinitions, as some of them may be instantiable.
13112     for (auto i : Func->redecls()) {
13113       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13114         MarkFunctionReferenced(Loc, i, OdrUse);
13115     }
13116   }
13117 
13118   if (!OdrUse) return;
13119 
13120   // Keep track of used but undefined functions.
13121   if (!Func->isDefined()) {
13122     if (mightHaveNonExternalLinkage(Func))
13123       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13124     else if (Func->getMostRecentDecl()->isInlined() &&
13125              !LangOpts.GNUInline &&
13126              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13127       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13128   }
13129 
13130   Func->markUsed(Context);
13131 }
13132 
13133 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,VarDecl * var,DeclContext * DC)13134 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13135                                    VarDecl *var, DeclContext *DC) {
13136   DeclContext *VarDC = var->getDeclContext();
13137 
13138   //  If the parameter still belongs to the translation unit, then
13139   //  we're actually just using one parameter in the declaration of
13140   //  the next.
13141   if (isa<ParmVarDecl>(var) &&
13142       isa<TranslationUnitDecl>(VarDC))
13143     return;
13144 
13145   // For C code, don't diagnose about capture if we're not actually in code
13146   // right now; it's impossible to write a non-constant expression outside of
13147   // function context, so we'll get other (more useful) diagnostics later.
13148   //
13149   // For C++, things get a bit more nasty... it would be nice to suppress this
13150   // diagnostic for certain cases like using a local variable in an array bound
13151   // for a member of a local class, but the correct predicate is not obvious.
13152   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13153     return;
13154 
13155   if (isa<CXXMethodDecl>(VarDC) &&
13156       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13157     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13158       << var->getIdentifier();
13159   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13160     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13161       << var->getIdentifier() << fn->getDeclName();
13162   } else if (isa<BlockDecl>(VarDC)) {
13163     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13164       << var->getIdentifier();
13165   } else {
13166     // FIXME: Is there any other context where a local variable can be
13167     // declared?
13168     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13169       << var->getIdentifier();
13170   }
13171 
13172   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13173       << var->getIdentifier();
13174 
13175   // FIXME: Add additional diagnostic info about class etc. which prevents
13176   // capture.
13177 }
13178 
13179 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)13180 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13181                                       bool &SubCapturesAreNested,
13182                                       QualType &CaptureType,
13183                                       QualType &DeclRefType) {
13184    // Check whether we've already captured it.
13185   if (CSI->CaptureMap.count(Var)) {
13186     // If we found a capture, any subcaptures are nested.
13187     SubCapturesAreNested = true;
13188 
13189     // Retrieve the capture type for this variable.
13190     CaptureType = CSI->getCapture(Var).getCaptureType();
13191 
13192     // Compute the type of an expression that refers to this variable.
13193     DeclRefType = CaptureType.getNonReferenceType();
13194 
13195     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13196     // are mutable in the sense that user can change their value - they are
13197     // private instances of the captured declarations.
13198     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13199     if (Cap.isCopyCapture() &&
13200         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13201         !(isa<CapturedRegionScopeInfo>(CSI) &&
13202           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13203       DeclRefType.addConst();
13204     return true;
13205   }
13206   return false;
13207 }
13208 
13209 // Only block literals, captured statements, and lambda expressions can
13210 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)13211 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13212                                  SourceLocation Loc,
13213                                  const bool Diagnose, Sema &S) {
13214   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13215     return getLambdaAwareParentOfDeclContext(DC);
13216   else if (Var->hasLocalStorage()) {
13217     if (Diagnose)
13218        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13219   }
13220   return nullptr;
13221 }
13222 
13223 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13224 // certain types of variables (unnamed, variably modified types etc.)
13225 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)13226 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13227                                  SourceLocation Loc,
13228                                  const bool Diagnose, Sema &S) {
13229 
13230   bool IsBlock = isa<BlockScopeInfo>(CSI);
13231   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13232 
13233   // Lambdas are not allowed to capture unnamed variables
13234   // (e.g. anonymous unions).
13235   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13236   // assuming that's the intent.
13237   if (IsLambda && !Var->getDeclName()) {
13238     if (Diagnose) {
13239       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13240       S.Diag(Var->getLocation(), diag::note_declared_at);
13241     }
13242     return false;
13243   }
13244 
13245   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13246   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13247     if (Diagnose) {
13248       S.Diag(Loc, diag::err_ref_vm_type);
13249       S.Diag(Var->getLocation(), diag::note_previous_decl)
13250         << Var->getDeclName();
13251     }
13252     return false;
13253   }
13254   // Prohibit structs with flexible array members too.
13255   // We cannot capture what is in the tail end of the struct.
13256   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13257     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13258       if (Diagnose) {
13259         if (IsBlock)
13260           S.Diag(Loc, diag::err_ref_flexarray_type);
13261         else
13262           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13263             << Var->getDeclName();
13264         S.Diag(Var->getLocation(), diag::note_previous_decl)
13265           << Var->getDeclName();
13266       }
13267       return false;
13268     }
13269   }
13270   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13271   // Lambdas and captured statements are not allowed to capture __block
13272   // variables; they don't support the expected semantics.
13273   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13274     if (Diagnose) {
13275       S.Diag(Loc, diag::err_capture_block_variable)
13276         << Var->getDeclName() << !IsLambda;
13277       S.Diag(Var->getLocation(), diag::note_previous_decl)
13278         << Var->getDeclName();
13279     }
13280     return false;
13281   }
13282 
13283   return true;
13284 }
13285 
13286 // 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)13287 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13288                                  SourceLocation Loc,
13289                                  const bool BuildAndDiagnose,
13290                                  QualType &CaptureType,
13291                                  QualType &DeclRefType,
13292                                  const bool Nested,
13293                                  Sema &S) {
13294   Expr *CopyExpr = nullptr;
13295   bool ByRef = false;
13296 
13297   // Blocks are not allowed to capture arrays.
13298   if (CaptureType->isArrayType()) {
13299     if (BuildAndDiagnose) {
13300       S.Diag(Loc, diag::err_ref_array_type);
13301       S.Diag(Var->getLocation(), diag::note_previous_decl)
13302       << Var->getDeclName();
13303     }
13304     return false;
13305   }
13306 
13307   // Forbid the block-capture of autoreleasing variables.
13308   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13309     if (BuildAndDiagnose) {
13310       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13311         << /*block*/ 0;
13312       S.Diag(Var->getLocation(), diag::note_previous_decl)
13313         << Var->getDeclName();
13314     }
13315     return false;
13316   }
13317   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13318   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13319       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13320     // Block capture by reference does not change the capture or
13321     // declaration reference types.
13322     ByRef = true;
13323   } else {
13324     // Block capture by copy introduces 'const'.
13325     CaptureType = CaptureType.getNonReferenceType().withConst();
13326     DeclRefType = CaptureType;
13327 
13328     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13329       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13330         // The capture logic needs the destructor, so make sure we mark it.
13331         // Usually this is unnecessary because most local variables have
13332         // their destructors marked at declaration time, but parameters are
13333         // an exception because it's technically only the call site that
13334         // actually requires the destructor.
13335         if (isa<ParmVarDecl>(Var))
13336           S.FinalizeVarWithDestructor(Var, Record);
13337 
13338         // Enter a new evaluation context to insulate the copy
13339         // full-expression.
13340         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13341 
13342         // According to the blocks spec, the capture of a variable from
13343         // the stack requires a const copy constructor.  This is not true
13344         // of the copy/move done to move a __block variable to the heap.
13345         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13346                                                   DeclRefType.withConst(),
13347                                                   VK_LValue, Loc);
13348 
13349         ExprResult Result
13350           = S.PerformCopyInitialization(
13351               InitializedEntity::InitializeBlock(Var->getLocation(),
13352                                                   CaptureType, false),
13353               Loc, DeclRef);
13354 
13355         // Build a full-expression copy expression if initialization
13356         // succeeded and used a non-trivial constructor.  Recover from
13357         // errors by pretending that the copy isn't necessary.
13358         if (!Result.isInvalid() &&
13359             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13360                 ->isTrivial()) {
13361           Result = S.MaybeCreateExprWithCleanups(Result);
13362           CopyExpr = Result.get();
13363         }
13364       }
13365     }
13366   }
13367 
13368   // Actually capture the variable.
13369   if (BuildAndDiagnose)
13370     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13371                     SourceLocation(), CaptureType, CopyExpr);
13372 
13373   return true;
13374 
13375 }
13376 
13377 
13378 /// \brief 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)13379 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13380                                     VarDecl *Var,
13381                                     SourceLocation Loc,
13382                                     const bool BuildAndDiagnose,
13383                                     QualType &CaptureType,
13384                                     QualType &DeclRefType,
13385                                     const bool RefersToCapturedVariable,
13386                                     Sema &S) {
13387   // By default, capture variables by reference.
13388   bool ByRef = true;
13389   // Using an LValue reference type is consistent with Lambdas (see below).
13390   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13391     if (S.IsOpenMPCapturedDecl(Var))
13392       DeclRefType = DeclRefType.getUnqualifiedType();
13393     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13394   }
13395 
13396   if (ByRef)
13397     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13398   else
13399     CaptureType = DeclRefType;
13400 
13401   Expr *CopyExpr = nullptr;
13402   if (BuildAndDiagnose) {
13403     // The current implementation assumes that all variables are captured
13404     // by references. Since there is no capture by copy, no expression
13405     // evaluation will be needed.
13406     RecordDecl *RD = RSI->TheRecordDecl;
13407 
13408     FieldDecl *Field
13409       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13410                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13411                           nullptr, false, ICIS_NoInit);
13412     Field->setImplicit(true);
13413     Field->setAccess(AS_private);
13414     RD->addDecl(Field);
13415 
13416     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13417                                             DeclRefType, VK_LValue, Loc);
13418     Var->setReferenced(true);
13419     Var->markUsed(S.Context);
13420   }
13421 
13422   // Actually capture the variable.
13423   if (BuildAndDiagnose)
13424     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13425                     SourceLocation(), CaptureType, CopyExpr);
13426 
13427 
13428   return true;
13429 }
13430 
13431 /// \brief Create a field within the lambda class for the variable
13432 /// being captured.
addAsFieldToClosureType(Sema & S,LambdaScopeInfo * LSI,QualType FieldType,QualType DeclRefType,SourceLocation Loc,bool RefersToCapturedVariable)13433 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13434                                     QualType FieldType, QualType DeclRefType,
13435                                     SourceLocation Loc,
13436                                     bool RefersToCapturedVariable) {
13437   CXXRecordDecl *Lambda = LSI->Lambda;
13438 
13439   // Build the non-static data member.
13440   FieldDecl *Field
13441     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13442                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13443                         nullptr, false, ICIS_NoInit);
13444   Field->setImplicit(true);
13445   Field->setAccess(AS_private);
13446   Lambda->addDecl(Field);
13447 }
13448 
13449 /// \brief 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)13450 static bool captureInLambda(LambdaScopeInfo *LSI,
13451                             VarDecl *Var,
13452                             SourceLocation Loc,
13453                             const bool BuildAndDiagnose,
13454                             QualType &CaptureType,
13455                             QualType &DeclRefType,
13456                             const bool RefersToCapturedVariable,
13457                             const Sema::TryCaptureKind Kind,
13458                             SourceLocation EllipsisLoc,
13459                             const bool IsTopScope,
13460                             Sema &S) {
13461 
13462   // Determine whether we are capturing by reference or by value.
13463   bool ByRef = false;
13464   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13465     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13466   } else {
13467     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13468   }
13469 
13470   // Compute the type of the field that will capture this variable.
13471   if (ByRef) {
13472     // C++11 [expr.prim.lambda]p15:
13473     //   An entity is captured by reference if it is implicitly or
13474     //   explicitly captured but not captured by copy. It is
13475     //   unspecified whether additional unnamed non-static data
13476     //   members are declared in the closure type for entities
13477     //   captured by reference.
13478     //
13479     // FIXME: It is not clear whether we want to build an lvalue reference
13480     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13481     // to do the former, while EDG does the latter. Core issue 1249 will
13482     // clarify, but for now we follow GCC because it's a more permissive and
13483     // easily defensible position.
13484     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13485   } else {
13486     // C++11 [expr.prim.lambda]p14:
13487     //   For each entity captured by copy, an unnamed non-static
13488     //   data member is declared in the closure type. The
13489     //   declaration order of these members is unspecified. The type
13490     //   of such a data member is the type of the corresponding
13491     //   captured entity if the entity is not a reference to an
13492     //   object, or the referenced type otherwise. [Note: If the
13493     //   captured entity is a reference to a function, the
13494     //   corresponding data member is also a reference to a
13495     //   function. - end note ]
13496     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13497       if (!RefType->getPointeeType()->isFunctionType())
13498         CaptureType = RefType->getPointeeType();
13499     }
13500 
13501     // Forbid the lambda copy-capture of autoreleasing variables.
13502     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13503       if (BuildAndDiagnose) {
13504         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13505         S.Diag(Var->getLocation(), diag::note_previous_decl)
13506           << Var->getDeclName();
13507       }
13508       return false;
13509     }
13510 
13511     // Make sure that by-copy captures are of a complete and non-abstract type.
13512     if (BuildAndDiagnose) {
13513       if (!CaptureType->isDependentType() &&
13514           S.RequireCompleteType(Loc, CaptureType,
13515                                 diag::err_capture_of_incomplete_type,
13516                                 Var->getDeclName()))
13517         return false;
13518 
13519       if (S.RequireNonAbstractType(Loc, CaptureType,
13520                                    diag::err_capture_of_abstract_type))
13521         return false;
13522     }
13523   }
13524 
13525   // Capture this variable in the lambda.
13526   if (BuildAndDiagnose)
13527     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13528                             RefersToCapturedVariable);
13529 
13530   // Compute the type of a reference to this captured variable.
13531   if (ByRef)
13532     DeclRefType = CaptureType.getNonReferenceType();
13533   else {
13534     // C++ [expr.prim.lambda]p5:
13535     //   The closure type for a lambda-expression has a public inline
13536     //   function call operator [...]. This function call operator is
13537     //   declared const (9.3.1) if and only if the lambda-expression’s
13538     //   parameter-declaration-clause is not followed by mutable.
13539     DeclRefType = CaptureType.getNonReferenceType();
13540     if (!LSI->Mutable && !CaptureType->isReferenceType())
13541       DeclRefType.addConst();
13542   }
13543 
13544   // Add the capture.
13545   if (BuildAndDiagnose)
13546     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13547                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13548 
13549   return true;
13550 }
13551 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)13552 bool Sema::tryCaptureVariable(
13553     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13554     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13555     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13556   // An init-capture is notionally from the context surrounding its
13557   // declaration, but its parent DC is the lambda class.
13558   DeclContext *VarDC = Var->getDeclContext();
13559   if (Var->isInitCapture())
13560     VarDC = VarDC->getParent();
13561 
13562   DeclContext *DC = CurContext;
13563   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13564       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13565   // We need to sync up the Declaration Context with the
13566   // FunctionScopeIndexToStopAt
13567   if (FunctionScopeIndexToStopAt) {
13568     unsigned FSIndex = FunctionScopes.size() - 1;
13569     while (FSIndex != MaxFunctionScopesIndex) {
13570       DC = getLambdaAwareParentOfDeclContext(DC);
13571       --FSIndex;
13572     }
13573   }
13574 
13575 
13576   // If the variable is declared in the current context, there is no need to
13577   // capture it.
13578   if (VarDC == DC) return true;
13579 
13580   // Capture global variables if it is required to use private copy of this
13581   // variable.
13582   bool IsGlobal = !Var->hasLocalStorage();
13583   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13584     return true;
13585 
13586   // Walk up the stack to determine whether we can capture the variable,
13587   // performing the "simple" checks that don't depend on type. We stop when
13588   // we've either hit the declared scope of the variable or find an existing
13589   // capture of that variable.  We start from the innermost capturing-entity
13590   // (the DC) and ensure that all intervening capturing-entities
13591   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13592   // declcontext can either capture the variable or have already captured
13593   // the variable.
13594   CaptureType = Var->getType();
13595   DeclRefType = CaptureType.getNonReferenceType();
13596   bool Nested = false;
13597   bool Explicit = (Kind != TryCapture_Implicit);
13598   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13599   do {
13600     // Only block literals, captured statements, and lambda expressions can
13601     // capture; other scopes don't work.
13602     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13603                                                               ExprLoc,
13604                                                               BuildAndDiagnose,
13605                                                               *this);
13606     // We need to check for the parent *first* because, if we *have*
13607     // private-captured a global variable, we need to recursively capture it in
13608     // intermediate blocks, lambdas, etc.
13609     if (!ParentDC) {
13610       if (IsGlobal) {
13611         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13612         break;
13613       }
13614       return true;
13615     }
13616 
13617     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13618     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13619 
13620 
13621     // Check whether we've already captured it.
13622     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13623                                              DeclRefType))
13624       break;
13625     // If we are instantiating a generic lambda call operator body,
13626     // we do not want to capture new variables.  What was captured
13627     // during either a lambdas transformation or initial parsing
13628     // should be used.
13629     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13630       if (BuildAndDiagnose) {
13631         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13632         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13633           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13634           Diag(Var->getLocation(), diag::note_previous_decl)
13635              << Var->getDeclName();
13636           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13637         } else
13638           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13639       }
13640       return true;
13641     }
13642     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13643     // certain types of variables (unnamed, variably modified types etc.)
13644     // so check for eligibility.
13645     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13646        return true;
13647 
13648     // Try to capture variable-length arrays types.
13649     if (Var->getType()->isVariablyModifiedType()) {
13650       // We're going to walk down into the type and look for VLA
13651       // expressions.
13652       QualType QTy = Var->getType();
13653       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13654         QTy = PVD->getOriginalType();
13655       captureVariablyModifiedType(Context, QTy, CSI);
13656     }
13657 
13658     if (getLangOpts().OpenMP) {
13659       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13660         // OpenMP private variables should not be captured in outer scope, so
13661         // just break here. Similarly, global variables that are captured in a
13662         // target region should not be captured outside the scope of the region.
13663         if (RSI->CapRegionKind == CR_OpenMP) {
13664           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13665           // When we detect target captures we are looking from inside the
13666           // target region, therefore we need to propagate the capture from the
13667           // enclosing region. Therefore, the capture is not initially nested.
13668           if (IsTargetCap)
13669             FunctionScopesIndex--;
13670 
13671           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13672             Nested = !IsTargetCap;
13673             DeclRefType = DeclRefType.getUnqualifiedType();
13674             CaptureType = Context.getLValueReferenceType(DeclRefType);
13675             break;
13676           }
13677         }
13678       }
13679     }
13680     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13681       // No capture-default, and this is not an explicit capture
13682       // so cannot capture this variable.
13683       if (BuildAndDiagnose) {
13684         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13685         Diag(Var->getLocation(), diag::note_previous_decl)
13686           << Var->getDeclName();
13687         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13688           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13689                diag::note_lambda_decl);
13690         // FIXME: If we error out because an outer lambda can not implicitly
13691         // capture a variable that an inner lambda explicitly captures, we
13692         // should have the inner lambda do the explicit capture - because
13693         // it makes for cleaner diagnostics later.  This would purely be done
13694         // so that the diagnostic does not misleadingly claim that a variable
13695         // can not be captured by a lambda implicitly even though it is captured
13696         // explicitly.  Suggestion:
13697         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13698         //    at the function head
13699         //  - cache the StartingDeclContext - this must be a lambda
13700         //  - captureInLambda in the innermost lambda the variable.
13701       }
13702       return true;
13703     }
13704 
13705     FunctionScopesIndex--;
13706     DC = ParentDC;
13707     Explicit = false;
13708   } while (!VarDC->Equals(DC));
13709 
13710   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13711   // computing the type of the capture at each step, checking type-specific
13712   // requirements, and adding captures if requested.
13713   // If the variable had already been captured previously, we start capturing
13714   // at the lambda nested within that one.
13715   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13716        ++I) {
13717     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13718 
13719     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13720       if (!captureInBlock(BSI, Var, ExprLoc,
13721                           BuildAndDiagnose, CaptureType,
13722                           DeclRefType, Nested, *this))
13723         return true;
13724       Nested = true;
13725     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13726       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13727                                    BuildAndDiagnose, CaptureType,
13728                                    DeclRefType, Nested, *this))
13729         return true;
13730       Nested = true;
13731     } else {
13732       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13733       if (!captureInLambda(LSI, Var, ExprLoc,
13734                            BuildAndDiagnose, CaptureType,
13735                            DeclRefType, Nested, Kind, EllipsisLoc,
13736                             /*IsTopScope*/I == N - 1, *this))
13737         return true;
13738       Nested = true;
13739     }
13740   }
13741   return false;
13742 }
13743 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)13744 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13745                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13746   QualType CaptureType;
13747   QualType DeclRefType;
13748   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13749                             /*BuildAndDiagnose=*/true, CaptureType,
13750                             DeclRefType, nullptr);
13751 }
13752 
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)13753 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13754   QualType CaptureType;
13755   QualType DeclRefType;
13756   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13757                              /*BuildAndDiagnose=*/false, CaptureType,
13758                              DeclRefType, nullptr);
13759 }
13760 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)13761 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13762   QualType CaptureType;
13763   QualType DeclRefType;
13764 
13765   // Determine whether we can capture this variable.
13766   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13767                          /*BuildAndDiagnose=*/false, CaptureType,
13768                          DeclRefType, nullptr))
13769     return QualType();
13770 
13771   return DeclRefType;
13772 }
13773 
13774 
13775 
13776 // If either the type of the variable or the initializer is dependent,
13777 // return false. Otherwise, determine whether the variable is a constant
13778 // expression. Use this if you need to know if a variable that might or
13779 // might not be dependent is truly a constant expression.
IsVariableNonDependentAndAConstantExpression(VarDecl * Var,ASTContext & Context)13780 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13781     ASTContext &Context) {
13782 
13783   if (Var->getType()->isDependentType())
13784     return false;
13785   const VarDecl *DefVD = nullptr;
13786   Var->getAnyInitializer(DefVD);
13787   if (!DefVD)
13788     return false;
13789   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13790   Expr *Init = cast<Expr>(Eval->Value);
13791   if (Init->isValueDependent())
13792     return false;
13793   return IsVariableAConstantExpression(Var, Context);
13794 }
13795 
13796 
UpdateMarkingForLValueToRValue(Expr * E)13797 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13798   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13799   // an object that satisfies the requirements for appearing in a
13800   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13801   // is immediately applied."  This function handles the lvalue-to-rvalue
13802   // conversion part.
13803   MaybeODRUseExprs.erase(E->IgnoreParens());
13804 
13805   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13806   // to a variable that is a constant expression, and if so, identify it as
13807   // a reference to a variable that does not involve an odr-use of that
13808   // variable.
13809   if (LambdaScopeInfo *LSI = getCurLambda()) {
13810     Expr *SansParensExpr = E->IgnoreParens();
13811     VarDecl *Var = nullptr;
13812     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13813       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13814     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13815       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13816 
13817     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13818       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13819   }
13820 }
13821 
ActOnConstantExpression(ExprResult Res)13822 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13823   Res = CorrectDelayedTyposInExpr(Res);
13824 
13825   if (!Res.isUsable())
13826     return Res;
13827 
13828   // If a constant-expression is a reference to a variable where we delay
13829   // deciding whether it is an odr-use, just assume we will apply the
13830   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13831   // (a non-type template argument), we have special handling anyway.
13832   UpdateMarkingForLValueToRValue(Res.get());
13833   return Res;
13834 }
13835 
CleanupVarDeclMarking()13836 void Sema::CleanupVarDeclMarking() {
13837   for (Expr *E : MaybeODRUseExprs) {
13838     VarDecl *Var;
13839     SourceLocation Loc;
13840     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13841       Var = cast<VarDecl>(DRE->getDecl());
13842       Loc = DRE->getLocation();
13843     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13844       Var = cast<VarDecl>(ME->getMemberDecl());
13845       Loc = ME->getMemberLoc();
13846     } else {
13847       llvm_unreachable("Unexpected expression");
13848     }
13849 
13850     MarkVarDeclODRUsed(Var, Loc, *this,
13851                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13852   }
13853 
13854   MaybeODRUseExprs.clear();
13855 }
13856 
13857 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)13858 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13859                                     VarDecl *Var, Expr *E) {
13860   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13861          "Invalid Expr argument to DoMarkVarDeclReferenced");
13862   Var->setReferenced();
13863 
13864   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13865   bool MarkODRUsed = true;
13866 
13867   // If the context is not potentially evaluated, this is not an odr-use and
13868   // does not trigger instantiation.
13869   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13870     if (SemaRef.isUnevaluatedContext())
13871       return;
13872 
13873     // If we don't yet know whether this context is going to end up being an
13874     // evaluated context, and we're referencing a variable from an enclosing
13875     // scope, add a potential capture.
13876     //
13877     // FIXME: Is this necessary? These contexts are only used for default
13878     // arguments, where local variables can't be used.
13879     const bool RefersToEnclosingScope =
13880         (SemaRef.CurContext != Var->getDeclContext() &&
13881          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13882     if (RefersToEnclosingScope) {
13883       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13884         // If a variable could potentially be odr-used, defer marking it so
13885         // until we finish analyzing the full expression for any
13886         // lvalue-to-rvalue
13887         // or discarded value conversions that would obviate odr-use.
13888         // Add it to the list of potential captures that will be analyzed
13889         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13890         // unless the variable is a reference that was initialized by a constant
13891         // expression (this will never need to be captured or odr-used).
13892         assert(E && "Capture variable should be used in an expression.");
13893         if (!Var->getType()->isReferenceType() ||
13894             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13895           LSI->addPotentialCapture(E->IgnoreParens());
13896       }
13897     }
13898 
13899     if (!isTemplateInstantiation(TSK))
13900       return;
13901 
13902     // Instantiate, but do not mark as odr-used, variable templates.
13903     MarkODRUsed = false;
13904   }
13905 
13906   VarTemplateSpecializationDecl *VarSpec =
13907       dyn_cast<VarTemplateSpecializationDecl>(Var);
13908   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13909          "Can't instantiate a partial template specialization.");
13910 
13911   // If this might be a member specialization of a static data member, check
13912   // the specialization is visible. We already did the checks for variable
13913   // template specializations when we created them.
13914   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13915     SemaRef.checkSpecializationVisibility(Loc, Var);
13916 
13917   // Perform implicit instantiation of static data members, static data member
13918   // templates of class templates, and variable template specializations. Delay
13919   // instantiations of variable templates, except for those that could be used
13920   // in a constant expression.
13921   if (isTemplateInstantiation(TSK)) {
13922     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13923 
13924     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13925       if (Var->getPointOfInstantiation().isInvalid()) {
13926         // This is a modification of an existing AST node. Notify listeners.
13927         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13928           L->StaticDataMemberInstantiated(Var);
13929       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13930         // Don't bother trying to instantiate it again, unless we might need
13931         // its initializer before we get to the end of the TU.
13932         TryInstantiating = false;
13933     }
13934 
13935     if (Var->getPointOfInstantiation().isInvalid())
13936       Var->setTemplateSpecializationKind(TSK, Loc);
13937 
13938     if (TryInstantiating) {
13939       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13940       bool InstantiationDependent = false;
13941       bool IsNonDependent =
13942           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13943                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13944                   : true;
13945 
13946       // Do not instantiate specializations that are still type-dependent.
13947       if (IsNonDependent) {
13948         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13949           // Do not defer instantiations of variables which could be used in a
13950           // constant expression.
13951           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13952         } else {
13953           SemaRef.PendingInstantiations
13954               .push_back(std::make_pair(Var, PointOfInstantiation));
13955         }
13956       }
13957     }
13958   }
13959 
13960   if (!MarkODRUsed)
13961     return;
13962 
13963   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13964   // the requirements for appearing in a constant expression (5.19) and, if
13965   // it is an object, the lvalue-to-rvalue conversion (4.1)
13966   // is immediately applied."  We check the first part here, and
13967   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13968   // Note that we use the C++11 definition everywhere because nothing in
13969   // C++03 depends on whether we get the C++03 version correct. The second
13970   // part does not apply to references, since they are not objects.
13971   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13972     // A reference initialized by a constant expression can never be
13973     // odr-used, so simply ignore it.
13974     if (!Var->getType()->isReferenceType())
13975       SemaRef.MaybeODRUseExprs.insert(E);
13976   } else
13977     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13978                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13979 }
13980 
13981 /// \brief Mark a variable referenced, and check whether it is odr-used
13982 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13983 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)13984 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13985   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13986 }
13987 
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse)13988 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13989                                Decl *D, Expr *E, bool MightBeOdrUse) {
13990   if (SemaRef.isInOpenMPDeclareTargetContext())
13991     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13992 
13993   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13994     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13995     return;
13996   }
13997 
13998   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
13999 
14000   // If this is a call to a method via a cast, also mark the method in the
14001   // derived class used in case codegen can devirtualize the call.
14002   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14003   if (!ME)
14004     return;
14005   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14006   if (!MD)
14007     return;
14008   // Only attempt to devirtualize if this is truly a virtual call.
14009   bool IsVirtualCall = MD->isVirtual() &&
14010                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14011   if (!IsVirtualCall)
14012     return;
14013   const Expr *Base = ME->getBase();
14014   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14015   if (!MostDerivedClassDecl)
14016     return;
14017   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14018   if (!DM || DM->isPure())
14019     return;
14020   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14021 }
14022 
14023 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E)14024 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14025   // TODO: update this with DR# once a defect report is filed.
14026   // C++11 defect. The address of a pure member should not be an ODR use, even
14027   // if it's a qualified reference.
14028   bool OdrUse = true;
14029   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14030     if (Method->isVirtual())
14031       OdrUse = false;
14032   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14033 }
14034 
14035 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)14036 void Sema::MarkMemberReferenced(MemberExpr *E) {
14037   // C++11 [basic.def.odr]p2:
14038   //   A non-overloaded function whose name appears as a potentially-evaluated
14039   //   expression or a member of a set of candidate functions, if selected by
14040   //   overload resolution when referred to from a potentially-evaluated
14041   //   expression, is odr-used, unless it is a pure virtual function and its
14042   //   name is not explicitly qualified.
14043   bool MightBeOdrUse = true;
14044   if (E->performsVirtualDispatch(getLangOpts())) {
14045     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14046       if (Method->isPure())
14047         MightBeOdrUse = false;
14048   }
14049   SourceLocation Loc = E->getMemberLoc().isValid() ?
14050                             E->getMemberLoc() : E->getLocStart();
14051   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14052 }
14053 
14054 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14055 /// marks the declaration referenced, and performs odr-use checking for
14056 /// functions and variables. This method should not be used when building a
14057 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)14058 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14059                                  bool MightBeOdrUse) {
14060   if (MightBeOdrUse) {
14061     if (auto *VD = dyn_cast<VarDecl>(D)) {
14062       MarkVariableReferenced(Loc, VD);
14063       return;
14064     }
14065   }
14066   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14067     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14068     return;
14069   }
14070   D->setReferenced();
14071 }
14072 
14073 namespace {
14074   // Mark all of the declarations referenced
14075   // FIXME: Not fully implemented yet! We need to have a better understanding
14076   // of when we're entering
14077   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14078     Sema &S;
14079     SourceLocation Loc;
14080 
14081   public:
14082     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14083 
MarkReferencedDecls(Sema & S,SourceLocation Loc)14084     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14085 
14086     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14087     bool TraverseRecordType(RecordType *T);
14088   };
14089 }
14090 
TraverseTemplateArgument(const TemplateArgument & Arg)14091 bool MarkReferencedDecls::TraverseTemplateArgument(
14092     const TemplateArgument &Arg) {
14093   if (Arg.getKind() == TemplateArgument::Declaration) {
14094     if (Decl *D = Arg.getAsDecl())
14095       S.MarkAnyDeclReferenced(Loc, D, true);
14096   }
14097 
14098   return Inherited::TraverseTemplateArgument(Arg);
14099 }
14100 
TraverseRecordType(RecordType * T)14101 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14102   if (ClassTemplateSpecializationDecl *Spec
14103                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14104     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14105     return TraverseTemplateArguments(Args.data(), Args.size());
14106   }
14107 
14108   return true;
14109 }
14110 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)14111 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14112   MarkReferencedDecls Marker(*this, Loc);
14113   Marker.TraverseType(Context.getCanonicalType(T));
14114 }
14115 
14116 namespace {
14117   /// \brief Helper class that marks all of the declarations referenced by
14118   /// potentially-evaluated subexpressions as "referenced".
14119   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14120     Sema &S;
14121     bool SkipLocalVariables;
14122 
14123   public:
14124     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14125 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)14126     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14127       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14128 
VisitDeclRefExpr(DeclRefExpr * E)14129     void VisitDeclRefExpr(DeclRefExpr *E) {
14130       // If we were asked not to visit local variables, don't.
14131       if (SkipLocalVariables) {
14132         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14133           if (VD->hasLocalStorage())
14134             return;
14135       }
14136 
14137       S.MarkDeclRefReferenced(E);
14138     }
14139 
VisitMemberExpr(MemberExpr * E)14140     void VisitMemberExpr(MemberExpr *E) {
14141       S.MarkMemberReferenced(E);
14142       Inherited::VisitMemberExpr(E);
14143     }
14144 
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)14145     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14146       S.MarkFunctionReferenced(E->getLocStart(),
14147             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14148       Visit(E->getSubExpr());
14149     }
14150 
VisitCXXNewExpr(CXXNewExpr * E)14151     void VisitCXXNewExpr(CXXNewExpr *E) {
14152       if (E->getOperatorNew())
14153         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14154       if (E->getOperatorDelete())
14155         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14156       Inherited::VisitCXXNewExpr(E);
14157     }
14158 
VisitCXXDeleteExpr(CXXDeleteExpr * E)14159     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14160       if (E->getOperatorDelete())
14161         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14162       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14163       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14164         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14165         S.MarkFunctionReferenced(E->getLocStart(),
14166                                     S.LookupDestructor(Record));
14167       }
14168 
14169       Inherited::VisitCXXDeleteExpr(E);
14170     }
14171 
VisitCXXConstructExpr(CXXConstructExpr * E)14172     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14173       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14174       Inherited::VisitCXXConstructExpr(E);
14175     }
14176 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * E)14177     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14178       Visit(E->getExpr());
14179     }
14180 
VisitImplicitCastExpr(ImplicitCastExpr * E)14181     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14182       Inherited::VisitImplicitCastExpr(E);
14183 
14184       if (E->getCastKind() == CK_LValueToRValue)
14185         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14186     }
14187   };
14188 }
14189 
14190 /// \brief Mark any declarations that appear within this expression or any
14191 /// potentially-evaluated subexpressions as "referenced".
14192 ///
14193 /// \param SkipLocalVariables If true, don't mark local variables as
14194 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)14195 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14196                                             bool SkipLocalVariables) {
14197   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14198 }
14199 
14200 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14201 /// of the program being compiled.
14202 ///
14203 /// This routine emits the given diagnostic when the code currently being
14204 /// type-checked is "potentially evaluated", meaning that there is a
14205 /// possibility that the code will actually be executable. Code in sizeof()
14206 /// expressions, code used only during overload resolution, etc., are not
14207 /// potentially evaluated. This routine will suppress such diagnostics or,
14208 /// in the absolutely nutty case of potentially potentially evaluated
14209 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14210 /// later.
14211 ///
14212 /// This routine should be used for all diagnostics that describe the run-time
14213 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14214 /// Failure to do so will likely result in spurious diagnostics or failures
14215 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)14216 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14217                                const PartialDiagnostic &PD) {
14218   switch (ExprEvalContexts.back().Context) {
14219   case Unevaluated:
14220   case UnevaluatedAbstract:
14221   case DiscardedStatement:
14222     // The argument will never be evaluated, so don't complain.
14223     break;
14224 
14225   case ConstantEvaluated:
14226     // Relevant diagnostics should be produced by constant evaluation.
14227     break;
14228 
14229   case PotentiallyEvaluated:
14230   case PotentiallyEvaluatedIfUsed:
14231     if (Statement && getCurFunctionOrMethodDecl()) {
14232       FunctionScopes.back()->PossiblyUnreachableDiags.
14233         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14234     }
14235     else
14236       Diag(Loc, PD);
14237 
14238     return true;
14239   }
14240 
14241   return false;
14242 }
14243 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)14244 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14245                                CallExpr *CE, FunctionDecl *FD) {
14246   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14247     return false;
14248 
14249   // If we're inside a decltype's expression, don't check for a valid return
14250   // type or construct temporaries until we know whether this is the last call.
14251   if (ExprEvalContexts.back().IsDecltype) {
14252     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14253     return false;
14254   }
14255 
14256   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14257     FunctionDecl *FD;
14258     CallExpr *CE;
14259 
14260   public:
14261     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14262       : FD(FD), CE(CE) { }
14263 
14264     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14265       if (!FD) {
14266         S.Diag(Loc, diag::err_call_incomplete_return)
14267           << T << CE->getSourceRange();
14268         return;
14269       }
14270 
14271       S.Diag(Loc, diag::err_call_function_incomplete_return)
14272         << CE->getSourceRange() << FD->getDeclName() << T;
14273       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14274           << FD->getDeclName();
14275     }
14276   } Diagnoser(FD, CE);
14277 
14278   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14279     return true;
14280 
14281   return false;
14282 }
14283 
14284 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14285 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)14286 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14287   SourceLocation Loc;
14288 
14289   unsigned diagnostic = diag::warn_condition_is_assignment;
14290   bool IsOrAssign = false;
14291 
14292   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14293     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14294       return;
14295 
14296     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14297 
14298     // Greylist some idioms by putting them into a warning subcategory.
14299     if (ObjCMessageExpr *ME
14300           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14301       Selector Sel = ME->getSelector();
14302 
14303       // self = [<foo> init...]
14304       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14305         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14306 
14307       // <foo> = [<bar> nextObject]
14308       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14309         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14310     }
14311 
14312     Loc = Op->getOperatorLoc();
14313   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14314     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14315       return;
14316 
14317     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14318     Loc = Op->getOperatorLoc();
14319   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14320     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14321   else {
14322     // Not an assignment.
14323     return;
14324   }
14325 
14326   Diag(Loc, diagnostic) << E->getSourceRange();
14327 
14328   SourceLocation Open = E->getLocStart();
14329   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14330   Diag(Loc, diag::note_condition_assign_silence)
14331         << FixItHint::CreateInsertion(Open, "(")
14332         << FixItHint::CreateInsertion(Close, ")");
14333 
14334   if (IsOrAssign)
14335     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14336       << FixItHint::CreateReplacement(Loc, "!=");
14337   else
14338     Diag(Loc, diag::note_condition_assign_to_comparison)
14339       << FixItHint::CreateReplacement(Loc, "==");
14340 }
14341 
14342 /// \brief Redundant parentheses over an equality comparison can indicate
14343 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)14344 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14345   // Don't warn if the parens came from a macro.
14346   SourceLocation parenLoc = ParenE->getLocStart();
14347   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14348     return;
14349   // Don't warn for dependent expressions.
14350   if (ParenE->isTypeDependent())
14351     return;
14352 
14353   Expr *E = ParenE->IgnoreParens();
14354 
14355   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14356     if (opE->getOpcode() == BO_EQ &&
14357         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14358                                                            == Expr::MLV_Valid) {
14359       SourceLocation Loc = opE->getOperatorLoc();
14360 
14361       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14362       SourceRange ParenERange = ParenE->getSourceRange();
14363       Diag(Loc, diag::note_equality_comparison_silence)
14364         << FixItHint::CreateRemoval(ParenERange.getBegin())
14365         << FixItHint::CreateRemoval(ParenERange.getEnd());
14366       Diag(Loc, diag::note_equality_comparison_to_assign)
14367         << FixItHint::CreateReplacement(Loc, "=");
14368     }
14369 }
14370 
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)14371 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14372                                        bool IsConstexpr) {
14373   DiagnoseAssignmentAsCondition(E);
14374   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14375     DiagnoseEqualityWithExtraParens(parenE);
14376 
14377   ExprResult result = CheckPlaceholderExpr(E);
14378   if (result.isInvalid()) return ExprError();
14379   E = result.get();
14380 
14381   if (!E->isTypeDependent()) {
14382     if (getLangOpts().CPlusPlus)
14383       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14384 
14385     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14386     if (ERes.isInvalid())
14387       return ExprError();
14388     E = ERes.get();
14389 
14390     QualType T = E->getType();
14391     if (!T->isScalarType()) { // C99 6.8.4.1p1
14392       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14393         << T << E->getSourceRange();
14394       return ExprError();
14395     }
14396     CheckBoolLikeConversion(E, Loc);
14397   }
14398 
14399   return E;
14400 }
14401 
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)14402 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14403                                            Expr *SubExpr, ConditionKind CK) {
14404   // Empty conditions are valid in for-statements.
14405   if (!SubExpr)
14406     return ConditionResult();
14407 
14408   ExprResult Cond;
14409   switch (CK) {
14410   case ConditionKind::Boolean:
14411     Cond = CheckBooleanCondition(Loc, SubExpr);
14412     break;
14413 
14414   case ConditionKind::ConstexprIf:
14415     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14416     break;
14417 
14418   case ConditionKind::Switch:
14419     Cond = CheckSwitchCondition(Loc, SubExpr);
14420     break;
14421   }
14422   if (Cond.isInvalid())
14423     return ConditionError();
14424 
14425   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14426   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14427   if (!FullExpr.get())
14428     return ConditionError();
14429 
14430   return ConditionResult(*this, nullptr, FullExpr,
14431                          CK == ConditionKind::ConstexprIf);
14432 }
14433 
14434 namespace {
14435   /// A visitor for rebuilding a call to an __unknown_any expression
14436   /// to have an appropriate type.
14437   struct RebuildUnknownAnyFunction
14438     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14439 
14440     Sema &S;
14441 
RebuildUnknownAnyFunction__anone84a48150b11::RebuildUnknownAnyFunction14442     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14443 
VisitStmt__anone84a48150b11::RebuildUnknownAnyFunction14444     ExprResult VisitStmt(Stmt *S) {
14445       llvm_unreachable("unexpected statement!");
14446     }
14447 
VisitExpr__anone84a48150b11::RebuildUnknownAnyFunction14448     ExprResult VisitExpr(Expr *E) {
14449       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14450         << E->getSourceRange();
14451       return ExprError();
14452     }
14453 
14454     /// Rebuild an expression which simply semantically wraps another
14455     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anone84a48150b11::RebuildUnknownAnyFunction14456     template <class T> ExprResult rebuildSugarExpr(T *E) {
14457       ExprResult SubResult = Visit(E->getSubExpr());
14458       if (SubResult.isInvalid()) return ExprError();
14459 
14460       Expr *SubExpr = SubResult.get();
14461       E->setSubExpr(SubExpr);
14462       E->setType(SubExpr->getType());
14463       E->setValueKind(SubExpr->getValueKind());
14464       assert(E->getObjectKind() == OK_Ordinary);
14465       return E;
14466     }
14467 
VisitParenExpr__anone84a48150b11::RebuildUnknownAnyFunction14468     ExprResult VisitParenExpr(ParenExpr *E) {
14469       return rebuildSugarExpr(E);
14470     }
14471 
VisitUnaryExtension__anone84a48150b11::RebuildUnknownAnyFunction14472     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14473       return rebuildSugarExpr(E);
14474     }
14475 
VisitUnaryAddrOf__anone84a48150b11::RebuildUnknownAnyFunction14476     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14477       ExprResult SubResult = Visit(E->getSubExpr());
14478       if (SubResult.isInvalid()) return ExprError();
14479 
14480       Expr *SubExpr = SubResult.get();
14481       E->setSubExpr(SubExpr);
14482       E->setType(S.Context.getPointerType(SubExpr->getType()));
14483       assert(E->getValueKind() == VK_RValue);
14484       assert(E->getObjectKind() == OK_Ordinary);
14485       return E;
14486     }
14487 
resolveDecl__anone84a48150b11::RebuildUnknownAnyFunction14488     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14489       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14490 
14491       E->setType(VD->getType());
14492 
14493       assert(E->getValueKind() == VK_RValue);
14494       if (S.getLangOpts().CPlusPlus &&
14495           !(isa<CXXMethodDecl>(VD) &&
14496             cast<CXXMethodDecl>(VD)->isInstance()))
14497         E->setValueKind(VK_LValue);
14498 
14499       return E;
14500     }
14501 
VisitMemberExpr__anone84a48150b11::RebuildUnknownAnyFunction14502     ExprResult VisitMemberExpr(MemberExpr *E) {
14503       return resolveDecl(E, E->getMemberDecl());
14504     }
14505 
VisitDeclRefExpr__anone84a48150b11::RebuildUnknownAnyFunction14506     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14507       return resolveDecl(E, E->getDecl());
14508     }
14509   };
14510 }
14511 
14512 /// Given a function expression of unknown-any type, try to rebuild it
14513 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)14514 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14515   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14516   if (Result.isInvalid()) return ExprError();
14517   return S.DefaultFunctionArrayConversion(Result.get());
14518 }
14519 
14520 namespace {
14521   /// A visitor for rebuilding an expression of type __unknown_anytype
14522   /// into one which resolves the type directly on the referring
14523   /// expression.  Strict preservation of the original source
14524   /// structure is not a goal.
14525   struct RebuildUnknownAnyExpr
14526     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14527 
14528     Sema &S;
14529 
14530     /// The current destination type.
14531     QualType DestType;
14532 
RebuildUnknownAnyExpr__anone84a48150c11::RebuildUnknownAnyExpr14533     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14534       : S(S), DestType(CastType) {}
14535 
VisitStmt__anone84a48150c11::RebuildUnknownAnyExpr14536     ExprResult VisitStmt(Stmt *S) {
14537       llvm_unreachable("unexpected statement!");
14538     }
14539 
VisitExpr__anone84a48150c11::RebuildUnknownAnyExpr14540     ExprResult VisitExpr(Expr *E) {
14541       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14542         << E->getSourceRange();
14543       return ExprError();
14544     }
14545 
14546     ExprResult VisitCallExpr(CallExpr *E);
14547     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14548 
14549     /// Rebuild an expression which simply semantically wraps another
14550     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anone84a48150c11::RebuildUnknownAnyExpr14551     template <class T> ExprResult rebuildSugarExpr(T *E) {
14552       ExprResult SubResult = Visit(E->getSubExpr());
14553       if (SubResult.isInvalid()) return ExprError();
14554       Expr *SubExpr = SubResult.get();
14555       E->setSubExpr(SubExpr);
14556       E->setType(SubExpr->getType());
14557       E->setValueKind(SubExpr->getValueKind());
14558       assert(E->getObjectKind() == OK_Ordinary);
14559       return E;
14560     }
14561 
VisitParenExpr__anone84a48150c11::RebuildUnknownAnyExpr14562     ExprResult VisitParenExpr(ParenExpr *E) {
14563       return rebuildSugarExpr(E);
14564     }
14565 
VisitUnaryExtension__anone84a48150c11::RebuildUnknownAnyExpr14566     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14567       return rebuildSugarExpr(E);
14568     }
14569 
VisitUnaryAddrOf__anone84a48150c11::RebuildUnknownAnyExpr14570     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14571       const PointerType *Ptr = DestType->getAs<PointerType>();
14572       if (!Ptr) {
14573         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14574           << E->getSourceRange();
14575         return ExprError();
14576       }
14577       assert(E->getValueKind() == VK_RValue);
14578       assert(E->getObjectKind() == OK_Ordinary);
14579       E->setType(DestType);
14580 
14581       // Build the sub-expression as if it were an object of the pointee type.
14582       DestType = Ptr->getPointeeType();
14583       ExprResult SubResult = Visit(E->getSubExpr());
14584       if (SubResult.isInvalid()) return ExprError();
14585       E->setSubExpr(SubResult.get());
14586       return E;
14587     }
14588 
14589     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14590 
14591     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14592 
VisitMemberExpr__anone84a48150c11::RebuildUnknownAnyExpr14593     ExprResult VisitMemberExpr(MemberExpr *E) {
14594       return resolveDecl(E, E->getMemberDecl());
14595     }
14596 
VisitDeclRefExpr__anone84a48150c11::RebuildUnknownAnyExpr14597     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14598       return resolveDecl(E, E->getDecl());
14599     }
14600   };
14601 }
14602 
14603 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)14604 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14605   Expr *CalleeExpr = E->getCallee();
14606 
14607   enum FnKind {
14608     FK_MemberFunction,
14609     FK_FunctionPointer,
14610     FK_BlockPointer
14611   };
14612 
14613   FnKind Kind;
14614   QualType CalleeType = CalleeExpr->getType();
14615   if (CalleeType == S.Context.BoundMemberTy) {
14616     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14617     Kind = FK_MemberFunction;
14618     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14619   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14620     CalleeType = Ptr->getPointeeType();
14621     Kind = FK_FunctionPointer;
14622   } else {
14623     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14624     Kind = FK_BlockPointer;
14625   }
14626   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14627 
14628   // Verify that this is a legal result type of a function.
14629   if (DestType->isArrayType() || DestType->isFunctionType()) {
14630     unsigned diagID = diag::err_func_returning_array_function;
14631     if (Kind == FK_BlockPointer)
14632       diagID = diag::err_block_returning_array_function;
14633 
14634     S.Diag(E->getExprLoc(), diagID)
14635       << DestType->isFunctionType() << DestType;
14636     return ExprError();
14637   }
14638 
14639   // Otherwise, go ahead and set DestType as the call's result.
14640   E->setType(DestType.getNonLValueExprType(S.Context));
14641   E->setValueKind(Expr::getValueKindForType(DestType));
14642   assert(E->getObjectKind() == OK_Ordinary);
14643 
14644   // Rebuild the function type, replacing the result type with DestType.
14645   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14646   if (Proto) {
14647     // __unknown_anytype(...) is a special case used by the debugger when
14648     // it has no idea what a function's signature is.
14649     //
14650     // We want to build this call essentially under the K&R
14651     // unprototyped rules, but making a FunctionNoProtoType in C++
14652     // would foul up all sorts of assumptions.  However, we cannot
14653     // simply pass all arguments as variadic arguments, nor can we
14654     // portably just call the function under a non-variadic type; see
14655     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14656     // However, it turns out that in practice it is generally safe to
14657     // call a function declared as "A foo(B,C,D);" under the prototype
14658     // "A foo(B,C,D,...);".  The only known exception is with the
14659     // Windows ABI, where any variadic function is implicitly cdecl
14660     // regardless of its normal CC.  Therefore we change the parameter
14661     // types to match the types of the arguments.
14662     //
14663     // This is a hack, but it is far superior to moving the
14664     // corresponding target-specific code from IR-gen to Sema/AST.
14665 
14666     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14667     SmallVector<QualType, 8> ArgTypes;
14668     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14669       ArgTypes.reserve(E->getNumArgs());
14670       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14671         Expr *Arg = E->getArg(i);
14672         QualType ArgType = Arg->getType();
14673         if (E->isLValue()) {
14674           ArgType = S.Context.getLValueReferenceType(ArgType);
14675         } else if (E->isXValue()) {
14676           ArgType = S.Context.getRValueReferenceType(ArgType);
14677         }
14678         ArgTypes.push_back(ArgType);
14679       }
14680       ParamTypes = ArgTypes;
14681     }
14682     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14683                                          Proto->getExtProtoInfo());
14684   } else {
14685     DestType = S.Context.getFunctionNoProtoType(DestType,
14686                                                 FnType->getExtInfo());
14687   }
14688 
14689   // Rebuild the appropriate pointer-to-function type.
14690   switch (Kind) {
14691   case FK_MemberFunction:
14692     // Nothing to do.
14693     break;
14694 
14695   case FK_FunctionPointer:
14696     DestType = S.Context.getPointerType(DestType);
14697     break;
14698 
14699   case FK_BlockPointer:
14700     DestType = S.Context.getBlockPointerType(DestType);
14701     break;
14702   }
14703 
14704   // Finally, we can recurse.
14705   ExprResult CalleeResult = Visit(CalleeExpr);
14706   if (!CalleeResult.isUsable()) return ExprError();
14707   E->setCallee(CalleeResult.get());
14708 
14709   // Bind a temporary if necessary.
14710   return S.MaybeBindToTemporary(E);
14711 }
14712 
VisitObjCMessageExpr(ObjCMessageExpr * E)14713 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14714   // Verify that this is a legal result type of a call.
14715   if (DestType->isArrayType() || DestType->isFunctionType()) {
14716     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14717       << DestType->isFunctionType() << DestType;
14718     return ExprError();
14719   }
14720 
14721   // Rewrite the method result type if available.
14722   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14723     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14724     Method->setReturnType(DestType);
14725   }
14726 
14727   // Change the type of the message.
14728   E->setType(DestType.getNonReferenceType());
14729   E->setValueKind(Expr::getValueKindForType(DestType));
14730 
14731   return S.MaybeBindToTemporary(E);
14732 }
14733 
VisitImplicitCastExpr(ImplicitCastExpr * E)14734 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14735   // The only case we should ever see here is a function-to-pointer decay.
14736   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14737     assert(E->getValueKind() == VK_RValue);
14738     assert(E->getObjectKind() == OK_Ordinary);
14739 
14740     E->setType(DestType);
14741 
14742     // Rebuild the sub-expression as the pointee (function) type.
14743     DestType = DestType->castAs<PointerType>()->getPointeeType();
14744 
14745     ExprResult Result = Visit(E->getSubExpr());
14746     if (!Result.isUsable()) return ExprError();
14747 
14748     E->setSubExpr(Result.get());
14749     return E;
14750   } else if (E->getCastKind() == CK_LValueToRValue) {
14751     assert(E->getValueKind() == VK_RValue);
14752     assert(E->getObjectKind() == OK_Ordinary);
14753 
14754     assert(isa<BlockPointerType>(E->getType()));
14755 
14756     E->setType(DestType);
14757 
14758     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14759     DestType = S.Context.getLValueReferenceType(DestType);
14760 
14761     ExprResult Result = Visit(E->getSubExpr());
14762     if (!Result.isUsable()) return ExprError();
14763 
14764     E->setSubExpr(Result.get());
14765     return E;
14766   } else {
14767     llvm_unreachable("Unhandled cast type!");
14768   }
14769 }
14770 
resolveDecl(Expr * E,ValueDecl * VD)14771 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14772   ExprValueKind ValueKind = VK_LValue;
14773   QualType Type = DestType;
14774 
14775   // We know how to make this work for certain kinds of decls:
14776 
14777   //  - functions
14778   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14779     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14780       DestType = Ptr->getPointeeType();
14781       ExprResult Result = resolveDecl(E, VD);
14782       if (Result.isInvalid()) return ExprError();
14783       return S.ImpCastExprToType(Result.get(), Type,
14784                                  CK_FunctionToPointerDecay, VK_RValue);
14785     }
14786 
14787     if (!Type->isFunctionType()) {
14788       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14789         << VD << E->getSourceRange();
14790       return ExprError();
14791     }
14792     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14793       // We must match the FunctionDecl's type to the hack introduced in
14794       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14795       // type. See the lengthy commentary in that routine.
14796       QualType FDT = FD->getType();
14797       const FunctionType *FnType = FDT->castAs<FunctionType>();
14798       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14799       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14800       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14801         SourceLocation Loc = FD->getLocation();
14802         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14803                                       FD->getDeclContext(),
14804                                       Loc, Loc, FD->getNameInfo().getName(),
14805                                       DestType, FD->getTypeSourceInfo(),
14806                                       SC_None, false/*isInlineSpecified*/,
14807                                       FD->hasPrototype(),
14808                                       false/*isConstexprSpecified*/);
14809 
14810         if (FD->getQualifier())
14811           NewFD->setQualifierInfo(FD->getQualifierLoc());
14812 
14813         SmallVector<ParmVarDecl*, 16> Params;
14814         for (const auto &AI : FT->param_types()) {
14815           ParmVarDecl *Param =
14816             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14817           Param->setScopeInfo(0, Params.size());
14818           Params.push_back(Param);
14819         }
14820         NewFD->setParams(Params);
14821         DRE->setDecl(NewFD);
14822         VD = DRE->getDecl();
14823       }
14824     }
14825 
14826     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14827       if (MD->isInstance()) {
14828         ValueKind = VK_RValue;
14829         Type = S.Context.BoundMemberTy;
14830       }
14831 
14832     // Function references aren't l-values in C.
14833     if (!S.getLangOpts().CPlusPlus)
14834       ValueKind = VK_RValue;
14835 
14836   //  - variables
14837   } else if (isa<VarDecl>(VD)) {
14838     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14839       Type = RefTy->getPointeeType();
14840     } else if (Type->isFunctionType()) {
14841       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14842         << VD << E->getSourceRange();
14843       return ExprError();
14844     }
14845 
14846   //  - nothing else
14847   } else {
14848     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14849       << VD << E->getSourceRange();
14850     return ExprError();
14851   }
14852 
14853   // Modifying the declaration like this is friendly to IR-gen but
14854   // also really dangerous.
14855   VD->setType(DestType);
14856   E->setType(Type);
14857   E->setValueKind(ValueKind);
14858   return E;
14859 }
14860 
14861 /// Check a cast of an unknown-any type.  We intentionally only
14862 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)14863 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14864                                      Expr *CastExpr, CastKind &CastKind,
14865                                      ExprValueKind &VK, CXXCastPath &Path) {
14866   // The type we're casting to must be either void or complete.
14867   if (!CastType->isVoidType() &&
14868       RequireCompleteType(TypeRange.getBegin(), CastType,
14869                           diag::err_typecheck_cast_to_incomplete))
14870     return ExprError();
14871 
14872   // Rewrite the casted expression from scratch.
14873   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14874   if (!result.isUsable()) return ExprError();
14875 
14876   CastExpr = result.get();
14877   VK = CastExpr->getValueKind();
14878   CastKind = CK_NoOp;
14879 
14880   return CastExpr;
14881 }
14882 
forceUnknownAnyToType(Expr * E,QualType ToType)14883 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14884   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14885 }
14886 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)14887 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14888                                     Expr *arg, QualType &paramType) {
14889   // If the syntactic form of the argument is not an explicit cast of
14890   // any sort, just do default argument promotion.
14891   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14892   if (!castArg) {
14893     ExprResult result = DefaultArgumentPromotion(arg);
14894     if (result.isInvalid()) return ExprError();
14895     paramType = result.get()->getType();
14896     return result;
14897   }
14898 
14899   // Otherwise, use the type that was written in the explicit cast.
14900   assert(!arg->hasPlaceholderType());
14901   paramType = castArg->getTypeAsWritten();
14902 
14903   // Copy-initialize a parameter of that type.
14904   InitializedEntity entity =
14905     InitializedEntity::InitializeParameter(Context, paramType,
14906                                            /*consumed*/ false);
14907   return PerformCopyInitialization(entity, callLoc, arg);
14908 }
14909 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)14910 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14911   Expr *orig = E;
14912   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14913   while (true) {
14914     E = E->IgnoreParenImpCasts();
14915     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14916       E = call->getCallee();
14917       diagID = diag::err_uncasted_call_of_unknown_any;
14918     } else {
14919       break;
14920     }
14921   }
14922 
14923   SourceLocation loc;
14924   NamedDecl *d;
14925   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14926     loc = ref->getLocation();
14927     d = ref->getDecl();
14928   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14929     loc = mem->getMemberLoc();
14930     d = mem->getMemberDecl();
14931   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14932     diagID = diag::err_uncasted_call_of_unknown_any;
14933     loc = msg->getSelectorStartLoc();
14934     d = msg->getMethodDecl();
14935     if (!d) {
14936       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14937         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14938         << orig->getSourceRange();
14939       return ExprError();
14940     }
14941   } else {
14942     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14943       << E->getSourceRange();
14944     return ExprError();
14945   }
14946 
14947   S.Diag(loc, diagID) << d << orig->getSourceRange();
14948 
14949   // Never recoverable.
14950   return ExprError();
14951 }
14952 
14953 /// Check for operands with placeholder types and complain if found.
14954 /// Returns true if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)14955 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14956   if (!getLangOpts().CPlusPlus) {
14957     // C cannot handle TypoExpr nodes on either side of a binop because it
14958     // doesn't handle dependent types properly, so make sure any TypoExprs have
14959     // been dealt with before checking the operands.
14960     ExprResult Result = CorrectDelayedTyposInExpr(E);
14961     if (!Result.isUsable()) return ExprError();
14962     E = Result.get();
14963   }
14964 
14965   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14966   if (!placeholderType) return E;
14967 
14968   switch (placeholderType->getKind()) {
14969 
14970   // Overloaded expressions.
14971   case BuiltinType::Overload: {
14972     // Try to resolve a single function template specialization.
14973     // This is obligatory.
14974     ExprResult Result = E;
14975     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
14976       return Result;
14977 
14978     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
14979     // leaves Result unchanged on failure.
14980     Result = E;
14981     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
14982       return Result;
14983 
14984     // If that failed, try to recover with a call.
14985     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
14986                          /*complain*/ true);
14987     return Result;
14988   }
14989 
14990   // Bound member functions.
14991   case BuiltinType::BoundMember: {
14992     ExprResult result = E;
14993     const Expr *BME = E->IgnoreParens();
14994     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14995     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14996     if (isa<CXXPseudoDestructorExpr>(BME)) {
14997       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14998     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14999       if (ME->getMemberNameInfo().getName().getNameKind() ==
15000           DeclarationName::CXXDestructorName)
15001         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15002     }
15003     tryToRecoverWithCall(result, PD,
15004                          /*complain*/ true);
15005     return result;
15006   }
15007 
15008   // ARC unbridged casts.
15009   case BuiltinType::ARCUnbridgedCast: {
15010     Expr *realCast = stripARCUnbridgedCast(E);
15011     diagnoseARCUnbridgedCast(realCast);
15012     return realCast;
15013   }
15014 
15015   // Expressions of unknown type.
15016   case BuiltinType::UnknownAny:
15017     return diagnoseUnknownAnyExpr(*this, E);
15018 
15019   // Pseudo-objects.
15020   case BuiltinType::PseudoObject:
15021     return checkPseudoObjectRValue(E);
15022 
15023   case BuiltinType::BuiltinFn: {
15024     // Accept __noop without parens by implicitly converting it to a call expr.
15025     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15026     if (DRE) {
15027       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15028       if (FD->getBuiltinID() == Builtin::BI__noop) {
15029         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15030                               CK_BuiltinFnToFnPtr).get();
15031         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15032                                       VK_RValue, SourceLocation());
15033       }
15034     }
15035 
15036     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15037     return ExprError();
15038   }
15039 
15040   // Expressions of unknown type.
15041   case BuiltinType::OMPArraySection:
15042     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15043     return ExprError();
15044 
15045   // Everything else should be impossible.
15046 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15047   case BuiltinType::Id:
15048 #include "clang/Basic/OpenCLImageTypes.def"
15049 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15050 #define PLACEHOLDER_TYPE(Id, SingletonId)
15051 #include "clang/AST/BuiltinTypes.def"
15052     break;
15053   }
15054 
15055   llvm_unreachable("invalid placeholder type!");
15056 }
15057 
CheckCaseExpression(Expr * E)15058 bool Sema::CheckCaseExpression(Expr *E) {
15059   if (E->isTypeDependent())
15060     return true;
15061   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15062     return E->getType()->isIntegralOrEnumerationType();
15063   return false;
15064 }
15065 
15066 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15067 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)15068 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15069   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15070          "Unknown Objective-C Boolean value!");
15071   QualType BoolT = Context.ObjCBuiltinBoolTy;
15072   if (!Context.getBOOLDecl()) {
15073     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15074                         Sema::LookupOrdinaryName);
15075     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15076       NamedDecl *ND = Result.getFoundDecl();
15077       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15078         Context.setBOOLDecl(TD);
15079     }
15080   }
15081   if (Context.getBOOLDecl())
15082     BoolT = Context.getBOOLType();
15083   return new (Context)
15084       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15085 }
15086