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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/Support/ConvertUTF.h"
46 using namespace clang;
47 using namespace sema;
48 
49 /// \brief Determine whether the use of this declaration is valid, without
50 /// emitting diagnostics.
CanUseDecl(NamedDecl * D)51 bool Sema::CanUseDecl(NamedDecl *D) {
52   // See if this is an auto-typed variable whose initializer we are parsing.
53   if (ParsingInitForAutoVars.count(D))
54     return false;
55 
56   // See if this is a deleted function.
57   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58     if (FD->isDeleted())
59       return false;
60 
61     // If the function has a deduced return type, and we can't deduce it,
62     // then we can't use it either.
63     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
64         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
65       return false;
66   }
67 
68   // See if this function is unavailable.
69   if (D->getAvailability() == AR_Unavailable &&
70       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71     return false;
72 
73   return true;
74 }
75 
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77   // Warn if this is used but marked unused.
78   if (D->hasAttr<UnusedAttr>()) {
79     const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
80     if (DC && !DC->hasAttr<UnusedAttr>())
81       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82   }
83 }
84 
HasRedeclarationWithoutAvailabilityInCategory(const Decl * D)85 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
86   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
87   if (!OMD)
88     return false;
89   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
90   if (!OID)
91     return false;
92 
93   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
94     if (ObjCMethodDecl *CatMeth =
95             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
96       if (!CatMeth->hasAttr<AvailabilityAttr>())
97         return true;
98   return false;
99 }
100 
101 static AvailabilityResult
DiagnoseAvailabilityOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)102 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
103                            const ObjCInterfaceDecl *UnknownObjCClass,
104                            bool ObjCPropertyAccess) {
105   // See if this declaration is unavailable or deprecated.
106   std::string Message;
107 
108   // Forward class declarations get their attributes from their definition.
109   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
110     if (IDecl->getDefinition())
111       D = IDecl->getDefinition();
112   }
113   AvailabilityResult Result = D->getAvailability(&Message);
114   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
115     if (Result == AR_Available) {
116       const DeclContext *DC = ECD->getDeclContext();
117       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
118         Result = TheEnumDecl->getAvailability(&Message);
119     }
120 
121   const ObjCPropertyDecl *ObjCPDecl = nullptr;
122   if (Result == AR_Deprecated || Result == AR_Unavailable ||
123       AR_NotYetIntroduced) {
124     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
125       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
126         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
127         if (PDeclResult == Result)
128           ObjCPDecl = PD;
129       }
130     }
131   }
132 
133   switch (Result) {
134     case AR_Available:
135       break;
136 
137     case AR_Deprecated:
138       if (S.getCurContextAvailability() != AR_Deprecated)
139         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
140                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
141                                   ObjCPropertyAccess);
142       break;
143 
144     case AR_NotYetIntroduced: {
145       // Don't do this for enums, they can't be redeclared.
146       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
147         break;
148 
149       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
150       // Objective-C method declarations in categories are not modelled as
151       // redeclarations, so manually look for a redeclaration in a category
152       // if necessary.
153       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
154         Warn = false;
155       // In general, D will point to the most recent redeclaration. However,
156       // for `@class A;` decls, this isn't true -- manually go through the
157       // redecl chain in that case.
158       if (Warn && isa<ObjCInterfaceDecl>(D))
159         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
160              Redecl = Redecl->getPreviousDecl())
161           if (!Redecl->hasAttr<AvailabilityAttr>() ||
162               Redecl->getAttr<AvailabilityAttr>()->isInherited())
163             Warn = false;
164 
165       if (Warn)
166         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
167                                   UnknownObjCClass, ObjCPDecl,
168                                   ObjCPropertyAccess);
169       break;
170     }
171 
172     case AR_Unavailable:
173       if (S.getCurContextAvailability() != AR_Unavailable)
174         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
175                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
176                                   ObjCPropertyAccess);
177       break;
178 
179     }
180     return Result;
181 }
182 
183 /// \brief Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)184 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
185   assert(Decl->isDeleted());
186 
187   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
188 
189   if (Method && Method->isDeleted() && Method->isDefaulted()) {
190     // If the method was explicitly defaulted, point at that declaration.
191     if (!Method->isImplicit())
192       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
193 
194     // Try to diagnose why this special member function was implicitly
195     // deleted. This might fail, if that reason no longer applies.
196     CXXSpecialMember CSM = getSpecialMember(Method);
197     if (CSM != CXXInvalid)
198       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
199 
200     return;
201   }
202 
203   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
204     if (CXXConstructorDecl *BaseCD =
205             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
206       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
207       if (BaseCD->isDeleted()) {
208         NoteDeletedFunction(BaseCD);
209       } else {
210         // FIXME: An explanation of why exactly it can't be inherited
211         // would be nice.
212         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
213       }
214       return;
215     }
216   }
217 
218   Diag(Decl->getLocation(), diag::note_availability_specified_here)
219     << Decl << true;
220 }
221 
222 /// \brief Determine whether a FunctionDecl was ever declared with an
223 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)224 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
225   for (auto I : D->redecls()) {
226     if (I->getStorageClass() != SC_None)
227       return true;
228   }
229   return false;
230 }
231 
232 /// \brief Check whether we're in an extern inline function and referring to a
233 /// variable or function with internal linkage (C11 6.7.4p3).
234 ///
235 /// This is only a warning because we used to silently accept this code, but
236 /// in many cases it will not behave correctly. This is not enabled in C++ mode
237 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
238 /// and so while there may still be user mistakes, most of the time we can't
239 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)240 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
241                                                       const NamedDecl *D,
242                                                       SourceLocation Loc) {
243   // This is disabled under C++; there are too many ways for this to fire in
244   // contexts where the warning is a false positive, or where it is technically
245   // correct but benign.
246   if (S.getLangOpts().CPlusPlus)
247     return;
248 
249   // Check if this is an inlined function or method.
250   FunctionDecl *Current = S.getCurFunctionDecl();
251   if (!Current)
252     return;
253   if (!Current->isInlined())
254     return;
255   if (!Current->isExternallyVisible())
256     return;
257 
258   // Check if the decl has internal linkage.
259   if (D->getFormalLinkage() != InternalLinkage)
260     return;
261 
262   // Downgrade from ExtWarn to Extension if
263   //  (1) the supposedly external inline function is in the main file,
264   //      and probably won't be included anywhere else.
265   //  (2) the thing we're referencing is a pure function.
266   //  (3) the thing we're referencing is another inline function.
267   // This last can give us false negatives, but it's better than warning on
268   // wrappers for simple C library functions.
269   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
270   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
271   if (!DowngradeWarning && UsedFn)
272     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
273 
274   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
275                                : diag::ext_internal_in_extern_inline)
276     << /*IsVar=*/!UsedFn << D;
277 
278   S.MaybeSuggestAddingStaticToDecl(Current);
279 
280   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
281       << D;
282 }
283 
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)284 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
285   const FunctionDecl *First = Cur->getFirstDecl();
286 
287   // Suggest "static" on the function, if possible.
288   if (!hasAnyExplicitStorageClass(First)) {
289     SourceLocation DeclBegin = First->getSourceRange().getBegin();
290     Diag(DeclBegin, diag::note_convert_inline_to_static)
291       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
292   }
293 }
294 
295 /// \brief Determine whether the use of this declaration is valid, and
296 /// emit any corresponding diagnostics.
297 ///
298 /// This routine diagnoses various problems with referencing
299 /// declarations that can occur when using a declaration. For example,
300 /// it might warn if a deprecated or unavailable declaration is being
301 /// used, or produce an error (and return true) if a C++0x deleted
302 /// function is being used.
303 ///
304 /// \returns true if there was an error (this declaration cannot be
305 /// referenced), false otherwise.
306 ///
DiagnoseUseOfDecl(NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)307 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
308                              const ObjCInterfaceDecl *UnknownObjCClass,
309                              bool ObjCPropertyAccess) {
310   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
311     // If there were any diagnostics suppressed by template argument deduction,
312     // emit them now.
313     SuppressedDiagnosticsMap::iterator
314       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
315     if (Pos != SuppressedDiagnostics.end()) {
316       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
317       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
318         Diag(Suppressed[I].first, Suppressed[I].second);
319 
320       // Clear out the list of suppressed diagnostics, so that we don't emit
321       // them again for this specialization. However, we don't obsolete this
322       // entry from the table, because we want to avoid ever emitting these
323       // diagnostics again.
324       Suppressed.clear();
325     }
326 
327     // C++ [basic.start.main]p3:
328     //   The function 'main' shall not be used within a program.
329     if (cast<FunctionDecl>(D)->isMain())
330       Diag(Loc, diag::ext_main_used);
331   }
332 
333   // See if this is an auto-typed variable whose initializer we are parsing.
334   if (ParsingInitForAutoVars.count(D)) {
335     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
336       << D->getDeclName();
337     return true;
338   }
339 
340   // See if this is a deleted function.
341   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
342     if (FD->isDeleted()) {
343       Diag(Loc, diag::err_deleted_function_use);
344       NoteDeletedFunction(FD);
345       return true;
346     }
347 
348     // If the function has a deduced return type, and we can't deduce it,
349     // then we can't use it either.
350     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
351         DeduceReturnType(FD, Loc))
352       return true;
353   }
354   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
355                              ObjCPropertyAccess);
356 
357   DiagnoseUnusedOfDecl(*this, D, Loc);
358 
359   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
360 
361   return false;
362 }
363 
364 /// \brief Retrieve the message suffix that should be added to a
365 /// diagnostic complaining about the given function being deleted or
366 /// unavailable.
getDeletedOrUnavailableSuffix(const FunctionDecl * FD)367 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
368   std::string Message;
369   if (FD->getAvailability(&Message))
370     return ": " + Message;
371 
372   return std::string();
373 }
374 
375 /// DiagnoseSentinelCalls - This routine checks whether a call or
376 /// message-send is to a declaration with the sentinel attribute, and
377 /// if so, it checks that the requirements of the sentinel are
378 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)379 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
380                                  ArrayRef<Expr *> Args) {
381   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
382   if (!attr)
383     return;
384 
385   // The number of formal parameters of the declaration.
386   unsigned numFormalParams;
387 
388   // The kind of declaration.  This is also an index into a %select in
389   // the diagnostic.
390   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
391 
392   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
393     numFormalParams = MD->param_size();
394     calleeType = CT_Method;
395   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
396     numFormalParams = FD->param_size();
397     calleeType = CT_Function;
398   } else if (isa<VarDecl>(D)) {
399     QualType type = cast<ValueDecl>(D)->getType();
400     const FunctionType *fn = nullptr;
401     if (const PointerType *ptr = type->getAs<PointerType>()) {
402       fn = ptr->getPointeeType()->getAs<FunctionType>();
403       if (!fn) return;
404       calleeType = CT_Function;
405     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
406       fn = ptr->getPointeeType()->castAs<FunctionType>();
407       calleeType = CT_Block;
408     } else {
409       return;
410     }
411 
412     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
413       numFormalParams = proto->getNumParams();
414     } else {
415       numFormalParams = 0;
416     }
417   } else {
418     return;
419   }
420 
421   // "nullPos" is the number of formal parameters at the end which
422   // effectively count as part of the variadic arguments.  This is
423   // useful if you would prefer to not have *any* formal parameters,
424   // but the language forces you to have at least one.
425   unsigned nullPos = attr->getNullPos();
426   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
427   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
428 
429   // The number of arguments which should follow the sentinel.
430   unsigned numArgsAfterSentinel = attr->getSentinel();
431 
432   // If there aren't enough arguments for all the formal parameters,
433   // the sentinel, and the args after the sentinel, complain.
434   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
435     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
436     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
437     return;
438   }
439 
440   // Otherwise, find the sentinel expression.
441   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
442   if (!sentinelExpr) return;
443   if (sentinelExpr->isValueDependent()) return;
444   if (Context.isSentinelNullExpr(sentinelExpr)) return;
445 
446   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
447   // or 'NULL' if those are actually defined in the context.  Only use
448   // 'nil' for ObjC methods, where it's much more likely that the
449   // variadic arguments form a list of object pointers.
450   SourceLocation MissingNilLoc
451     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
452   std::string NullValue;
453   if (calleeType == CT_Method &&
454       PP.getIdentifierInfo("nil")->hasMacroDefinition())
455     NullValue = "nil";
456   else if (getLangOpts().CPlusPlus11)
457     NullValue = "nullptr";
458   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
459     NullValue = "NULL";
460   else
461     NullValue = "(void*) 0";
462 
463   if (MissingNilLoc.isInvalid())
464     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
465   else
466     Diag(MissingNilLoc, diag::warn_missing_sentinel)
467       << int(calleeType)
468       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
469   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
470 }
471 
getExprRange(Expr * E) const472 SourceRange Sema::getExprRange(Expr *E) const {
473   return E ? E->getSourceRange() : SourceRange();
474 }
475 
476 //===----------------------------------------------------------------------===//
477 //  Standard Promotions and Conversions
478 //===----------------------------------------------------------------------===//
479 
480 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E)481 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
482   // Handle any placeholder expressions which made it here.
483   if (E->getType()->isPlaceholderType()) {
484     ExprResult result = CheckPlaceholderExpr(E);
485     if (result.isInvalid()) return ExprError();
486     E = result.get();
487   }
488 
489   QualType Ty = E->getType();
490   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
491 
492   if (Ty->isFunctionType()) {
493     // If we are here, we are not calling a function but taking
494     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
495     if (getLangOpts().OpenCL) {
496       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
497       return ExprError();
498     }
499     E = ImpCastExprToType(E, Context.getPointerType(Ty),
500                           CK_FunctionToPointerDecay).get();
501   } else if (Ty->isArrayType()) {
502     // In C90 mode, arrays only promote to pointers if the array expression is
503     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
504     // type 'array of type' is converted to an expression that has type 'pointer
505     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
506     // that has type 'array of type' ...".  The relevant change is "an lvalue"
507     // (C90) to "an expression" (C99).
508     //
509     // C++ 4.2p1:
510     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
511     // T" can be converted to an rvalue of type "pointer to T".
512     //
513     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
514       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
515                             CK_ArrayToPointerDecay).get();
516   }
517   return E;
518 }
519 
CheckForNullPointerDereference(Sema & S,Expr * E)520 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
521   // Check to see if we are dereferencing a null pointer.  If so,
522   // and if not volatile-qualified, this is undefined behavior that the
523   // optimizer will delete, so warn about it.  People sometimes try to use this
524   // to get a deterministic trap and are surprised by clang's behavior.  This
525   // only handles the pattern "*null", which is a very syntactic check.
526   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
527     if (UO->getOpcode() == UO_Deref &&
528         UO->getSubExpr()->IgnoreParenCasts()->
529           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
530         !UO->getType().isVolatileQualified()) {
531     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
532                           S.PDiag(diag::warn_indirection_through_null)
533                             << UO->getSubExpr()->getSourceRange());
534     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
535                         S.PDiag(diag::note_indirection_through_null));
536   }
537 }
538 
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)539 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
540                                     SourceLocation AssignLoc,
541                                     const Expr* RHS) {
542   const ObjCIvarDecl *IV = OIRE->getDecl();
543   if (!IV)
544     return;
545 
546   DeclarationName MemberName = IV->getDeclName();
547   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
548   if (!Member || !Member->isStr("isa"))
549     return;
550 
551   const Expr *Base = OIRE->getBase();
552   QualType BaseType = Base->getType();
553   if (OIRE->isArrow())
554     BaseType = BaseType->getPointeeType();
555   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
556     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
557       ObjCInterfaceDecl *ClassDeclared = nullptr;
558       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
559       if (!ClassDeclared->getSuperClass()
560           && (*ClassDeclared->ivar_begin()) == IV) {
561         if (RHS) {
562           NamedDecl *ObjectSetClass =
563             S.LookupSingleName(S.TUScope,
564                                &S.Context.Idents.get("object_setClass"),
565                                SourceLocation(), S.LookupOrdinaryName);
566           if (ObjectSetClass) {
567             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
568             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
569             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
570             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
571                                                      AssignLoc), ",") <<
572             FixItHint::CreateInsertion(RHSLocEnd, ")");
573           }
574           else
575             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
576         } else {
577           NamedDecl *ObjectGetClass =
578             S.LookupSingleName(S.TUScope,
579                                &S.Context.Idents.get("object_getClass"),
580                                SourceLocation(), S.LookupOrdinaryName);
581           if (ObjectGetClass)
582             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
583             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
584             FixItHint::CreateReplacement(
585                                          SourceRange(OIRE->getOpLoc(),
586                                                      OIRE->getLocEnd()), ")");
587           else
588             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
589         }
590         S.Diag(IV->getLocation(), diag::note_ivar_decl);
591       }
592     }
593 }
594 
DefaultLvalueConversion(Expr * E)595 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
596   // Handle any placeholder expressions which made it here.
597   if (E->getType()->isPlaceholderType()) {
598     ExprResult result = CheckPlaceholderExpr(E);
599     if (result.isInvalid()) return ExprError();
600     E = result.get();
601   }
602 
603   // C++ [conv.lval]p1:
604   //   A glvalue of a non-function, non-array type T can be
605   //   converted to a prvalue.
606   if (!E->isGLValue()) return E;
607 
608   QualType T = E->getType();
609   assert(!T.isNull() && "r-value conversion on typeless expression?");
610 
611   // We don't want to throw lvalue-to-rvalue casts on top of
612   // expressions of certain types in C++.
613   if (getLangOpts().CPlusPlus &&
614       (E->getType() == Context.OverloadTy ||
615        T->isDependentType() ||
616        T->isRecordType()))
617     return E;
618 
619   // The C standard is actually really unclear on this point, and
620   // DR106 tells us what the result should be but not why.  It's
621   // generally best to say that void types just doesn't undergo
622   // lvalue-to-rvalue at all.  Note that expressions of unqualified
623   // 'void' type are never l-values, but qualified void can be.
624   if (T->isVoidType())
625     return E;
626 
627   // OpenCL usually rejects direct accesses to values of 'half' type.
628   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
629       T->isHalfType()) {
630     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
631       << 0 << T;
632     return ExprError();
633   }
634 
635   CheckForNullPointerDereference(*this, E);
636   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
637     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
638                                      &Context.Idents.get("object_getClass"),
639                                      SourceLocation(), LookupOrdinaryName);
640     if (ObjectGetClass)
641       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
642         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
643         FixItHint::CreateReplacement(
644                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
645     else
646       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
647   }
648   else if (const ObjCIvarRefExpr *OIRE =
649             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
650     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
651 
652   // C++ [conv.lval]p1:
653   //   [...] If T is a non-class type, the type of the prvalue is the
654   //   cv-unqualified version of T. Otherwise, the type of the
655   //   rvalue is T.
656   //
657   // C99 6.3.2.1p2:
658   //   If the lvalue has qualified type, the value has the unqualified
659   //   version of the type of the lvalue; otherwise, the value has the
660   //   type of the lvalue.
661   if (T.hasQualifiers())
662     T = T.getUnqualifiedType();
663 
664   UpdateMarkingForLValueToRValue(E);
665 
666   // Loading a __weak object implicitly retains the value, so we need a cleanup to
667   // balance that.
668   if (getLangOpts().ObjCAutoRefCount &&
669       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
670     ExprNeedsCleanups = true;
671 
672   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
673                                             nullptr, VK_RValue);
674 
675   // C11 6.3.2.1p2:
676   //   ... if the lvalue has atomic type, the value has the non-atomic version
677   //   of the type of the lvalue ...
678   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
679     T = Atomic->getValueType().getUnqualifiedType();
680     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
681                                    nullptr, VK_RValue);
682   }
683 
684   return Res;
685 }
686 
DefaultFunctionArrayLvalueConversion(Expr * E)687 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
688   ExprResult Res = DefaultFunctionArrayConversion(E);
689   if (Res.isInvalid())
690     return ExprError();
691   Res = DefaultLvalueConversion(Res.get());
692   if (Res.isInvalid())
693     return ExprError();
694   return Res;
695 }
696 
697 /// CallExprUnaryConversions - a special case of an unary conversion
698 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)699 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
700   QualType Ty = E->getType();
701   ExprResult Res = E;
702   // Only do implicit cast for a function type, but not for a pointer
703   // to function type.
704   if (Ty->isFunctionType()) {
705     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
706                             CK_FunctionToPointerDecay).get();
707     if (Res.isInvalid())
708       return ExprError();
709   }
710   Res = DefaultLvalueConversion(Res.get());
711   if (Res.isInvalid())
712     return ExprError();
713   return Res.get();
714 }
715 
716 /// UsualUnaryConversions - Performs various conversions that are common to most
717 /// operators (C99 6.3). The conversions of array and function types are
718 /// sometimes suppressed. For example, the array->pointer conversion doesn't
719 /// apply if the array is an argument to the sizeof or address (&) operators.
720 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)721 ExprResult Sema::UsualUnaryConversions(Expr *E) {
722   // First, convert to an r-value.
723   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
724   if (Res.isInvalid())
725     return ExprError();
726   E = Res.get();
727 
728   QualType Ty = E->getType();
729   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
730 
731   // Half FP have to be promoted to float unless it is natively supported
732   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
733     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
734 
735   // Try to perform integral promotions if the object has a theoretically
736   // promotable type.
737   if (Ty->isIntegralOrUnscopedEnumerationType()) {
738     // C99 6.3.1.1p2:
739     //
740     //   The following may be used in an expression wherever an int or
741     //   unsigned int may be used:
742     //     - an object or expression with an integer type whose integer
743     //       conversion rank is less than or equal to the rank of int
744     //       and unsigned int.
745     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
746     //
747     //   If an int can represent all values of the original type, the
748     //   value is converted to an int; otherwise, it is converted to an
749     //   unsigned int. These are called the integer promotions. All
750     //   other types are unchanged by the integer promotions.
751 
752     QualType PTy = Context.isPromotableBitField(E);
753     if (!PTy.isNull()) {
754       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
755       return E;
756     }
757     if (Ty->isPromotableIntegerType()) {
758       QualType PT = Context.getPromotedIntegerType(Ty);
759       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
760       return E;
761     }
762   }
763   return E;
764 }
765 
766 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
767 /// do not have a prototype. Arguments that have type float or __fp16
768 /// are promoted to double. All other argument types are converted by
769 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)770 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
771   QualType Ty = E->getType();
772   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
773 
774   ExprResult Res = UsualUnaryConversions(E);
775   if (Res.isInvalid())
776     return ExprError();
777   E = Res.get();
778 
779   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
780   // double.
781   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
782   if (BTy && (BTy->getKind() == BuiltinType::Half ||
783               BTy->getKind() == BuiltinType::Float))
784     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
785 
786   // C++ performs lvalue-to-rvalue conversion as a default argument
787   // promotion, even on class types, but note:
788   //   C++11 [conv.lval]p2:
789   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
790   //     operand or a subexpression thereof the value contained in the
791   //     referenced object is not accessed. Otherwise, if the glvalue
792   //     has a class type, the conversion copy-initializes a temporary
793   //     of type T from the glvalue and the result of the conversion
794   //     is a prvalue for the temporary.
795   // FIXME: add some way to gate this entire thing for correctness in
796   // potentially potentially evaluated contexts.
797   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
798     ExprResult Temp = PerformCopyInitialization(
799                        InitializedEntity::InitializeTemporary(E->getType()),
800                                                 E->getExprLoc(), E);
801     if (Temp.isInvalid())
802       return ExprError();
803     E = Temp.get();
804   }
805 
806   return E;
807 }
808 
809 /// Determine the degree of POD-ness for an expression.
810 /// Incomplete types are considered POD, since this check can be performed
811 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)812 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
813   if (Ty->isIncompleteType()) {
814     // C++11 [expr.call]p7:
815     //   After these conversions, if the argument does not have arithmetic,
816     //   enumeration, pointer, pointer to member, or class type, the program
817     //   is ill-formed.
818     //
819     // Since we've already performed array-to-pointer and function-to-pointer
820     // decay, the only such type in C++ is cv void. This also handles
821     // initializer lists as variadic arguments.
822     if (Ty->isVoidType())
823       return VAK_Invalid;
824 
825     if (Ty->isObjCObjectType())
826       return VAK_Invalid;
827     return VAK_Valid;
828   }
829 
830   if (Ty.isCXX98PODType(Context))
831     return VAK_Valid;
832 
833   // C++11 [expr.call]p7:
834   //   Passing a potentially-evaluated argument of class type (Clause 9)
835   //   having a non-trivial copy constructor, a non-trivial move constructor,
836   //   or a non-trivial destructor, with no corresponding parameter,
837   //   is conditionally-supported with implementation-defined semantics.
838   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
839     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
840       if (!Record->hasNonTrivialCopyConstructor() &&
841           !Record->hasNonTrivialMoveConstructor() &&
842           !Record->hasNonTrivialDestructor())
843         return VAK_ValidInCXX11;
844 
845   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
846     return VAK_Valid;
847 
848   if (Ty->isObjCObjectType())
849     return VAK_Invalid;
850 
851   if (getLangOpts().MSVCCompat)
852     return VAK_MSVCUndefined;
853 
854   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
855   // permitted to reject them. We should consider doing so.
856   return VAK_Undefined;
857 }
858 
checkVariadicArgument(const Expr * E,VariadicCallType CT)859 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
860   // Don't allow one to pass an Objective-C interface to a vararg.
861   const QualType &Ty = E->getType();
862   VarArgKind VAK = isValidVarArgType(Ty);
863 
864   // Complain about passing non-POD types through varargs.
865   switch (VAK) {
866   case VAK_ValidInCXX11:
867     DiagRuntimeBehavior(
868         E->getLocStart(), nullptr,
869         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
870           << Ty << CT);
871     // Fall through.
872   case VAK_Valid:
873     if (Ty->isRecordType()) {
874       // This is unlikely to be what the user intended. If the class has a
875       // 'c_str' member function, the user probably meant to call that.
876       DiagRuntimeBehavior(E->getLocStart(), nullptr,
877                           PDiag(diag::warn_pass_class_arg_to_vararg)
878                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
879     }
880     break;
881 
882   case VAK_Undefined:
883   case VAK_MSVCUndefined:
884     DiagRuntimeBehavior(
885         E->getLocStart(), nullptr,
886         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
887           << getLangOpts().CPlusPlus11 << Ty << CT);
888     break;
889 
890   case VAK_Invalid:
891     if (Ty->isObjCObjectType())
892       DiagRuntimeBehavior(
893           E->getLocStart(), nullptr,
894           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
895             << Ty << CT);
896     else
897       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
898         << isa<InitListExpr>(E) << Ty << CT;
899     break;
900   }
901 }
902 
903 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
904 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)905 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
906                                                   FunctionDecl *FDecl) {
907   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
908     // Strip the unbridged-cast placeholder expression off, if applicable.
909     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
910         (CT == VariadicMethod ||
911          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
912       E = stripARCUnbridgedCast(E);
913 
914     // Otherwise, do normal placeholder checking.
915     } else {
916       ExprResult ExprRes = CheckPlaceholderExpr(E);
917       if (ExprRes.isInvalid())
918         return ExprError();
919       E = ExprRes.get();
920     }
921   }
922 
923   ExprResult ExprRes = DefaultArgumentPromotion(E);
924   if (ExprRes.isInvalid())
925     return ExprError();
926   E = ExprRes.get();
927 
928   // Diagnostics regarding non-POD argument types are
929   // emitted along with format string checking in Sema::CheckFunctionCall().
930   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
931     // Turn this into a trap.
932     CXXScopeSpec SS;
933     SourceLocation TemplateKWLoc;
934     UnqualifiedId Name;
935     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
936                        E->getLocStart());
937     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
938                                           Name, true, false);
939     if (TrapFn.isInvalid())
940       return ExprError();
941 
942     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
943                                     E->getLocStart(), None,
944                                     E->getLocEnd());
945     if (Call.isInvalid())
946       return ExprError();
947 
948     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
949                                   Call.get(), E);
950     if (Comma.isInvalid())
951       return ExprError();
952     return Comma.get();
953   }
954 
955   if (!getLangOpts().CPlusPlus &&
956       RequireCompleteType(E->getExprLoc(), E->getType(),
957                           diag::err_call_incomplete_argument))
958     return ExprError();
959 
960   return E;
961 }
962 
963 /// \brief Converts an integer to complex float type.  Helper function of
964 /// UsualArithmeticConversions()
965 ///
966 /// \return false if the integer expression is an integer type and is
967 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)968 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
969                                                   ExprResult &ComplexExpr,
970                                                   QualType IntTy,
971                                                   QualType ComplexTy,
972                                                   bool SkipCast) {
973   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
974   if (SkipCast) return false;
975   if (IntTy->isIntegerType()) {
976     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
977     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
978     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
979                                   CK_FloatingRealToComplex);
980   } else {
981     assert(IntTy->isComplexIntegerType());
982     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
983                                   CK_IntegralComplexToFloatingComplex);
984   }
985   return false;
986 }
987 
988 /// \brief Handle arithmetic conversion with complex types.  Helper function of
989 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)990 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
991                                              ExprResult &RHS, QualType LHSType,
992                                              QualType RHSType,
993                                              bool IsCompAssign) {
994   // if we have an integer operand, the result is the complex type.
995   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
996                                              /*skipCast*/false))
997     return LHSType;
998   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
999                                              /*skipCast*/IsCompAssign))
1000     return RHSType;
1001 
1002   // This handles complex/complex, complex/float, or float/complex.
1003   // When both operands are complex, the shorter operand is converted to the
1004   // type of the longer, and that is the type of the result. This corresponds
1005   // to what is done when combining two real floating-point operands.
1006   // The fun begins when size promotion occur across type domains.
1007   // From H&S 6.3.4: When one operand is complex and the other is a real
1008   // floating-point type, the less precise type is converted, within it's
1009   // real or complex domain, to the precision of the other type. For example,
1010   // when combining a "long double" with a "double _Complex", the
1011   // "double _Complex" is promoted to "long double _Complex".
1012 
1013   // Compute the rank of the two types, regardless of whether they are complex.
1014   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1015 
1016   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1017   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1018   QualType LHSElementType =
1019       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1020   QualType RHSElementType =
1021       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1022 
1023   QualType ResultType = S.Context.getComplexType(LHSElementType);
1024   if (Order < 0) {
1025     // Promote the precision of the LHS if not an assignment.
1026     ResultType = S.Context.getComplexType(RHSElementType);
1027     if (!IsCompAssign) {
1028       if (LHSComplexType)
1029         LHS =
1030             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1031       else
1032         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1033     }
1034   } else if (Order > 0) {
1035     // Promote the precision of the RHS.
1036     if (RHSComplexType)
1037       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1038     else
1039       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1040   }
1041   return ResultType;
1042 }
1043 
1044 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1045 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1046 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1047                                            ExprResult &IntExpr,
1048                                            QualType FloatTy, QualType IntTy,
1049                                            bool ConvertFloat, bool ConvertInt) {
1050   if (IntTy->isIntegerType()) {
1051     if (ConvertInt)
1052       // Convert intExpr to the lhs floating point type.
1053       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1054                                     CK_IntegralToFloating);
1055     return FloatTy;
1056   }
1057 
1058   // Convert both sides to the appropriate complex float.
1059   assert(IntTy->isComplexIntegerType());
1060   QualType result = S.Context.getComplexType(FloatTy);
1061 
1062   // _Complex int -> _Complex float
1063   if (ConvertInt)
1064     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1065                                   CK_IntegralComplexToFloatingComplex);
1066 
1067   // float -> _Complex float
1068   if (ConvertFloat)
1069     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1070                                     CK_FloatingRealToComplex);
1071 
1072   return result;
1073 }
1074 
1075 /// \brief Handle arithmethic conversion with floating point types.  Helper
1076 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1077 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1078                                       ExprResult &RHS, QualType LHSType,
1079                                       QualType RHSType, bool IsCompAssign) {
1080   bool LHSFloat = LHSType->isRealFloatingType();
1081   bool RHSFloat = RHSType->isRealFloatingType();
1082 
1083   // If we have two real floating types, convert the smaller operand
1084   // to the bigger result.
1085   if (LHSFloat && RHSFloat) {
1086     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1087     if (order > 0) {
1088       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1089       return LHSType;
1090     }
1091 
1092     assert(order < 0 && "illegal float comparison");
1093     if (!IsCompAssign)
1094       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1095     return RHSType;
1096   }
1097 
1098   if (LHSFloat)
1099     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1100                                       /*convertFloat=*/!IsCompAssign,
1101                                       /*convertInt=*/ true);
1102   assert(RHSFloat);
1103   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1104                                     /*convertInt=*/ true,
1105                                     /*convertFloat=*/!IsCompAssign);
1106 }
1107 
1108 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1109 
1110 namespace {
1111 /// These helper callbacks are placed in an anonymous namespace to
1112 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1113 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1114   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1115 }
1116 
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1117 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1118   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1119                              CK_IntegralComplexCast);
1120 }
1121 }
1122 
1123 /// \brief Handle integer arithmetic conversions.  Helper function of
1124 /// UsualArithmeticConversions()
1125 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1126 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1127                                         ExprResult &RHS, QualType LHSType,
1128                                         QualType RHSType, bool IsCompAssign) {
1129   // The rules for this case are in C99 6.3.1.8
1130   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1131   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1132   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1133   if (LHSSigned == RHSSigned) {
1134     // Same signedness; use the higher-ranked type
1135     if (order >= 0) {
1136       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1137       return LHSType;
1138     } else if (!IsCompAssign)
1139       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1140     return RHSType;
1141   } else if (order != (LHSSigned ? 1 : -1)) {
1142     // The unsigned type has greater than or equal rank to the
1143     // signed type, so use the unsigned type
1144     if (RHSSigned) {
1145       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1146       return LHSType;
1147     } else if (!IsCompAssign)
1148       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1149     return RHSType;
1150   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1151     // The two types are different widths; if we are here, that
1152     // means the signed type is larger than the unsigned type, so
1153     // use the signed type.
1154     if (LHSSigned) {
1155       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1156       return LHSType;
1157     } else if (!IsCompAssign)
1158       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1159     return RHSType;
1160   } else {
1161     // The signed type is higher-ranked than the unsigned type,
1162     // but isn't actually any bigger (like unsigned int and long
1163     // on most 32-bit systems).  Use the unsigned type corresponding
1164     // to the signed type.
1165     QualType result =
1166       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1167     RHS = (*doRHSCast)(S, RHS.get(), result);
1168     if (!IsCompAssign)
1169       LHS = (*doLHSCast)(S, LHS.get(), result);
1170     return result;
1171   }
1172 }
1173 
1174 /// \brief Handle conversions with GCC complex int extension.  Helper function
1175 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1176 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1177                                            ExprResult &RHS, QualType LHSType,
1178                                            QualType RHSType,
1179                                            bool IsCompAssign) {
1180   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1181   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1182 
1183   if (LHSComplexInt && RHSComplexInt) {
1184     QualType LHSEltType = LHSComplexInt->getElementType();
1185     QualType RHSEltType = RHSComplexInt->getElementType();
1186     QualType ScalarType =
1187       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1188         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1189 
1190     return S.Context.getComplexType(ScalarType);
1191   }
1192 
1193   if (LHSComplexInt) {
1194     QualType LHSEltType = LHSComplexInt->getElementType();
1195     QualType ScalarType =
1196       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1197         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1198     QualType ComplexType = S.Context.getComplexType(ScalarType);
1199     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1200                               CK_IntegralRealToComplex);
1201 
1202     return ComplexType;
1203   }
1204 
1205   assert(RHSComplexInt);
1206 
1207   QualType RHSEltType = RHSComplexInt->getElementType();
1208   QualType ScalarType =
1209     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1210       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1211   QualType ComplexType = S.Context.getComplexType(ScalarType);
1212 
1213   if (!IsCompAssign)
1214     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1215                               CK_IntegralRealToComplex);
1216   return ComplexType;
1217 }
1218 
1219 /// UsualArithmeticConversions - Performs various conversions that are common to
1220 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1221 /// routine returns the first non-arithmetic type found. The client is
1222 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,bool IsCompAssign)1223 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1224                                           bool IsCompAssign) {
1225   if (!IsCompAssign) {
1226     LHS = UsualUnaryConversions(LHS.get());
1227     if (LHS.isInvalid())
1228       return QualType();
1229   }
1230 
1231   RHS = UsualUnaryConversions(RHS.get());
1232   if (RHS.isInvalid())
1233     return QualType();
1234 
1235   // For conversion purposes, we ignore any qualifiers.
1236   // For example, "const float" and "float" are equivalent.
1237   QualType LHSType =
1238     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1239   QualType RHSType =
1240     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1241 
1242   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1243   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1244     LHSType = AtomicLHS->getValueType();
1245 
1246   // If both types are identical, no conversion is needed.
1247   if (LHSType == RHSType)
1248     return LHSType;
1249 
1250   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1251   // The caller can deal with this (e.g. pointer + int).
1252   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1253     return QualType();
1254 
1255   // Apply unary and bitfield promotions to the LHS's type.
1256   QualType LHSUnpromotedType = LHSType;
1257   if (LHSType->isPromotableIntegerType())
1258     LHSType = Context.getPromotedIntegerType(LHSType);
1259   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1260   if (!LHSBitfieldPromoteTy.isNull())
1261     LHSType = LHSBitfieldPromoteTy;
1262   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1263     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1264 
1265   // If both types are identical, no conversion is needed.
1266   if (LHSType == RHSType)
1267     return LHSType;
1268 
1269   // At this point, we have two different arithmetic types.
1270 
1271   // Handle complex types first (C99 6.3.1.8p1).
1272   if (LHSType->isComplexType() || RHSType->isComplexType())
1273     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1274                                         IsCompAssign);
1275 
1276   // Now handle "real" floating types (i.e. float, double, long double).
1277   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1278     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1279                                  IsCompAssign);
1280 
1281   // Handle GCC complex int extension.
1282   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1283     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1284                                       IsCompAssign);
1285 
1286   // Finally, we have two differing integer types.
1287   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1288            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1289 }
1290 
1291 
1292 //===----------------------------------------------------------------------===//
1293 //  Semantic Analysis for various Expression Types
1294 //===----------------------------------------------------------------------===//
1295 
1296 
1297 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1299                                 SourceLocation DefaultLoc,
1300                                 SourceLocation RParenLoc,
1301                                 Expr *ControllingExpr,
1302                                 ArrayRef<ParsedType> ArgTypes,
1303                                 ArrayRef<Expr *> ArgExprs) {
1304   unsigned NumAssocs = ArgTypes.size();
1305   assert(NumAssocs == ArgExprs.size());
1306 
1307   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1308   for (unsigned i = 0; i < NumAssocs; ++i) {
1309     if (ArgTypes[i])
1310       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1311     else
1312       Types[i] = nullptr;
1313   }
1314 
1315   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1316                                              ControllingExpr,
1317                                              llvm::makeArrayRef(Types, NumAssocs),
1318                                              ArgExprs);
1319   delete [] Types;
1320   return ER;
1321 }
1322 
1323 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1325                                  SourceLocation DefaultLoc,
1326                                  SourceLocation RParenLoc,
1327                                  Expr *ControllingExpr,
1328                                  ArrayRef<TypeSourceInfo *> Types,
1329                                  ArrayRef<Expr *> Exprs) {
1330   unsigned NumAssocs = Types.size();
1331   assert(NumAssocs == Exprs.size());
1332   if (ControllingExpr->getType()->isPlaceholderType()) {
1333     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1334     if (result.isInvalid()) return ExprError();
1335     ControllingExpr = result.get();
1336   }
1337 
1338   // The controlling expression is an unevaluated operand, so side effects are
1339   // likely unintended.
1340   if (ActiveTemplateInstantiations.empty() &&
1341       ControllingExpr->HasSideEffects(Context, false))
1342     Diag(ControllingExpr->getExprLoc(),
1343          diag::warn_side_effects_unevaluated_context);
1344 
1345   bool TypeErrorFound = false,
1346        IsResultDependent = ControllingExpr->isTypeDependent(),
1347        ContainsUnexpandedParameterPack
1348          = ControllingExpr->containsUnexpandedParameterPack();
1349 
1350   for (unsigned i = 0; i < NumAssocs; ++i) {
1351     if (Exprs[i]->containsUnexpandedParameterPack())
1352       ContainsUnexpandedParameterPack = true;
1353 
1354     if (Types[i]) {
1355       if (Types[i]->getType()->containsUnexpandedParameterPack())
1356         ContainsUnexpandedParameterPack = true;
1357 
1358       if (Types[i]->getType()->isDependentType()) {
1359         IsResultDependent = true;
1360       } else {
1361         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1362         // complete object type other than a variably modified type."
1363         unsigned D = 0;
1364         if (Types[i]->getType()->isIncompleteType())
1365           D = diag::err_assoc_type_incomplete;
1366         else if (!Types[i]->getType()->isObjectType())
1367           D = diag::err_assoc_type_nonobject;
1368         else if (Types[i]->getType()->isVariablyModifiedType())
1369           D = diag::err_assoc_type_variably_modified;
1370 
1371         if (D != 0) {
1372           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1373             << Types[i]->getTypeLoc().getSourceRange()
1374             << Types[i]->getType();
1375           TypeErrorFound = true;
1376         }
1377 
1378         // C11 6.5.1.1p2 "No two generic associations in the same generic
1379         // selection shall specify compatible types."
1380         for (unsigned j = i+1; j < NumAssocs; ++j)
1381           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1382               Context.typesAreCompatible(Types[i]->getType(),
1383                                          Types[j]->getType())) {
1384             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1385                  diag::err_assoc_compatible_types)
1386               << Types[j]->getTypeLoc().getSourceRange()
1387               << Types[j]->getType()
1388               << Types[i]->getType();
1389             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1390                  diag::note_compat_assoc)
1391               << Types[i]->getTypeLoc().getSourceRange()
1392               << Types[i]->getType();
1393             TypeErrorFound = true;
1394           }
1395       }
1396     }
1397   }
1398   if (TypeErrorFound)
1399     return ExprError();
1400 
1401   // If we determined that the generic selection is result-dependent, don't
1402   // try to compute the result expression.
1403   if (IsResultDependent)
1404     return new (Context) GenericSelectionExpr(
1405         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1406         ContainsUnexpandedParameterPack);
1407 
1408   SmallVector<unsigned, 1> CompatIndices;
1409   unsigned DefaultIndex = -1U;
1410   for (unsigned i = 0; i < NumAssocs; ++i) {
1411     if (!Types[i])
1412       DefaultIndex = i;
1413     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1414                                         Types[i]->getType()))
1415       CompatIndices.push_back(i);
1416   }
1417 
1418   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1419   // type compatible with at most one of the types named in its generic
1420   // association list."
1421   if (CompatIndices.size() > 1) {
1422     // We strip parens here because the controlling expression is typically
1423     // parenthesized in macro definitions.
1424     ControllingExpr = ControllingExpr->IgnoreParens();
1425     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1426       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1427       << (unsigned) CompatIndices.size();
1428     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1429          E = CompatIndices.end(); I != E; ++I) {
1430       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1431            diag::note_compat_assoc)
1432         << Types[*I]->getTypeLoc().getSourceRange()
1433         << Types[*I]->getType();
1434     }
1435     return ExprError();
1436   }
1437 
1438   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1439   // its controlling expression shall have type compatible with exactly one of
1440   // the types named in its generic association list."
1441   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1442     // We strip parens here because the controlling expression is typically
1443     // parenthesized in macro definitions.
1444     ControllingExpr = ControllingExpr->IgnoreParens();
1445     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1446       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1447     return ExprError();
1448   }
1449 
1450   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1451   // type name that is compatible with the type of the controlling expression,
1452   // then the result expression of the generic selection is the expression
1453   // in that generic association. Otherwise, the result expression of the
1454   // generic selection is the expression in the default generic association."
1455   unsigned ResultIndex =
1456     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1457 
1458   return new (Context) GenericSelectionExpr(
1459       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1460       ContainsUnexpandedParameterPack, ResultIndex);
1461 }
1462 
1463 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1464 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1465 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1466                                      unsigned Offset) {
1467   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1468                                         S.getLangOpts());
1469 }
1470 
1471 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1472 /// 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)1473 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1474                                                  IdentifierInfo *UDSuffix,
1475                                                  SourceLocation UDSuffixLoc,
1476                                                  ArrayRef<Expr*> Args,
1477                                                  SourceLocation LitEndLoc) {
1478   assert(Args.size() <= 2 && "too many arguments for literal operator");
1479 
1480   QualType ArgTy[2];
1481   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1482     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1483     if (ArgTy[ArgIdx]->isArrayType())
1484       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1485   }
1486 
1487   DeclarationName OpName =
1488     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1489   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1490   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1491 
1492   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1493   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1494                               /*AllowRaw*/false, /*AllowTemplate*/false,
1495                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1496     return ExprError();
1497 
1498   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1499 }
1500 
1501 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1502 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1503 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1504 /// multiple tokens.  However, the common case is that StringToks points to one
1505 /// string.
1506 ///
1507 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1508 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1509   assert(!StringToks.empty() && "Must have at least one string!");
1510 
1511   StringLiteralParser Literal(StringToks, PP);
1512   if (Literal.hadError)
1513     return ExprError();
1514 
1515   SmallVector<SourceLocation, 4> StringTokLocs;
1516   for (unsigned i = 0; i != StringToks.size(); ++i)
1517     StringTokLocs.push_back(StringToks[i].getLocation());
1518 
1519   QualType CharTy = Context.CharTy;
1520   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1521   if (Literal.isWide()) {
1522     CharTy = Context.getWideCharType();
1523     Kind = StringLiteral::Wide;
1524   } else if (Literal.isUTF8()) {
1525     Kind = StringLiteral::UTF8;
1526   } else if (Literal.isUTF16()) {
1527     CharTy = Context.Char16Ty;
1528     Kind = StringLiteral::UTF16;
1529   } else if (Literal.isUTF32()) {
1530     CharTy = Context.Char32Ty;
1531     Kind = StringLiteral::UTF32;
1532   } else if (Literal.isPascal()) {
1533     CharTy = Context.UnsignedCharTy;
1534   }
1535 
1536   QualType CharTyConst = CharTy;
1537   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1538   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1539     CharTyConst.addConst();
1540 
1541   // Get an array type for the string, according to C99 6.4.5.  This includes
1542   // the nul terminator character as well as the string length for pascal
1543   // strings.
1544   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1545                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1546                                  ArrayType::Normal, 0);
1547 
1548   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1549   if (getLangOpts().OpenCL) {
1550     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1551   }
1552 
1553   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1554   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1555                                              Kind, Literal.Pascal, StrTy,
1556                                              &StringTokLocs[0],
1557                                              StringTokLocs.size());
1558   if (Literal.getUDSuffix().empty())
1559     return Lit;
1560 
1561   // We're building a user-defined literal.
1562   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1563   SourceLocation UDSuffixLoc =
1564     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1565                    Literal.getUDSuffixOffset());
1566 
1567   // Make sure we're allowed user-defined literals here.
1568   if (!UDLScope)
1569     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1570 
1571   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1572   //   operator "" X (str, len)
1573   QualType SizeType = Context.getSizeType();
1574 
1575   DeclarationName OpName =
1576     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1577   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1578   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1579 
1580   QualType ArgTy[] = {
1581     Context.getArrayDecayedType(StrTy), SizeType
1582   };
1583 
1584   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1585   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1586                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1587                                 /*AllowStringTemplate*/true)) {
1588 
1589   case LOLR_Cooked: {
1590     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1591     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1592                                                     StringTokLocs[0]);
1593     Expr *Args[] = { Lit, LenArg };
1594 
1595     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1596   }
1597 
1598   case LOLR_StringTemplate: {
1599     TemplateArgumentListInfo ExplicitArgs;
1600 
1601     unsigned CharBits = Context.getIntWidth(CharTy);
1602     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1603     llvm::APSInt Value(CharBits, CharIsUnsigned);
1604 
1605     TemplateArgument TypeArg(CharTy);
1606     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1607     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1608 
1609     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1610       Value = Lit->getCodeUnit(I);
1611       TemplateArgument Arg(Context, Value, CharTy);
1612       TemplateArgumentLocInfo ArgInfo;
1613       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1614     }
1615     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1616                                     &ExplicitArgs);
1617   }
1618   case LOLR_Raw:
1619   case LOLR_Template:
1620     llvm_unreachable("unexpected literal operator lookup result");
1621   case LOLR_Error:
1622     return ExprError();
1623   }
1624   llvm_unreachable("unexpected literal operator lookup result");
1625 }
1626 
1627 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1628 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1629                        SourceLocation Loc,
1630                        const CXXScopeSpec *SS) {
1631   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1632   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1633 }
1634 
1635 /// BuildDeclRefExpr - Build an expression that references a
1636 /// declaration that does not require a closure capture.
1637 ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)1638 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1639                        const DeclarationNameInfo &NameInfo,
1640                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1641                        const TemplateArgumentListInfo *TemplateArgs) {
1642   if (getLangOpts().CUDA)
1643     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1644       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1645         if (CheckCUDATarget(Caller, Callee)) {
1646           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1647             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1648             << IdentifyCUDATarget(Caller);
1649           Diag(D->getLocation(), diag::note_previous_decl)
1650             << D->getIdentifier();
1651           return ExprError();
1652         }
1653       }
1654 
1655   bool RefersToCapturedVariable =
1656       isa<VarDecl>(D) &&
1657       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1658 
1659   DeclRefExpr *E;
1660   if (isa<VarTemplateSpecializationDecl>(D)) {
1661     VarTemplateSpecializationDecl *VarSpec =
1662         cast<VarTemplateSpecializationDecl>(D);
1663 
1664     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1665                                         : NestedNameSpecifierLoc(),
1666                             VarSpec->getTemplateKeywordLoc(), D,
1667                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1668                             FoundD, TemplateArgs);
1669   } else {
1670     assert(!TemplateArgs && "No template arguments for non-variable"
1671                             " template specialization references");
1672     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1673                                         : NestedNameSpecifierLoc(),
1674                             SourceLocation(), D, RefersToCapturedVariable,
1675                             NameInfo, Ty, VK, FoundD);
1676   }
1677 
1678   MarkDeclRefReferenced(E);
1679 
1680   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1681       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1682       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1683       recordUseOfEvaluatedWeak(E);
1684 
1685   // Just in case we're building an illegal pointer-to-member.
1686   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1687   if (FD && FD->isBitField())
1688     E->setObjectKind(OK_BitField);
1689 
1690   return E;
1691 }
1692 
1693 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1694 /// possibly a list of template arguments.
1695 ///
1696 /// If this produces template arguments, it is permitted to call
1697 /// DecomposeTemplateName.
1698 ///
1699 /// This actually loses a lot of source location information for
1700 /// non-standard name kinds; we should consider preserving that in
1701 /// some way.
1702 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)1703 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1704                              TemplateArgumentListInfo &Buffer,
1705                              DeclarationNameInfo &NameInfo,
1706                              const TemplateArgumentListInfo *&TemplateArgs) {
1707   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1708     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1709     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1710 
1711     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1712                                        Id.TemplateId->NumArgs);
1713     translateTemplateArguments(TemplateArgsPtr, Buffer);
1714 
1715     TemplateName TName = Id.TemplateId->Template.get();
1716     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1717     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1718     TemplateArgs = &Buffer;
1719   } else {
1720     NameInfo = GetNameFromUnqualifiedId(Id);
1721     TemplateArgs = nullptr;
1722   }
1723 }
1724 
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)1725 static void emitEmptyLookupTypoDiagnostic(
1726     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1727     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1728     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1729   DeclContext *Ctx =
1730       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1731   if (!TC) {
1732     // Emit a special diagnostic for failed member lookups.
1733     // FIXME: computing the declaration context might fail here (?)
1734     if (Ctx)
1735       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1736                                                  << SS.getRange();
1737     else
1738       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1739     return;
1740   }
1741 
1742   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1743   bool DroppedSpecifier =
1744       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1745   unsigned NoteID =
1746       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1747           ? diag::note_implicit_param_decl
1748           : diag::note_previous_decl;
1749   if (!Ctx)
1750     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1751                          SemaRef.PDiag(NoteID));
1752   else
1753     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1754                                  << Typo << Ctx << DroppedSpecifier
1755                                  << SS.getRange(),
1756                          SemaRef.PDiag(NoteID));
1757 }
1758 
1759 /// Diagnose an empty lookup.
1760 ///
1761 /// \return false if new lookup candidates were found
1762 bool
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,std::unique_ptr<CorrectionCandidateCallback> CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)1763 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1764                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1765                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1766                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1767   DeclarationName Name = R.getLookupName();
1768 
1769   unsigned diagnostic = diag::err_undeclared_var_use;
1770   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1771   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1772       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1773       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1774     diagnostic = diag::err_undeclared_use;
1775     diagnostic_suggest = diag::err_undeclared_use_suggest;
1776   }
1777 
1778   // If the original lookup was an unqualified lookup, fake an
1779   // unqualified lookup.  This is useful when (for example) the
1780   // original lookup would not have found something because it was a
1781   // dependent name.
1782   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1783     ? CurContext : nullptr;
1784   while (DC) {
1785     if (isa<CXXRecordDecl>(DC)) {
1786       LookupQualifiedName(R, DC);
1787 
1788       if (!R.empty()) {
1789         // Don't give errors about ambiguities in this lookup.
1790         R.suppressDiagnostics();
1791 
1792         // During a default argument instantiation the CurContext points
1793         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1794         // function parameter list, hence add an explicit check.
1795         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1796                               ActiveTemplateInstantiations.back().Kind ==
1797             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1798         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1799         bool isInstance = CurMethod &&
1800                           CurMethod->isInstance() &&
1801                           DC == CurMethod->getParent() && !isDefaultArgument;
1802 
1803 
1804         // Give a code modification hint to insert 'this->'.
1805         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1806         // Actually quite difficult!
1807         if (getLangOpts().MSVCCompat)
1808           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1809         if (isInstance) {
1810           Diag(R.getNameLoc(), diagnostic) << Name
1811             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1812           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1813               CallsUndergoingInstantiation.back()->getCallee());
1814 
1815           CXXMethodDecl *DepMethod;
1816           if (CurMethod->isDependentContext())
1817             DepMethod = CurMethod;
1818           else if (CurMethod->getTemplatedKind() ==
1819               FunctionDecl::TK_FunctionTemplateSpecialization)
1820             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1821                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1822           else
1823             DepMethod = cast<CXXMethodDecl>(
1824                 CurMethod->getInstantiatedFromMemberFunction());
1825           assert(DepMethod && "No template pattern found");
1826 
1827           QualType DepThisType = DepMethod->getThisType(Context);
1828           CheckCXXThisCapture(R.getNameLoc());
1829           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1830                                      R.getNameLoc(), DepThisType, false);
1831           TemplateArgumentListInfo TList;
1832           if (ULE->hasExplicitTemplateArgs())
1833             ULE->copyTemplateArgumentsInto(TList);
1834 
1835           CXXScopeSpec SS;
1836           SS.Adopt(ULE->getQualifierLoc());
1837           CXXDependentScopeMemberExpr *DepExpr =
1838               CXXDependentScopeMemberExpr::Create(
1839                   Context, DepThis, DepThisType, true, SourceLocation(),
1840                   SS.getWithLocInContext(Context),
1841                   ULE->getTemplateKeywordLoc(), nullptr,
1842                   R.getLookupNameInfo(),
1843                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1844           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1845         } else {
1846           Diag(R.getNameLoc(), diagnostic) << Name;
1847         }
1848 
1849         // Do we really want to note all of these?
1850         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1851           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1852 
1853         // Return true if we are inside a default argument instantiation
1854         // and the found name refers to an instance member function, otherwise
1855         // the function calling DiagnoseEmptyLookup will try to create an
1856         // implicit member call and this is wrong for default argument.
1857         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1858           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1859           return true;
1860         }
1861 
1862         // Tell the callee to try to recover.
1863         return false;
1864       }
1865 
1866       R.clear();
1867     }
1868 
1869     // In Microsoft mode, if we are performing lookup from within a friend
1870     // function definition declared at class scope then we must set
1871     // DC to the lexical parent to be able to search into the parent
1872     // class.
1873     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1874         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1875         DC->getLexicalParent()->isRecord())
1876       DC = DC->getLexicalParent();
1877     else
1878       DC = DC->getParent();
1879   }
1880 
1881   // We didn't find anything, so try to correct for a typo.
1882   TypoCorrection Corrected;
1883   if (S && Out) {
1884     SourceLocation TypoLoc = R.getNameLoc();
1885     assert(!ExplicitTemplateArgs &&
1886            "Diagnosing an empty lookup with explicit template args!");
1887     *Out = CorrectTypoDelayed(
1888         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1889         [=](const TypoCorrection &TC) {
1890           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1891                                         diagnostic, diagnostic_suggest);
1892         },
1893         nullptr, CTK_ErrorRecovery);
1894     if (*Out)
1895       return true;
1896   } else if (S && (Corrected =
1897                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1898                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1899     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1900     bool DroppedSpecifier =
1901         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1902     R.setLookupName(Corrected.getCorrection());
1903 
1904     bool AcceptableWithRecovery = false;
1905     bool AcceptableWithoutRecovery = false;
1906     NamedDecl *ND = Corrected.getCorrectionDecl();
1907     if (ND) {
1908       if (Corrected.isOverloaded()) {
1909         OverloadCandidateSet OCS(R.getNameLoc(),
1910                                  OverloadCandidateSet::CSK_Normal);
1911         OverloadCandidateSet::iterator Best;
1912         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1913                                         CDEnd = Corrected.end();
1914              CD != CDEnd; ++CD) {
1915           if (FunctionTemplateDecl *FTD =
1916                    dyn_cast<FunctionTemplateDecl>(*CD))
1917             AddTemplateOverloadCandidate(
1918                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1919                 Args, OCS);
1920           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1921             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1922               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1923                                    Args, OCS);
1924         }
1925         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1926         case OR_Success:
1927           ND = Best->Function;
1928           Corrected.setCorrectionDecl(ND);
1929           break;
1930         default:
1931           // FIXME: Arbitrarily pick the first declaration for the note.
1932           Corrected.setCorrectionDecl(ND);
1933           break;
1934         }
1935       }
1936       R.addDecl(ND);
1937       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1938         CXXRecordDecl *Record = nullptr;
1939         if (Corrected.getCorrectionSpecifier()) {
1940           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1941           Record = Ty->getAsCXXRecordDecl();
1942         }
1943         if (!Record)
1944           Record = cast<CXXRecordDecl>(
1945               ND->getDeclContext()->getRedeclContext());
1946         R.setNamingClass(Record);
1947       }
1948 
1949       AcceptableWithRecovery =
1950           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1951       // FIXME: If we ended up with a typo for a type name or
1952       // Objective-C class name, we're in trouble because the parser
1953       // is in the wrong place to recover. Suggest the typo
1954       // correction, but don't make it a fix-it since we're not going
1955       // to recover well anyway.
1956       AcceptableWithoutRecovery =
1957           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1958     } else {
1959       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1960       // because we aren't able to recover.
1961       AcceptableWithoutRecovery = true;
1962     }
1963 
1964     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1965       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1966                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1967                             ? diag::note_implicit_param_decl
1968                             : diag::note_previous_decl;
1969       if (SS.isEmpty())
1970         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1971                      PDiag(NoteID), AcceptableWithRecovery);
1972       else
1973         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1974                                   << Name << computeDeclContext(SS, false)
1975                                   << DroppedSpecifier << SS.getRange(),
1976                      PDiag(NoteID), AcceptableWithRecovery);
1977 
1978       // Tell the callee whether to try to recover.
1979       return !AcceptableWithRecovery;
1980     }
1981   }
1982   R.clear();
1983 
1984   // Emit a special diagnostic for failed member lookups.
1985   // FIXME: computing the declaration context might fail here (?)
1986   if (!SS.isEmpty()) {
1987     Diag(R.getNameLoc(), diag::err_no_member)
1988       << Name << computeDeclContext(SS, false)
1989       << SS.getRange();
1990     return true;
1991   }
1992 
1993   // Give up, we can't recover.
1994   Diag(R.getNameLoc(), diagnostic) << Name;
1995   return true;
1996 }
1997 
1998 /// In Microsoft mode, if we are inside a template class whose parent class has
1999 /// dependent base classes, and we can't resolve an unqualified identifier, then
2000 /// assume the identifier is a member of a dependent base class.  We can only
2001 /// recover successfully in static methods, instance methods, and other contexts
2002 /// where 'this' is available.  This doesn't precisely match MSVC's
2003 /// instantiation model, but it's close enough.
2004 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2005 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2006                                DeclarationNameInfo &NameInfo,
2007                                SourceLocation TemplateKWLoc,
2008                                const TemplateArgumentListInfo *TemplateArgs) {
2009   // Only try to recover from lookup into dependent bases in static methods or
2010   // contexts where 'this' is available.
2011   QualType ThisType = S.getCurrentThisType();
2012   const CXXRecordDecl *RD = nullptr;
2013   if (!ThisType.isNull())
2014     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2015   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2016     RD = MD->getParent();
2017   if (!RD || !RD->hasAnyDependentBases())
2018     return nullptr;
2019 
2020   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2021   // is available, suggest inserting 'this->' as a fixit.
2022   SourceLocation Loc = NameInfo.getLoc();
2023   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2024   DB << NameInfo.getName() << RD;
2025 
2026   if (!ThisType.isNull()) {
2027     DB << FixItHint::CreateInsertion(Loc, "this->");
2028     return CXXDependentScopeMemberExpr::Create(
2029         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2030         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2031         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2032   }
2033 
2034   // Synthesize a fake NNS that points to the derived class.  This will
2035   // perform name lookup during template instantiation.
2036   CXXScopeSpec SS;
2037   auto *NNS =
2038       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2039   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2040   return DependentScopeDeclRefExpr::Create(
2041       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2042       TemplateArgs);
2043 }
2044 
2045 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2046 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2047                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2048                         bool HasTrailingLParen, bool IsAddressOfOperand,
2049                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2050                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2051   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2052          "cannot be direct & operand and have a trailing lparen");
2053   if (SS.isInvalid())
2054     return ExprError();
2055 
2056   TemplateArgumentListInfo TemplateArgsBuffer;
2057 
2058   // Decompose the UnqualifiedId into the following data.
2059   DeclarationNameInfo NameInfo;
2060   const TemplateArgumentListInfo *TemplateArgs;
2061   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2062 
2063   DeclarationName Name = NameInfo.getName();
2064   IdentifierInfo *II = Name.getAsIdentifierInfo();
2065   SourceLocation NameLoc = NameInfo.getLoc();
2066 
2067   // C++ [temp.dep.expr]p3:
2068   //   An id-expression is type-dependent if it contains:
2069   //     -- an identifier that was declared with a dependent type,
2070   //        (note: handled after lookup)
2071   //     -- a template-id that is dependent,
2072   //        (note: handled in BuildTemplateIdExpr)
2073   //     -- a conversion-function-id that specifies a dependent type,
2074   //     -- a nested-name-specifier that contains a class-name that
2075   //        names a dependent type.
2076   // Determine whether this is a member of an unknown specialization;
2077   // we need to handle these differently.
2078   bool DependentID = false;
2079   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2080       Name.getCXXNameType()->isDependentType()) {
2081     DependentID = true;
2082   } else if (SS.isSet()) {
2083     if (DeclContext *DC = computeDeclContext(SS, false)) {
2084       if (RequireCompleteDeclContext(SS, DC))
2085         return ExprError();
2086     } else {
2087       DependentID = true;
2088     }
2089   }
2090 
2091   if (DependentID)
2092     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2093                                       IsAddressOfOperand, TemplateArgs);
2094 
2095   // Perform the required lookup.
2096   LookupResult R(*this, NameInfo,
2097                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2098                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2099   if (TemplateArgs) {
2100     // Lookup the template name again to correctly establish the context in
2101     // which it was found. This is really unfortunate as we already did the
2102     // lookup to determine that it was a template name in the first place. If
2103     // this becomes a performance hit, we can work harder to preserve those
2104     // results until we get here but it's likely not worth it.
2105     bool MemberOfUnknownSpecialization;
2106     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2107                        MemberOfUnknownSpecialization);
2108 
2109     if (MemberOfUnknownSpecialization ||
2110         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2111       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2112                                         IsAddressOfOperand, TemplateArgs);
2113   } else {
2114     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2115     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2116 
2117     // If the result might be in a dependent base class, this is a dependent
2118     // id-expression.
2119     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2120       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2121                                         IsAddressOfOperand, TemplateArgs);
2122 
2123     // If this reference is in an Objective-C method, then we need to do
2124     // some special Objective-C lookup, too.
2125     if (IvarLookupFollowUp) {
2126       ExprResult E(LookupInObjCMethod(R, S, II, true));
2127       if (E.isInvalid())
2128         return ExprError();
2129 
2130       if (Expr *Ex = E.getAs<Expr>())
2131         return Ex;
2132     }
2133   }
2134 
2135   if (R.isAmbiguous())
2136     return ExprError();
2137 
2138   // This could be an implicitly declared function reference (legal in C90,
2139   // extension in C99, forbidden in C++).
2140   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2141     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2142     if (D) R.addDecl(D);
2143   }
2144 
2145   // Determine whether this name might be a candidate for
2146   // argument-dependent lookup.
2147   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2148 
2149   if (R.empty() && !ADL) {
2150     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2151       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2152                                                    TemplateKWLoc, TemplateArgs))
2153         return E;
2154     }
2155 
2156     // Don't diagnose an empty lookup for inline assembly.
2157     if (IsInlineAsmIdentifier)
2158       return ExprError();
2159 
2160     // If this name wasn't predeclared and if this is not a function
2161     // call, diagnose the problem.
2162     TypoExpr *TE = nullptr;
2163     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2164         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2165     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2166     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2167            "Typo correction callback misconfigured");
2168     if (CCC) {
2169       // Make sure the callback knows what the typo being diagnosed is.
2170       CCC->setTypoName(II);
2171       if (SS.isValid())
2172         CCC->setTypoNNS(SS.getScopeRep());
2173     }
2174     if (DiagnoseEmptyLookup(S, SS, R,
2175                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2176                             nullptr, None, &TE)) {
2177       if (TE && KeywordReplacement) {
2178         auto &State = getTypoExprState(TE);
2179         auto BestTC = State.Consumer->getNextCorrection();
2180         if (BestTC.isKeyword()) {
2181           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2182           if (State.DiagHandler)
2183             State.DiagHandler(BestTC);
2184           KeywordReplacement->startToken();
2185           KeywordReplacement->setKind(II->getTokenID());
2186           KeywordReplacement->setIdentifierInfo(II);
2187           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2188           // Clean up the state associated with the TypoExpr, since it has
2189           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2190           clearDelayedTypo(TE);
2191           // Signal that a correction to a keyword was performed by returning a
2192           // valid-but-null ExprResult.
2193           return (Expr*)nullptr;
2194         }
2195         State.Consumer->resetCorrectionStream();
2196       }
2197       return TE ? TE : ExprError();
2198     }
2199 
2200     assert(!R.empty() &&
2201            "DiagnoseEmptyLookup returned false but added no results");
2202 
2203     // If we found an Objective-C instance variable, let
2204     // LookupInObjCMethod build the appropriate expression to
2205     // reference the ivar.
2206     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2207       R.clear();
2208       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2209       // In a hopelessly buggy code, Objective-C instance variable
2210       // lookup fails and no expression will be built to reference it.
2211       if (!E.isInvalid() && !E.get())
2212         return ExprError();
2213       return E;
2214     }
2215   }
2216 
2217   // This is guaranteed from this point on.
2218   assert(!R.empty() || ADL);
2219 
2220   // Check whether this might be a C++ implicit instance member access.
2221   // C++ [class.mfct.non-static]p3:
2222   //   When an id-expression that is not part of a class member access
2223   //   syntax and not used to form a pointer to member is used in the
2224   //   body of a non-static member function of class X, if name lookup
2225   //   resolves the name in the id-expression to a non-static non-type
2226   //   member of some class C, the id-expression is transformed into a
2227   //   class member access expression using (*this) as the
2228   //   postfix-expression to the left of the . operator.
2229   //
2230   // But we don't actually need to do this for '&' operands if R
2231   // resolved to a function or overloaded function set, because the
2232   // expression is ill-formed if it actually works out to be a
2233   // non-static member function:
2234   //
2235   // C++ [expr.ref]p4:
2236   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2237   //   [t]he expression can be used only as the left-hand operand of a
2238   //   member function call.
2239   //
2240   // There are other safeguards against such uses, but it's important
2241   // to get this right here so that we don't end up making a
2242   // spuriously dependent expression if we're inside a dependent
2243   // instance method.
2244   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2245     bool MightBeImplicitMember;
2246     if (!IsAddressOfOperand)
2247       MightBeImplicitMember = true;
2248     else if (!SS.isEmpty())
2249       MightBeImplicitMember = false;
2250     else if (R.isOverloadedResult())
2251       MightBeImplicitMember = false;
2252     else if (R.isUnresolvableResult())
2253       MightBeImplicitMember = true;
2254     else
2255       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2256                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2257                               isa<MSPropertyDecl>(R.getFoundDecl());
2258 
2259     if (MightBeImplicitMember)
2260       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2261                                              R, TemplateArgs);
2262   }
2263 
2264   if (TemplateArgs || TemplateKWLoc.isValid()) {
2265 
2266     // In C++1y, if this is a variable template id, then check it
2267     // in BuildTemplateIdExpr().
2268     // The single lookup result must be a variable template declaration.
2269     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2270         Id.TemplateId->Kind == TNK_Var_template) {
2271       assert(R.getAsSingle<VarTemplateDecl>() &&
2272              "There should only be one declaration found.");
2273     }
2274 
2275     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2276   }
2277 
2278   return BuildDeclarationNameExpr(SS, R, ADL);
2279 }
2280 
2281 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2282 /// declaration name, generally during template instantiation.
2283 /// There's a large number of things which don't need to be done along
2284 /// this path.
2285 ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,TypeSourceInfo ** RecoveryTSI)2286 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2287                                         const DeclarationNameInfo &NameInfo,
2288                                         bool IsAddressOfOperand,
2289                                         TypeSourceInfo **RecoveryTSI) {
2290   DeclContext *DC = computeDeclContext(SS, false);
2291   if (!DC)
2292     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2293                                      NameInfo, /*TemplateArgs=*/nullptr);
2294 
2295   if (RequireCompleteDeclContext(SS, DC))
2296     return ExprError();
2297 
2298   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2299   LookupQualifiedName(R, DC);
2300 
2301   if (R.isAmbiguous())
2302     return ExprError();
2303 
2304   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2305     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2306                                      NameInfo, /*TemplateArgs=*/nullptr);
2307 
2308   if (R.empty()) {
2309     Diag(NameInfo.getLoc(), diag::err_no_member)
2310       << NameInfo.getName() << DC << SS.getRange();
2311     return ExprError();
2312   }
2313 
2314   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2315     // Diagnose a missing typename if this resolved unambiguously to a type in
2316     // a dependent context.  If we can recover with a type, downgrade this to
2317     // a warning in Microsoft compatibility mode.
2318     unsigned DiagID = diag::err_typename_missing;
2319     if (RecoveryTSI && getLangOpts().MSVCCompat)
2320       DiagID = diag::ext_typename_missing;
2321     SourceLocation Loc = SS.getBeginLoc();
2322     auto D = Diag(Loc, DiagID);
2323     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2324       << SourceRange(Loc, NameInfo.getEndLoc());
2325 
2326     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2327     // context.
2328     if (!RecoveryTSI)
2329       return ExprError();
2330 
2331     // Only issue the fixit if we're prepared to recover.
2332     D << FixItHint::CreateInsertion(Loc, "typename ");
2333 
2334     // Recover by pretending this was an elaborated type.
2335     QualType Ty = Context.getTypeDeclType(TD);
2336     TypeLocBuilder TLB;
2337     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2338 
2339     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2340     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2341     QTL.setElaboratedKeywordLoc(SourceLocation());
2342     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2343 
2344     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2345 
2346     return ExprEmpty();
2347   }
2348 
2349   // Defend against this resolving to an implicit member access. We usually
2350   // won't get here if this might be a legitimate a class member (we end up in
2351   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2352   // a pointer-to-member or in an unevaluated context in C++11.
2353   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2354     return BuildPossibleImplicitMemberExpr(SS,
2355                                            /*TemplateKWLoc=*/SourceLocation(),
2356                                            R, /*TemplateArgs=*/nullptr);
2357 
2358   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2359 }
2360 
2361 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2362 /// detected that we're currently inside an ObjC method.  Perform some
2363 /// additional lookup.
2364 ///
2365 /// Ideally, most of this would be done by lookup, but there's
2366 /// actually quite a lot of extra work involved.
2367 ///
2368 /// Returns a null sentinel to indicate trivial success.
2369 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2370 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2371                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2372   SourceLocation Loc = Lookup.getNameLoc();
2373   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2374 
2375   // Check for error condition which is already reported.
2376   if (!CurMethod)
2377     return ExprError();
2378 
2379   // There are two cases to handle here.  1) scoped lookup could have failed,
2380   // in which case we should look for an ivar.  2) scoped lookup could have
2381   // found a decl, but that decl is outside the current instance method (i.e.
2382   // a global variable).  In these two cases, we do a lookup for an ivar with
2383   // this name, if the lookup sucedes, we replace it our current decl.
2384 
2385   // If we're in a class method, we don't normally want to look for
2386   // ivars.  But if we don't find anything else, and there's an
2387   // ivar, that's an error.
2388   bool IsClassMethod = CurMethod->isClassMethod();
2389 
2390   bool LookForIvars;
2391   if (Lookup.empty())
2392     LookForIvars = true;
2393   else if (IsClassMethod)
2394     LookForIvars = false;
2395   else
2396     LookForIvars = (Lookup.isSingleResult() &&
2397                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2398   ObjCInterfaceDecl *IFace = nullptr;
2399   if (LookForIvars) {
2400     IFace = CurMethod->getClassInterface();
2401     ObjCInterfaceDecl *ClassDeclared;
2402     ObjCIvarDecl *IV = nullptr;
2403     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2404       // Diagnose using an ivar in a class method.
2405       if (IsClassMethod)
2406         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2407                          << IV->getDeclName());
2408 
2409       // If we're referencing an invalid decl, just return this as a silent
2410       // error node.  The error diagnostic was already emitted on the decl.
2411       if (IV->isInvalidDecl())
2412         return ExprError();
2413 
2414       // Check if referencing a field with __attribute__((deprecated)).
2415       if (DiagnoseUseOfDecl(IV, Loc))
2416         return ExprError();
2417 
2418       // Diagnose the use of an ivar outside of the declaring class.
2419       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2420           !declaresSameEntity(ClassDeclared, IFace) &&
2421           !getLangOpts().DebuggerSupport)
2422         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2423 
2424       // FIXME: This should use a new expr for a direct reference, don't
2425       // turn this into Self->ivar, just return a BareIVarExpr or something.
2426       IdentifierInfo &II = Context.Idents.get("self");
2427       UnqualifiedId SelfName;
2428       SelfName.setIdentifier(&II, SourceLocation());
2429       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2430       CXXScopeSpec SelfScopeSpec;
2431       SourceLocation TemplateKWLoc;
2432       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2433                                               SelfName, false, false);
2434       if (SelfExpr.isInvalid())
2435         return ExprError();
2436 
2437       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2438       if (SelfExpr.isInvalid())
2439         return ExprError();
2440 
2441       MarkAnyDeclReferenced(Loc, IV, true);
2442 
2443       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2444       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2445           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2446         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2447 
2448       ObjCIvarRefExpr *Result = new (Context)
2449           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2450                           SelfExpr.get(), true, true);
2451 
2452       if (getLangOpts().ObjCAutoRefCount) {
2453         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2454           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2455             recordUseOfEvaluatedWeak(Result);
2456         }
2457         if (CurContext->isClosure())
2458           Diag(Loc, diag::warn_implicitly_retains_self)
2459             << FixItHint::CreateInsertion(Loc, "self->");
2460       }
2461 
2462       return Result;
2463     }
2464   } else if (CurMethod->isInstanceMethod()) {
2465     // We should warn if a local variable hides an ivar.
2466     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2467       ObjCInterfaceDecl *ClassDeclared;
2468       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2469         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2470             declaresSameEntity(IFace, ClassDeclared))
2471           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2472       }
2473     }
2474   } else if (Lookup.isSingleResult() &&
2475              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2476     // If accessing a stand-alone ivar in a class method, this is an error.
2477     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2478       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2479                        << IV->getDeclName());
2480   }
2481 
2482   if (Lookup.empty() && II && AllowBuiltinCreation) {
2483     // FIXME. Consolidate this with similar code in LookupName.
2484     if (unsigned BuiltinID = II->getBuiltinID()) {
2485       if (!(getLangOpts().CPlusPlus &&
2486             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2487         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2488                                            S, Lookup.isForRedeclaration(),
2489                                            Lookup.getNameLoc());
2490         if (D) Lookup.addDecl(D);
2491       }
2492     }
2493   }
2494   // Sentinel value saying that we didn't do anything special.
2495   return ExprResult((Expr *)nullptr);
2496 }
2497 
2498 /// \brief Cast a base object to a member's actual type.
2499 ///
2500 /// Logically this happens in three phases:
2501 ///
2502 /// * First we cast from the base type to the naming class.
2503 ///   The naming class is the class into which we were looking
2504 ///   when we found the member;  it's the qualifier type if a
2505 ///   qualifier was provided, and otherwise it's the base type.
2506 ///
2507 /// * Next we cast from the naming class to the declaring class.
2508 ///   If the member we found was brought into a class's scope by
2509 ///   a using declaration, this is that class;  otherwise it's
2510 ///   the class declaring the member.
2511 ///
2512 /// * Finally we cast from the declaring class to the "true"
2513 ///   declaring class of the member.  This conversion does not
2514 ///   obey access control.
2515 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2516 Sema::PerformObjectMemberConversion(Expr *From,
2517                                     NestedNameSpecifier *Qualifier,
2518                                     NamedDecl *FoundDecl,
2519                                     NamedDecl *Member) {
2520   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2521   if (!RD)
2522     return From;
2523 
2524   QualType DestRecordType;
2525   QualType DestType;
2526   QualType FromRecordType;
2527   QualType FromType = From->getType();
2528   bool PointerConversions = false;
2529   if (isa<FieldDecl>(Member)) {
2530     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2531 
2532     if (FromType->getAs<PointerType>()) {
2533       DestType = Context.getPointerType(DestRecordType);
2534       FromRecordType = FromType->getPointeeType();
2535       PointerConversions = true;
2536     } else {
2537       DestType = DestRecordType;
2538       FromRecordType = FromType;
2539     }
2540   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2541     if (Method->isStatic())
2542       return From;
2543 
2544     DestType = Method->getThisType(Context);
2545     DestRecordType = DestType->getPointeeType();
2546 
2547     if (FromType->getAs<PointerType>()) {
2548       FromRecordType = FromType->getPointeeType();
2549       PointerConversions = true;
2550     } else {
2551       FromRecordType = FromType;
2552       DestType = DestRecordType;
2553     }
2554   } else {
2555     // No conversion necessary.
2556     return From;
2557   }
2558 
2559   if (DestType->isDependentType() || FromType->isDependentType())
2560     return From;
2561 
2562   // If the unqualified types are the same, no conversion is necessary.
2563   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2564     return From;
2565 
2566   SourceRange FromRange = From->getSourceRange();
2567   SourceLocation FromLoc = FromRange.getBegin();
2568 
2569   ExprValueKind VK = From->getValueKind();
2570 
2571   // C++ [class.member.lookup]p8:
2572   //   [...] Ambiguities can often be resolved by qualifying a name with its
2573   //   class name.
2574   //
2575   // If the member was a qualified name and the qualified referred to a
2576   // specific base subobject type, we'll cast to that intermediate type
2577   // first and then to the object in which the member is declared. That allows
2578   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2579   //
2580   //   class Base { public: int x; };
2581   //   class Derived1 : public Base { };
2582   //   class Derived2 : public Base { };
2583   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2584   //
2585   //   void VeryDerived::f() {
2586   //     x = 17; // error: ambiguous base subobjects
2587   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2588   //   }
2589   if (Qualifier && Qualifier->getAsType()) {
2590     QualType QType = QualType(Qualifier->getAsType(), 0);
2591     assert(QType->isRecordType() && "lookup done with non-record type");
2592 
2593     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2594 
2595     // In C++98, the qualifier type doesn't actually have to be a base
2596     // type of the object type, in which case we just ignore it.
2597     // Otherwise build the appropriate casts.
2598     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2599       CXXCastPath BasePath;
2600       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2601                                        FromLoc, FromRange, &BasePath))
2602         return ExprError();
2603 
2604       if (PointerConversions)
2605         QType = Context.getPointerType(QType);
2606       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2607                                VK, &BasePath).get();
2608 
2609       FromType = QType;
2610       FromRecordType = QRecordType;
2611 
2612       // If the qualifier type was the same as the destination type,
2613       // we're done.
2614       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2615         return From;
2616     }
2617   }
2618 
2619   bool IgnoreAccess = false;
2620 
2621   // If we actually found the member through a using declaration, cast
2622   // down to the using declaration's type.
2623   //
2624   // Pointer equality is fine here because only one declaration of a
2625   // class ever has member declarations.
2626   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2627     assert(isa<UsingShadowDecl>(FoundDecl));
2628     QualType URecordType = Context.getTypeDeclType(
2629                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2630 
2631     // We only need to do this if the naming-class to declaring-class
2632     // conversion is non-trivial.
2633     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2634       assert(IsDerivedFrom(FromRecordType, URecordType));
2635       CXXCastPath BasePath;
2636       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2637                                        FromLoc, FromRange, &BasePath))
2638         return ExprError();
2639 
2640       QualType UType = URecordType;
2641       if (PointerConversions)
2642         UType = Context.getPointerType(UType);
2643       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2644                                VK, &BasePath).get();
2645       FromType = UType;
2646       FromRecordType = URecordType;
2647     }
2648 
2649     // We don't do access control for the conversion from the
2650     // declaring class to the true declaring class.
2651     IgnoreAccess = true;
2652   }
2653 
2654   CXXCastPath BasePath;
2655   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2656                                    FromLoc, FromRange, &BasePath,
2657                                    IgnoreAccess))
2658     return ExprError();
2659 
2660   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2661                            VK, &BasePath);
2662 }
2663 
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2664 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2665                                       const LookupResult &R,
2666                                       bool HasTrailingLParen) {
2667   // Only when used directly as the postfix-expression of a call.
2668   if (!HasTrailingLParen)
2669     return false;
2670 
2671   // Never if a scope specifier was provided.
2672   if (SS.isSet())
2673     return false;
2674 
2675   // Only in C++ or ObjC++.
2676   if (!getLangOpts().CPlusPlus)
2677     return false;
2678 
2679   // Turn off ADL when we find certain kinds of declarations during
2680   // normal lookup:
2681   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2682     NamedDecl *D = *I;
2683 
2684     // C++0x [basic.lookup.argdep]p3:
2685     //     -- a declaration of a class member
2686     // Since using decls preserve this property, we check this on the
2687     // original decl.
2688     if (D->isCXXClassMember())
2689       return false;
2690 
2691     // C++0x [basic.lookup.argdep]p3:
2692     //     -- a block-scope function declaration that is not a
2693     //        using-declaration
2694     // NOTE: we also trigger this for function templates (in fact, we
2695     // don't check the decl type at all, since all other decl types
2696     // turn off ADL anyway).
2697     if (isa<UsingShadowDecl>(D))
2698       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2699     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2700       return false;
2701 
2702     // C++0x [basic.lookup.argdep]p3:
2703     //     -- a declaration that is neither a function or a function
2704     //        template
2705     // And also for builtin functions.
2706     if (isa<FunctionDecl>(D)) {
2707       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2708 
2709       // But also builtin functions.
2710       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2711         return false;
2712     } else if (!isa<FunctionTemplateDecl>(D))
2713       return false;
2714   }
2715 
2716   return true;
2717 }
2718 
2719 
2720 /// Diagnoses obvious problems with the use of the given declaration
2721 /// as an expression.  This is only actually called for lookups that
2722 /// were not overloaded, and it doesn't promise that the declaration
2723 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)2724 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2725   if (isa<TypedefNameDecl>(D)) {
2726     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2727     return true;
2728   }
2729 
2730   if (isa<ObjCInterfaceDecl>(D)) {
2731     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2732     return true;
2733   }
2734 
2735   if (isa<NamespaceDecl>(D)) {
2736     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2737     return true;
2738   }
2739 
2740   return false;
2741 }
2742 
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)2743 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2744                                           LookupResult &R, bool NeedsADL,
2745                                           bool AcceptInvalidDecl) {
2746   // If this is a single, fully-resolved result and we don't need ADL,
2747   // just build an ordinary singleton decl ref.
2748   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2749     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2750                                     R.getRepresentativeDecl(), nullptr,
2751                                     AcceptInvalidDecl);
2752 
2753   // We only need to check the declaration if there's exactly one
2754   // result, because in the overloaded case the results can only be
2755   // functions and function templates.
2756   if (R.isSingleResult() &&
2757       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2758     return ExprError();
2759 
2760   // Otherwise, just build an unresolved lookup expression.  Suppress
2761   // any lookup-related diagnostics; we'll hash these out later, when
2762   // we've picked a target.
2763   R.suppressDiagnostics();
2764 
2765   UnresolvedLookupExpr *ULE
2766     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2767                                    SS.getWithLocInContext(Context),
2768                                    R.getLookupNameInfo(),
2769                                    NeedsADL, R.isOverloadedResult(),
2770                                    R.begin(), R.end());
2771 
2772   return ULE;
2773 }
2774 
2775 /// \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)2776 ExprResult Sema::BuildDeclarationNameExpr(
2777     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2778     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2779     bool AcceptInvalidDecl) {
2780   assert(D && "Cannot refer to a NULL declaration");
2781   assert(!isa<FunctionTemplateDecl>(D) &&
2782          "Cannot refer unambiguously to a function template");
2783 
2784   SourceLocation Loc = NameInfo.getLoc();
2785   if (CheckDeclInExpr(*this, Loc, D))
2786     return ExprError();
2787 
2788   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2789     // Specifically diagnose references to class templates that are missing
2790     // a template argument list.
2791     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2792                                            << Template << SS.getRange();
2793     Diag(Template->getLocation(), diag::note_template_decl_here);
2794     return ExprError();
2795   }
2796 
2797   // Make sure that we're referring to a value.
2798   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2799   if (!VD) {
2800     Diag(Loc, diag::err_ref_non_value)
2801       << D << SS.getRange();
2802     Diag(D->getLocation(), diag::note_declared_at);
2803     return ExprError();
2804   }
2805 
2806   // Check whether this declaration can be used. Note that we suppress
2807   // this check when we're going to perform argument-dependent lookup
2808   // on this function name, because this might not be the function
2809   // that overload resolution actually selects.
2810   if (DiagnoseUseOfDecl(VD, Loc))
2811     return ExprError();
2812 
2813   // Only create DeclRefExpr's for valid Decl's.
2814   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2815     return ExprError();
2816 
2817   // Handle members of anonymous structs and unions.  If we got here,
2818   // and the reference is to a class member indirect field, then this
2819   // must be the subject of a pointer-to-member expression.
2820   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2821     if (!indirectField->isCXXClassMember())
2822       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2823                                                       indirectField);
2824 
2825   {
2826     QualType type = VD->getType();
2827     ExprValueKind valueKind = VK_RValue;
2828 
2829     switch (D->getKind()) {
2830     // Ignore all the non-ValueDecl kinds.
2831 #define ABSTRACT_DECL(kind)
2832 #define VALUE(type, base)
2833 #define DECL(type, base) \
2834     case Decl::type:
2835 #include "clang/AST/DeclNodes.inc"
2836       llvm_unreachable("invalid value decl kind");
2837 
2838     // These shouldn't make it here.
2839     case Decl::ObjCAtDefsField:
2840     case Decl::ObjCIvar:
2841       llvm_unreachable("forming non-member reference to ivar?");
2842 
2843     // Enum constants are always r-values and never references.
2844     // Unresolved using declarations are dependent.
2845     case Decl::EnumConstant:
2846     case Decl::UnresolvedUsingValue:
2847       valueKind = VK_RValue;
2848       break;
2849 
2850     // Fields and indirect fields that got here must be for
2851     // pointer-to-member expressions; we just call them l-values for
2852     // internal consistency, because this subexpression doesn't really
2853     // exist in the high-level semantics.
2854     case Decl::Field:
2855     case Decl::IndirectField:
2856       assert(getLangOpts().CPlusPlus &&
2857              "building reference to field in C?");
2858 
2859       // These can't have reference type in well-formed programs, but
2860       // for internal consistency we do this anyway.
2861       type = type.getNonReferenceType();
2862       valueKind = VK_LValue;
2863       break;
2864 
2865     // Non-type template parameters are either l-values or r-values
2866     // depending on the type.
2867     case Decl::NonTypeTemplateParm: {
2868       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869         type = reftype->getPointeeType();
2870         valueKind = VK_LValue; // even if the parameter is an r-value reference
2871         break;
2872       }
2873 
2874       // For non-references, we need to strip qualifiers just in case
2875       // the template parameter was declared as 'const int' or whatever.
2876       valueKind = VK_RValue;
2877       type = type.getUnqualifiedType();
2878       break;
2879     }
2880 
2881     case Decl::Var:
2882     case Decl::VarTemplateSpecialization:
2883     case Decl::VarTemplatePartialSpecialization:
2884       // In C, "extern void blah;" is valid and is an r-value.
2885       if (!getLangOpts().CPlusPlus &&
2886           !type.hasQualifiers() &&
2887           type->isVoidType()) {
2888         valueKind = VK_RValue;
2889         break;
2890       }
2891       // fallthrough
2892 
2893     case Decl::ImplicitParam:
2894     case Decl::ParmVar: {
2895       // These are always l-values.
2896       valueKind = VK_LValue;
2897       type = type.getNonReferenceType();
2898 
2899       // FIXME: Does the addition of const really only apply in
2900       // potentially-evaluated contexts? Since the variable isn't actually
2901       // captured in an unevaluated context, it seems that the answer is no.
2902       if (!isUnevaluatedContext()) {
2903         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2904         if (!CapturedType.isNull())
2905           type = CapturedType;
2906       }
2907 
2908       break;
2909     }
2910 
2911     case Decl::Function: {
2912       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2913         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2914           type = Context.BuiltinFnTy;
2915           valueKind = VK_RValue;
2916           break;
2917         }
2918       }
2919 
2920       const FunctionType *fty = type->castAs<FunctionType>();
2921 
2922       // If we're referring to a function with an __unknown_anytype
2923       // result type, make the entire expression __unknown_anytype.
2924       if (fty->getReturnType() == Context.UnknownAnyTy) {
2925         type = Context.UnknownAnyTy;
2926         valueKind = VK_RValue;
2927         break;
2928       }
2929 
2930       // Functions are l-values in C++.
2931       if (getLangOpts().CPlusPlus) {
2932         valueKind = VK_LValue;
2933         break;
2934       }
2935 
2936       // C99 DR 316 says that, if a function type comes from a
2937       // function definition (without a prototype), that type is only
2938       // used for checking compatibility. Therefore, when referencing
2939       // the function, we pretend that we don't have the full function
2940       // type.
2941       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2942           isa<FunctionProtoType>(fty))
2943         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2944                                               fty->getExtInfo());
2945 
2946       // Functions are r-values in C.
2947       valueKind = VK_RValue;
2948       break;
2949     }
2950 
2951     case Decl::MSProperty:
2952       valueKind = VK_LValue;
2953       break;
2954 
2955     case Decl::CXXMethod:
2956       // If we're referring to a method with an __unknown_anytype
2957       // result type, make the entire expression __unknown_anytype.
2958       // This should only be possible with a type written directly.
2959       if (const FunctionProtoType *proto
2960             = dyn_cast<FunctionProtoType>(VD->getType()))
2961         if (proto->getReturnType() == Context.UnknownAnyTy) {
2962           type = Context.UnknownAnyTy;
2963           valueKind = VK_RValue;
2964           break;
2965         }
2966 
2967       // C++ methods are l-values if static, r-values if non-static.
2968       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2969         valueKind = VK_LValue;
2970         break;
2971       }
2972       // fallthrough
2973 
2974     case Decl::CXXConversion:
2975     case Decl::CXXDestructor:
2976     case Decl::CXXConstructor:
2977       valueKind = VK_RValue;
2978       break;
2979     }
2980 
2981     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2982                             TemplateArgs);
2983   }
2984 }
2985 
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)2986 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2987                                     SmallString<32> &Target) {
2988   Target.resize(CharByteWidth * (Source.size() + 1));
2989   char *ResultPtr = &Target[0];
2990   const UTF8 *ErrorPtr;
2991   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2992   (void)success;
2993   assert(success);
2994   Target.resize(ResultPtr - &Target[0]);
2995 }
2996 
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentType IT)2997 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2998                                      PredefinedExpr::IdentType IT) {
2999   // Pick the current block, lambda, captured statement or function.
3000   Decl *currentDecl = nullptr;
3001   if (const BlockScopeInfo *BSI = getCurBlock())
3002     currentDecl = BSI->TheDecl;
3003   else if (const LambdaScopeInfo *LSI = getCurLambda())
3004     currentDecl = LSI->CallOperator;
3005   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3006     currentDecl = CSI->TheCapturedDecl;
3007   else
3008     currentDecl = getCurFunctionOrMethodDecl();
3009 
3010   if (!currentDecl) {
3011     Diag(Loc, diag::ext_predef_outside_function);
3012     currentDecl = Context.getTranslationUnitDecl();
3013   }
3014 
3015   QualType ResTy;
3016   StringLiteral *SL = nullptr;
3017   if (cast<DeclContext>(currentDecl)->isDependentContext())
3018     ResTy = Context.DependentTy;
3019   else {
3020     // Pre-defined identifiers are of type char[x], where x is the length of
3021     // the string.
3022     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3023     unsigned Length = Str.length();
3024 
3025     llvm::APInt LengthI(32, Length + 1);
3026     if (IT == PredefinedExpr::LFunction) {
3027       ResTy = Context.WideCharTy.withConst();
3028       SmallString<32> RawChars;
3029       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3030                               Str, RawChars);
3031       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3032                                            /*IndexTypeQuals*/ 0);
3033       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3034                                  /*Pascal*/ false, ResTy, Loc);
3035     } else {
3036       ResTy = Context.CharTy.withConst();
3037       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3038                                            /*IndexTypeQuals*/ 0);
3039       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3040                                  /*Pascal*/ false, ResTy, Loc);
3041     }
3042   }
3043 
3044   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3045 }
3046 
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3047 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3048   PredefinedExpr::IdentType IT;
3049 
3050   switch (Kind) {
3051   default: llvm_unreachable("Unknown simple primary expr!");
3052   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3053   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3054   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3055   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3056   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3057   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3058   }
3059 
3060   return BuildPredefinedExpr(Loc, IT);
3061 }
3062 
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3063 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3064   SmallString<16> CharBuffer;
3065   bool Invalid = false;
3066   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3067   if (Invalid)
3068     return ExprError();
3069 
3070   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3071                             PP, Tok.getKind());
3072   if (Literal.hadError())
3073     return ExprError();
3074 
3075   QualType Ty;
3076   if (Literal.isWide())
3077     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3078   else if (Literal.isUTF16())
3079     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3080   else if (Literal.isUTF32())
3081     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3082   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3083     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3084   else
3085     Ty = Context.CharTy;  // 'x' -> char in C++
3086 
3087   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3088   if (Literal.isWide())
3089     Kind = CharacterLiteral::Wide;
3090   else if (Literal.isUTF16())
3091     Kind = CharacterLiteral::UTF16;
3092   else if (Literal.isUTF32())
3093     Kind = CharacterLiteral::UTF32;
3094 
3095   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3096                                              Tok.getLocation());
3097 
3098   if (Literal.getUDSuffix().empty())
3099     return Lit;
3100 
3101   // We're building a user-defined literal.
3102   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3103   SourceLocation UDSuffixLoc =
3104     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3105 
3106   // Make sure we're allowed user-defined literals here.
3107   if (!UDLScope)
3108     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3109 
3110   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3111   //   operator "" X (ch)
3112   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3113                                         Lit, Tok.getLocation());
3114 }
3115 
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3116 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3117   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3118   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3119                                 Context.IntTy, Loc);
3120 }
3121 
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3122 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3123                                   QualType Ty, SourceLocation Loc) {
3124   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3125 
3126   using llvm::APFloat;
3127   APFloat Val(Format);
3128 
3129   APFloat::opStatus result = Literal.GetFloatValue(Val);
3130 
3131   // Overflow is always an error, but underflow is only an error if
3132   // we underflowed to zero (APFloat reports denormals as underflow).
3133   if ((result & APFloat::opOverflow) ||
3134       ((result & APFloat::opUnderflow) && Val.isZero())) {
3135     unsigned diagnostic;
3136     SmallString<20> buffer;
3137     if (result & APFloat::opOverflow) {
3138       diagnostic = diag::warn_float_overflow;
3139       APFloat::getLargest(Format).toString(buffer);
3140     } else {
3141       diagnostic = diag::warn_float_underflow;
3142       APFloat::getSmallest(Format).toString(buffer);
3143     }
3144 
3145     S.Diag(Loc, diagnostic)
3146       << Ty
3147       << StringRef(buffer.data(), buffer.size());
3148   }
3149 
3150   bool isExact = (result == APFloat::opOK);
3151   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3152 }
3153 
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3154 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3155   assert(E && "Invalid expression");
3156 
3157   if (E->isValueDependent())
3158     return false;
3159 
3160   QualType QT = E->getType();
3161   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3162     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3163     return true;
3164   }
3165 
3166   llvm::APSInt ValueAPS;
3167   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3168 
3169   if (R.isInvalid())
3170     return true;
3171 
3172   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3173   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3174     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3175         << ValueAPS.toString(10) << ValueIsPositive;
3176     return true;
3177   }
3178 
3179   return false;
3180 }
3181 
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3182 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3183   // Fast path for a single digit (which is quite common).  A single digit
3184   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3185   if (Tok.getLength() == 1) {
3186     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3187     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3188   }
3189 
3190   SmallString<128> SpellingBuffer;
3191   // NumericLiteralParser wants to overread by one character.  Add padding to
3192   // the buffer in case the token is copied to the buffer.  If getSpelling()
3193   // returns a StringRef to the memory buffer, it should have a null char at
3194   // the EOF, so it is also safe.
3195   SpellingBuffer.resize(Tok.getLength() + 1);
3196 
3197   // Get the spelling of the token, which eliminates trigraphs, etc.
3198   bool Invalid = false;
3199   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3200   if (Invalid)
3201     return ExprError();
3202 
3203   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3204   if (Literal.hadError)
3205     return ExprError();
3206 
3207   if (Literal.hasUDSuffix()) {
3208     // We're building a user-defined literal.
3209     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3210     SourceLocation UDSuffixLoc =
3211       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3212 
3213     // Make sure we're allowed user-defined literals here.
3214     if (!UDLScope)
3215       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3216 
3217     QualType CookedTy;
3218     if (Literal.isFloatingLiteral()) {
3219       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3220       // long double, the literal is treated as a call of the form
3221       //   operator "" X (f L)
3222       CookedTy = Context.LongDoubleTy;
3223     } else {
3224       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3225       // unsigned long long, the literal is treated as a call of the form
3226       //   operator "" X (n ULL)
3227       CookedTy = Context.UnsignedLongLongTy;
3228     }
3229 
3230     DeclarationName OpName =
3231       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3232     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3233     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3234 
3235     SourceLocation TokLoc = Tok.getLocation();
3236 
3237     // Perform literal operator lookup to determine if we're building a raw
3238     // literal or a cooked one.
3239     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3240     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3241                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3242                                   /*AllowStringTemplate*/false)) {
3243     case LOLR_Error:
3244       return ExprError();
3245 
3246     case LOLR_Cooked: {
3247       Expr *Lit;
3248       if (Literal.isFloatingLiteral()) {
3249         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3250       } else {
3251         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3252         if (Literal.GetIntegerValue(ResultVal))
3253           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3254               << /* Unsigned */ 1;
3255         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3256                                      Tok.getLocation());
3257       }
3258       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3259     }
3260 
3261     case LOLR_Raw: {
3262       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3263       // literal is treated as a call of the form
3264       //   operator "" X ("n")
3265       unsigned Length = Literal.getUDSuffixOffset();
3266       QualType StrTy = Context.getConstantArrayType(
3267           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3268           ArrayType::Normal, 0);
3269       Expr *Lit = StringLiteral::Create(
3270           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3271           /*Pascal*/false, StrTy, &TokLoc, 1);
3272       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3273     }
3274 
3275     case LOLR_Template: {
3276       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3277       // template), L is treated as a call fo the form
3278       //   operator "" X <'c1', 'c2', ... 'ck'>()
3279       // where n is the source character sequence c1 c2 ... ck.
3280       TemplateArgumentListInfo ExplicitArgs;
3281       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3282       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3283       llvm::APSInt Value(CharBits, CharIsUnsigned);
3284       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3285         Value = TokSpelling[I];
3286         TemplateArgument Arg(Context, Value, Context.CharTy);
3287         TemplateArgumentLocInfo ArgInfo;
3288         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3289       }
3290       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3291                                       &ExplicitArgs);
3292     }
3293     case LOLR_StringTemplate:
3294       llvm_unreachable("unexpected literal operator lookup result");
3295     }
3296   }
3297 
3298   Expr *Res;
3299 
3300   if (Literal.isFloatingLiteral()) {
3301     QualType Ty;
3302     if (Literal.isFloat)
3303       Ty = Context.FloatTy;
3304     else if (!Literal.isLong)
3305       Ty = Context.DoubleTy;
3306     else
3307       Ty = Context.LongDoubleTy;
3308 
3309     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3310 
3311     if (Ty == Context.DoubleTy) {
3312       if (getLangOpts().SinglePrecisionConstants) {
3313         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3314       } else if (getLangOpts().OpenCL &&
3315                  !((getLangOpts().OpenCLVersion >= 120) ||
3316                    getOpenCLOptions().cl_khr_fp64)) {
3317         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3318         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3319       }
3320     }
3321   } else if (!Literal.isIntegerLiteral()) {
3322     return ExprError();
3323   } else {
3324     QualType Ty;
3325 
3326     // 'long long' is a C99 or C++11 feature.
3327     if (!getLangOpts().C99 && Literal.isLongLong) {
3328       if (getLangOpts().CPlusPlus)
3329         Diag(Tok.getLocation(),
3330              getLangOpts().CPlusPlus11 ?
3331              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3332       else
3333         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3334     }
3335 
3336     // Get the value in the widest-possible width.
3337     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3338     // The microsoft literal suffix extensions support 128-bit literals, which
3339     // may be wider than [u]intmax_t.
3340     // FIXME: Actually, they don't. We seem to have accidentally invented the
3341     //        i128 suffix.
3342     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3343         Context.getTargetInfo().hasInt128Type())
3344       MaxWidth = 128;
3345     llvm::APInt ResultVal(MaxWidth, 0);
3346 
3347     if (Literal.GetIntegerValue(ResultVal)) {
3348       // If this value didn't fit into uintmax_t, error and force to ull.
3349       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3350           << /* Unsigned */ 1;
3351       Ty = Context.UnsignedLongLongTy;
3352       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3353              "long long is not intmax_t?");
3354     } else {
3355       // If this value fits into a ULL, try to figure out what else it fits into
3356       // according to the rules of C99 6.4.4.1p5.
3357 
3358       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3359       // be an unsigned int.
3360       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3361 
3362       // Check from smallest to largest, picking the smallest type we can.
3363       unsigned Width = 0;
3364 
3365       // Microsoft specific integer suffixes are explicitly sized.
3366       if (Literal.MicrosoftInteger) {
3367         if (Literal.MicrosoftInteger > MaxWidth) {
3368           // If this target doesn't support __int128, error and force to ull.
3369           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3370           Width = MaxWidth;
3371           Ty = Context.getIntMaxType();
3372         } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3373           Width = 8;
3374           Ty = Context.CharTy;
3375         } else {
3376           Width = Literal.MicrosoftInteger;
3377           Ty = Context.getIntTypeForBitwidth(Width,
3378                                              /*Signed=*/!Literal.isUnsigned);
3379         }
3380       }
3381 
3382       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3383         // Are int/unsigned possibilities?
3384         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3385 
3386         // Does it fit in a unsigned int?
3387         if (ResultVal.isIntN(IntSize)) {
3388           // Does it fit in a signed int?
3389           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3390             Ty = Context.IntTy;
3391           else if (AllowUnsigned)
3392             Ty = Context.UnsignedIntTy;
3393           Width = IntSize;
3394         }
3395       }
3396 
3397       // Are long/unsigned long possibilities?
3398       if (Ty.isNull() && !Literal.isLongLong) {
3399         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3400 
3401         // Does it fit in a unsigned long?
3402         if (ResultVal.isIntN(LongSize)) {
3403           // Does it fit in a signed long?
3404           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3405             Ty = Context.LongTy;
3406           else if (AllowUnsigned)
3407             Ty = Context.UnsignedLongTy;
3408           Width = LongSize;
3409         }
3410       }
3411 
3412       // Check long long if needed.
3413       if (Ty.isNull()) {
3414         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3415 
3416         // Does it fit in a unsigned long long?
3417         if (ResultVal.isIntN(LongLongSize)) {
3418           // Does it fit in a signed long long?
3419           // To be compatible with MSVC, hex integer literals ending with the
3420           // LL or i64 suffix are always signed in Microsoft mode.
3421           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3422               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3423             Ty = Context.LongLongTy;
3424           else if (AllowUnsigned)
3425             Ty = Context.UnsignedLongLongTy;
3426           Width = LongLongSize;
3427         }
3428       }
3429 
3430       // If we still couldn't decide a type, we probably have something that
3431       // does not fit in a signed long long, but has no U suffix.
3432       if (Ty.isNull()) {
3433         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3434         Ty = Context.UnsignedLongLongTy;
3435         Width = Context.getTargetInfo().getLongLongWidth();
3436       }
3437 
3438       if (ResultVal.getBitWidth() != Width)
3439         ResultVal = ResultVal.trunc(Width);
3440     }
3441     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3442   }
3443 
3444   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3445   if (Literal.isImaginary)
3446     Res = new (Context) ImaginaryLiteral(Res,
3447                                         Context.getComplexType(Res->getType()));
3448 
3449   return Res;
3450 }
3451 
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3452 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3453   assert(E && "ActOnParenExpr() missing expr");
3454   return new (Context) ParenExpr(L, R, E);
3455 }
3456 
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3457 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3458                                          SourceLocation Loc,
3459                                          SourceRange ArgRange) {
3460   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3461   // scalar or vector data type argument..."
3462   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3463   // type (C99 6.2.5p18) or void.
3464   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3465     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3466       << T << ArgRange;
3467     return true;
3468   }
3469 
3470   assert((T->isVoidType() || !T->isIncompleteType()) &&
3471          "Scalar types should always be complete");
3472   return false;
3473 }
3474 
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3475 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3476                                            SourceLocation Loc,
3477                                            SourceRange ArgRange,
3478                                            UnaryExprOrTypeTrait TraitKind) {
3479   // Invalid types must be hard errors for SFINAE in C++.
3480   if (S.LangOpts.CPlusPlus)
3481     return true;
3482 
3483   // C99 6.5.3.4p1:
3484   if (T->isFunctionType() &&
3485       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3486     // sizeof(function)/alignof(function) is allowed as an extension.
3487     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3488       << TraitKind << ArgRange;
3489     return false;
3490   }
3491 
3492   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3493   // this is an error (OpenCL v1.1 s6.3.k)
3494   if (T->isVoidType()) {
3495     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3496                                         : diag::ext_sizeof_alignof_void_type;
3497     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3498     return false;
3499   }
3500 
3501   return true;
3502 }
3503 
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3504 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3505                                              SourceLocation Loc,
3506                                              SourceRange ArgRange,
3507                                              UnaryExprOrTypeTrait TraitKind) {
3508   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3509   // runtime doesn't allow it.
3510   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3511     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3512       << T << (TraitKind == UETT_SizeOf)
3513       << ArgRange;
3514     return true;
3515   }
3516 
3517   return false;
3518 }
3519 
3520 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3521 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)3522 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3523                                      Expr *E) {
3524   // Don't warn if the operation changed the type.
3525   if (T != E->getType())
3526     return;
3527 
3528   // Now look for array decays.
3529   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3530   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3531     return;
3532 
3533   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3534                                              << ICE->getType()
3535                                              << ICE->getSubExpr()->getType();
3536 }
3537 
3538 /// \brief Check the constraints on expression operands to unary type expression
3539 /// and type traits.
3540 ///
3541 /// Completes any types necessary and validates the constraints on the operand
3542 /// expression. The logic mostly mirrors the type-based overload, but may modify
3543 /// the expression as it completes the type for that expression through template
3544 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)3545 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3546                                             UnaryExprOrTypeTrait ExprKind) {
3547   QualType ExprTy = E->getType();
3548   assert(!ExprTy->isReferenceType());
3549 
3550   if (ExprKind == UETT_VecStep)
3551     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3552                                         E->getSourceRange());
3553 
3554   // Whitelist some types as extensions
3555   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3556                                       E->getSourceRange(), ExprKind))
3557     return false;
3558 
3559   // 'alignof' applied to an expression only requires the base element type of
3560   // the expression to be complete. 'sizeof' requires the expression's type to
3561   // be complete (and will attempt to complete it if it's an array of unknown
3562   // bound).
3563   if (ExprKind == UETT_AlignOf) {
3564     if (RequireCompleteType(E->getExprLoc(),
3565                             Context.getBaseElementType(E->getType()),
3566                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3567                             E->getSourceRange()))
3568       return true;
3569   } else {
3570     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3571                                 ExprKind, E->getSourceRange()))
3572       return true;
3573   }
3574 
3575   // Completing the expression's type may have changed it.
3576   ExprTy = E->getType();
3577   assert(!ExprTy->isReferenceType());
3578 
3579   if (ExprTy->isFunctionType()) {
3580     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3581       << ExprKind << E->getSourceRange();
3582     return true;
3583   }
3584 
3585   // The operand for sizeof and alignof is in an unevaluated expression context,
3586   // so side effects could result in unintended consequences.
3587   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3588       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3589     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3590 
3591   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3592                                        E->getSourceRange(), ExprKind))
3593     return true;
3594 
3595   if (ExprKind == UETT_SizeOf) {
3596     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3597       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3598         QualType OType = PVD->getOriginalType();
3599         QualType Type = PVD->getType();
3600         if (Type->isPointerType() && OType->isArrayType()) {
3601           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3602             << Type << OType;
3603           Diag(PVD->getLocation(), diag::note_declared_at);
3604         }
3605       }
3606     }
3607 
3608     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3609     // decays into a pointer and returns an unintended result. This is most
3610     // likely a typo for "sizeof(array) op x".
3611     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3612       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3613                                BO->getLHS());
3614       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3615                                BO->getRHS());
3616     }
3617   }
3618 
3619   return false;
3620 }
3621 
3622 /// \brief Check the constraints on operands to unary expression and type
3623 /// traits.
3624 ///
3625 /// This will complete any types necessary, and validate the various constraints
3626 /// on those operands.
3627 ///
3628 /// The UsualUnaryConversions() function is *not* called by this routine.
3629 /// C99 6.3.2.1p[2-4] all state:
3630 ///   Except when it is the operand of the sizeof operator ...
3631 ///
3632 /// C++ [expr.sizeof]p4
3633 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3634 ///   standard conversions are not applied to the operand of sizeof.
3635 ///
3636 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)3637 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3638                                             SourceLocation OpLoc,
3639                                             SourceRange ExprRange,
3640                                             UnaryExprOrTypeTrait ExprKind) {
3641   if (ExprType->isDependentType())
3642     return false;
3643 
3644   // C++ [expr.sizeof]p2:
3645   //     When applied to a reference or a reference type, the result
3646   //     is the size of the referenced type.
3647   // C++11 [expr.alignof]p3:
3648   //     When alignof is applied to a reference type, the result
3649   //     shall be the alignment of the referenced type.
3650   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3651     ExprType = Ref->getPointeeType();
3652 
3653   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3654   //   When alignof or _Alignof is applied to an array type, the result
3655   //   is the alignment of the element type.
3656   if (ExprKind == UETT_AlignOf)
3657     ExprType = Context.getBaseElementType(ExprType);
3658 
3659   if (ExprKind == UETT_VecStep)
3660     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3661 
3662   // Whitelist some types as extensions
3663   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3664                                       ExprKind))
3665     return false;
3666 
3667   if (RequireCompleteType(OpLoc, ExprType,
3668                           diag::err_sizeof_alignof_incomplete_type,
3669                           ExprKind, ExprRange))
3670     return true;
3671 
3672   if (ExprType->isFunctionType()) {
3673     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3674       << ExprKind << ExprRange;
3675     return true;
3676   }
3677 
3678   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3679                                        ExprKind))
3680     return true;
3681 
3682   return false;
3683 }
3684 
CheckAlignOfExpr(Sema & S,Expr * E)3685 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3686   E = E->IgnoreParens();
3687 
3688   // Cannot know anything else if the expression is dependent.
3689   if (E->isTypeDependent())
3690     return false;
3691 
3692   if (E->getObjectKind() == OK_BitField) {
3693     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3694        << 1 << E->getSourceRange();
3695     return true;
3696   }
3697 
3698   ValueDecl *D = nullptr;
3699   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3700     D = DRE->getDecl();
3701   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3702     D = ME->getMemberDecl();
3703   }
3704 
3705   // If it's a field, require the containing struct to have a
3706   // complete definition so that we can compute the layout.
3707   //
3708   // This can happen in C++11 onwards, either by naming the member
3709   // in a way that is not transformed into a member access expression
3710   // (in an unevaluated operand, for instance), or by naming the member
3711   // in a trailing-return-type.
3712   //
3713   // For the record, since __alignof__ on expressions is a GCC
3714   // extension, GCC seems to permit this but always gives the
3715   // nonsensical answer 0.
3716   //
3717   // We don't really need the layout here --- we could instead just
3718   // directly check for all the appropriate alignment-lowing
3719   // attributes --- but that would require duplicating a lot of
3720   // logic that just isn't worth duplicating for such a marginal
3721   // use-case.
3722   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3723     // Fast path this check, since we at least know the record has a
3724     // definition if we can find a member of it.
3725     if (!FD->getParent()->isCompleteDefinition()) {
3726       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3727         << E->getSourceRange();
3728       return true;
3729     }
3730 
3731     // Otherwise, if it's a field, and the field doesn't have
3732     // reference type, then it must have a complete type (or be a
3733     // flexible array member, which we explicitly want to
3734     // white-list anyway), which makes the following checks trivial.
3735     if (!FD->getType()->isReferenceType())
3736       return false;
3737   }
3738 
3739   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3740 }
3741 
CheckVecStepExpr(Expr * E)3742 bool Sema::CheckVecStepExpr(Expr *E) {
3743   E = E->IgnoreParens();
3744 
3745   // Cannot know anything else if the expression is dependent.
3746   if (E->isTypeDependent())
3747     return false;
3748 
3749   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3750 }
3751 
3752 /// \brief Build a sizeof or alignof expression given a type operand.
3753 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)3754 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3755                                      SourceLocation OpLoc,
3756                                      UnaryExprOrTypeTrait ExprKind,
3757                                      SourceRange R) {
3758   if (!TInfo)
3759     return ExprError();
3760 
3761   QualType T = TInfo->getType();
3762 
3763   if (!T->isDependentType() &&
3764       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3765     return ExprError();
3766 
3767   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3768   return new (Context) UnaryExprOrTypeTraitExpr(
3769       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3770 }
3771 
3772 /// \brief Build a sizeof or alignof expression given an expression
3773 /// operand.
3774 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)3775 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3776                                      UnaryExprOrTypeTrait ExprKind) {
3777   ExprResult PE = CheckPlaceholderExpr(E);
3778   if (PE.isInvalid())
3779     return ExprError();
3780 
3781   E = PE.get();
3782 
3783   // Verify that the operand is valid.
3784   bool isInvalid = false;
3785   if (E->isTypeDependent()) {
3786     // Delay type-checking for type-dependent expressions.
3787   } else if (ExprKind == UETT_AlignOf) {
3788     isInvalid = CheckAlignOfExpr(*this, E);
3789   } else if (ExprKind == UETT_VecStep) {
3790     isInvalid = CheckVecStepExpr(E);
3791   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3792     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3793     isInvalid = true;
3794   } else {
3795     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3796   }
3797 
3798   if (isInvalid)
3799     return ExprError();
3800 
3801   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3802     PE = TransformToPotentiallyEvaluated(E);
3803     if (PE.isInvalid()) return ExprError();
3804     E = PE.get();
3805   }
3806 
3807   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3808   return new (Context) UnaryExprOrTypeTraitExpr(
3809       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3810 }
3811 
3812 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3813 /// expr and the same for @c alignof and @c __alignof
3814 /// Note that the ArgRange is invalid if isType is false.
3815 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,const SourceRange & ArgRange)3816 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3817                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3818                                     void *TyOrEx, const SourceRange &ArgRange) {
3819   // If error parsing type, ignore.
3820   if (!TyOrEx) return ExprError();
3821 
3822   if (IsType) {
3823     TypeSourceInfo *TInfo;
3824     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3825     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3826   }
3827 
3828   Expr *ArgEx = (Expr *)TyOrEx;
3829   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3830   return Result;
3831 }
3832 
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)3833 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3834                                      bool IsReal) {
3835   if (V.get()->isTypeDependent())
3836     return S.Context.DependentTy;
3837 
3838   // _Real and _Imag are only l-values for normal l-values.
3839   if (V.get()->getObjectKind() != OK_Ordinary) {
3840     V = S.DefaultLvalueConversion(V.get());
3841     if (V.isInvalid())
3842       return QualType();
3843   }
3844 
3845   // These operators return the element type of a complex type.
3846   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3847     return CT->getElementType();
3848 
3849   // Otherwise they pass through real integer and floating point types here.
3850   if (V.get()->getType()->isArithmeticType())
3851     return V.get()->getType();
3852 
3853   // Test for placeholders.
3854   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3855   if (PR.isInvalid()) return QualType();
3856   if (PR.get() != V.get()) {
3857     V = PR;
3858     return CheckRealImagOperand(S, V, Loc, IsReal);
3859   }
3860 
3861   // Reject anything else.
3862   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3863     << (IsReal ? "__real" : "__imag");
3864   return QualType();
3865 }
3866 
3867 
3868 
3869 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)3870 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3871                           tok::TokenKind Kind, Expr *Input) {
3872   UnaryOperatorKind Opc;
3873   switch (Kind) {
3874   default: llvm_unreachable("Unknown unary op!");
3875   case tok::plusplus:   Opc = UO_PostInc; break;
3876   case tok::minusminus: Opc = UO_PostDec; break;
3877   }
3878 
3879   // Since this might is a postfix expression, get rid of ParenListExprs.
3880   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3881   if (Result.isInvalid()) return ExprError();
3882   Input = Result.get();
3883 
3884   return BuildUnaryOp(S, OpLoc, Opc, Input);
3885 }
3886 
3887 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3888 ///
3889 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)3890 static bool checkArithmeticOnObjCPointer(Sema &S,
3891                                          SourceLocation opLoc,
3892                                          Expr *op) {
3893   assert(op->getType()->isObjCObjectPointerType());
3894   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3895       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3896     return false;
3897 
3898   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3899     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3900     << op->getSourceRange();
3901   return true;
3902 }
3903 
3904 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)3905 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3906                               Expr *idx, SourceLocation rbLoc) {
3907   // Since this might be a postfix expression, get rid of ParenListExprs.
3908   if (isa<ParenListExpr>(base)) {
3909     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3910     if (result.isInvalid()) return ExprError();
3911     base = result.get();
3912   }
3913 
3914   // Handle any non-overload placeholder types in the base and index
3915   // expressions.  We can't handle overloads here because the other
3916   // operand might be an overloadable type, in which case the overload
3917   // resolution for the operator overload should get the first crack
3918   // at the overload.
3919   if (base->getType()->isNonOverloadPlaceholderType()) {
3920     ExprResult result = CheckPlaceholderExpr(base);
3921     if (result.isInvalid()) return ExprError();
3922     base = result.get();
3923   }
3924   if (idx->getType()->isNonOverloadPlaceholderType()) {
3925     ExprResult result = CheckPlaceholderExpr(idx);
3926     if (result.isInvalid()) return ExprError();
3927     idx = result.get();
3928   }
3929 
3930   // Build an unanalyzed expression if either operand is type-dependent.
3931   if (getLangOpts().CPlusPlus &&
3932       (base->isTypeDependent() || idx->isTypeDependent())) {
3933     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3934                                             VK_LValue, OK_Ordinary, rbLoc);
3935   }
3936 
3937   // Use C++ overloaded-operator rules if either operand has record
3938   // type.  The spec says to do this if either type is *overloadable*,
3939   // but enum types can't declare subscript operators or conversion
3940   // operators, so there's nothing interesting for overload resolution
3941   // to do if there aren't any record types involved.
3942   //
3943   // ObjC pointers have their own subscripting logic that is not tied
3944   // to overload resolution and so should not take this path.
3945   if (getLangOpts().CPlusPlus &&
3946       (base->getType()->isRecordType() ||
3947        (!base->getType()->isObjCObjectPointerType() &&
3948         idx->getType()->isRecordType()))) {
3949     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3950   }
3951 
3952   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3953 }
3954 
3955 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)3956 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3957                                       Expr *Idx, SourceLocation RLoc) {
3958   Expr *LHSExp = Base;
3959   Expr *RHSExp = Idx;
3960 
3961   // Perform default conversions.
3962   if (!LHSExp->getType()->getAs<VectorType>()) {
3963     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3964     if (Result.isInvalid())
3965       return ExprError();
3966     LHSExp = Result.get();
3967   }
3968   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3969   if (Result.isInvalid())
3970     return ExprError();
3971   RHSExp = Result.get();
3972 
3973   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3974   ExprValueKind VK = VK_LValue;
3975   ExprObjectKind OK = OK_Ordinary;
3976 
3977   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3978   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3979   // in the subscript position. As a result, we need to derive the array base
3980   // and index from the expression types.
3981   Expr *BaseExpr, *IndexExpr;
3982   QualType ResultType;
3983   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3984     BaseExpr = LHSExp;
3985     IndexExpr = RHSExp;
3986     ResultType = Context.DependentTy;
3987   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3988     BaseExpr = LHSExp;
3989     IndexExpr = RHSExp;
3990     ResultType = PTy->getPointeeType();
3991   } else if (const ObjCObjectPointerType *PTy =
3992                LHSTy->getAs<ObjCObjectPointerType>()) {
3993     BaseExpr = LHSExp;
3994     IndexExpr = RHSExp;
3995 
3996     // Use custom logic if this should be the pseudo-object subscript
3997     // expression.
3998     if (!LangOpts.isSubscriptPointerArithmetic())
3999       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4000                                           nullptr);
4001 
4002     ResultType = PTy->getPointeeType();
4003   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4004      // Handle the uncommon case of "123[Ptr]".
4005     BaseExpr = RHSExp;
4006     IndexExpr = LHSExp;
4007     ResultType = PTy->getPointeeType();
4008   } else if (const ObjCObjectPointerType *PTy =
4009                RHSTy->getAs<ObjCObjectPointerType>()) {
4010      // Handle the uncommon case of "123[Ptr]".
4011     BaseExpr = RHSExp;
4012     IndexExpr = LHSExp;
4013     ResultType = PTy->getPointeeType();
4014     if (!LangOpts.isSubscriptPointerArithmetic()) {
4015       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4016         << ResultType << BaseExpr->getSourceRange();
4017       return ExprError();
4018     }
4019   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4020     BaseExpr = LHSExp;    // vectors: V[123]
4021     IndexExpr = RHSExp;
4022     VK = LHSExp->getValueKind();
4023     if (VK != VK_RValue)
4024       OK = OK_VectorComponent;
4025 
4026     // FIXME: need to deal with const...
4027     ResultType = VTy->getElementType();
4028   } else if (LHSTy->isArrayType()) {
4029     // If we see an array that wasn't promoted by
4030     // DefaultFunctionArrayLvalueConversion, it must be an array that
4031     // wasn't promoted because of the C90 rule that doesn't
4032     // allow promoting non-lvalue arrays.  Warn, then
4033     // force the promotion here.
4034     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4035         LHSExp->getSourceRange();
4036     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4037                                CK_ArrayToPointerDecay).get();
4038     LHSTy = LHSExp->getType();
4039 
4040     BaseExpr = LHSExp;
4041     IndexExpr = RHSExp;
4042     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4043   } else if (RHSTy->isArrayType()) {
4044     // Same as previous, except for 123[f().a] case
4045     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4046         RHSExp->getSourceRange();
4047     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4048                                CK_ArrayToPointerDecay).get();
4049     RHSTy = RHSExp->getType();
4050 
4051     BaseExpr = RHSExp;
4052     IndexExpr = LHSExp;
4053     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4054   } else {
4055     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4056        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4057   }
4058   // C99 6.5.2.1p1
4059   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4060     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4061                      << IndexExpr->getSourceRange());
4062 
4063   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4064        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4065          && !IndexExpr->isTypeDependent())
4066     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4067 
4068   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4069   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4070   // type. Note that Functions are not objects, and that (in C99 parlance)
4071   // incomplete types are not object types.
4072   if (ResultType->isFunctionType()) {
4073     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4074       << ResultType << BaseExpr->getSourceRange();
4075     return ExprError();
4076   }
4077 
4078   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4079     // GNU extension: subscripting on pointer to void
4080     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4081       << BaseExpr->getSourceRange();
4082 
4083     // C forbids expressions of unqualified void type from being l-values.
4084     // See IsCForbiddenLValueType.
4085     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4086   } else if (!ResultType->isDependentType() &&
4087       RequireCompleteType(LLoc, ResultType,
4088                           diag::err_subscript_incomplete_type, BaseExpr))
4089     return ExprError();
4090 
4091   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4092          !ResultType.isCForbiddenLValueType());
4093 
4094   return new (Context)
4095       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4096 }
4097 
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)4098 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4099                                         FunctionDecl *FD,
4100                                         ParmVarDecl *Param) {
4101   if (Param->hasUnparsedDefaultArg()) {
4102     Diag(CallLoc,
4103          diag::err_use_of_default_argument_to_function_declared_later) <<
4104       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4105     Diag(UnparsedDefaultArgLocs[Param],
4106          diag::note_default_argument_declared_here);
4107     return ExprError();
4108   }
4109 
4110   if (Param->hasUninstantiatedDefaultArg()) {
4111     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4112 
4113     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4114                                                  Param);
4115 
4116     // Instantiate the expression.
4117     MultiLevelTemplateArgumentList MutiLevelArgList
4118       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4119 
4120     InstantiatingTemplate Inst(*this, CallLoc, Param,
4121                                MutiLevelArgList.getInnermost());
4122     if (Inst.isInvalid())
4123       return ExprError();
4124 
4125     ExprResult Result;
4126     {
4127       // C++ [dcl.fct.default]p5:
4128       //   The names in the [default argument] expression are bound, and
4129       //   the semantic constraints are checked, at the point where the
4130       //   default argument expression appears.
4131       ContextRAII SavedContext(*this, FD);
4132       LocalInstantiationScope Local(*this);
4133       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4134     }
4135     if (Result.isInvalid())
4136       return ExprError();
4137 
4138     // Check the expression as an initializer for the parameter.
4139     InitializedEntity Entity
4140       = InitializedEntity::InitializeParameter(Context, Param);
4141     InitializationKind Kind
4142       = InitializationKind::CreateCopy(Param->getLocation(),
4143              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4144     Expr *ResultE = Result.getAs<Expr>();
4145 
4146     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4147     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4148     if (Result.isInvalid())
4149       return ExprError();
4150 
4151     Expr *Arg = Result.getAs<Expr>();
4152     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4153     // Build the default argument expression.
4154     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4155   }
4156 
4157   // If the default expression creates temporaries, we need to
4158   // push them to the current stack of expression temporaries so they'll
4159   // be properly destroyed.
4160   // FIXME: We should really be rebuilding the default argument with new
4161   // bound temporaries; see the comment in PR5810.
4162   // We don't need to do that with block decls, though, because
4163   // blocks in default argument expression can never capture anything.
4164   if (isa<ExprWithCleanups>(Param->getInit())) {
4165     // Set the "needs cleanups" bit regardless of whether there are
4166     // any explicit objects.
4167     ExprNeedsCleanups = true;
4168 
4169     // Append all the objects to the cleanup list.  Right now, this
4170     // should always be a no-op, because blocks in default argument
4171     // expressions should never be able to capture anything.
4172     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4173            "default argument expression has capturing blocks?");
4174   }
4175 
4176   // We already type-checked the argument, so we know it works.
4177   // Just mark all of the declarations in this potentially-evaluated expression
4178   // as being "referenced".
4179   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4180                                    /*SkipLocalVariables=*/true);
4181   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4182 }
4183 
4184 
4185 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)4186 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4187                           Expr *Fn) {
4188   if (Proto && Proto->isVariadic()) {
4189     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4190       return VariadicConstructor;
4191     else if (Fn && Fn->getType()->isBlockPointerType())
4192       return VariadicBlock;
4193     else if (FDecl) {
4194       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4195         if (Method->isInstance())
4196           return VariadicMethod;
4197     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4198       return VariadicMethod;
4199     return VariadicFunction;
4200   }
4201   return VariadicDoesNotApply;
4202 }
4203 
4204 namespace {
4205 class FunctionCallCCC : public FunctionCallFilterCCC {
4206 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)4207   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4208                   unsigned NumArgs, MemberExpr *ME)
4209       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4210         FunctionName(FuncName) {}
4211 
ValidateCandidate(const TypoCorrection & candidate)4212   bool ValidateCandidate(const TypoCorrection &candidate) override {
4213     if (!candidate.getCorrectionSpecifier() ||
4214         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4215       return false;
4216     }
4217 
4218     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4219   }
4220 
4221 private:
4222   const IdentifierInfo *const FunctionName;
4223 };
4224 }
4225 
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)4226 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4227                                                FunctionDecl *FDecl,
4228                                                ArrayRef<Expr *> Args) {
4229   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4230   DeclarationName FuncName = FDecl->getDeclName();
4231   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4232 
4233   if (TypoCorrection Corrected = S.CorrectTypo(
4234           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4235           S.getScopeForContext(S.CurContext), nullptr,
4236           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4237                                              Args.size(), ME),
4238           Sema::CTK_ErrorRecovery)) {
4239     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4240       if (Corrected.isOverloaded()) {
4241         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4242         OverloadCandidateSet::iterator Best;
4243         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4244                                            CDEnd = Corrected.end();
4245              CD != CDEnd; ++CD) {
4246           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4247             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4248                                    OCS);
4249         }
4250         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4251         case OR_Success:
4252           ND = Best->Function;
4253           Corrected.setCorrectionDecl(ND);
4254           break;
4255         default:
4256           break;
4257         }
4258       }
4259       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4260         return Corrected;
4261       }
4262     }
4263   }
4264   return TypoCorrection();
4265 }
4266 
4267 /// ConvertArgumentsForCall - Converts the arguments specified in
4268 /// Args/NumArgs to the parameter types of the function FDecl with
4269 /// function prototype Proto. Call is the call expression itself, and
4270 /// Fn is the function expression. For a C++ member function, this
4271 /// routine does not attempt to convert the object argument. Returns
4272 /// true if the call is ill-formed.
4273 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)4274 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4275                               FunctionDecl *FDecl,
4276                               const FunctionProtoType *Proto,
4277                               ArrayRef<Expr *> Args,
4278                               SourceLocation RParenLoc,
4279                               bool IsExecConfig) {
4280   // Bail out early if calling a builtin with custom typechecking.
4281   // We don't need to do this in the
4282   if (FDecl)
4283     if (unsigned ID = FDecl->getBuiltinID())
4284       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4285         return false;
4286 
4287   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4288   // assignment, to the types of the corresponding parameter, ...
4289   unsigned NumParams = Proto->getNumParams();
4290   bool Invalid = false;
4291   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4292   unsigned FnKind = Fn->getType()->isBlockPointerType()
4293                        ? 1 /* block */
4294                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4295                                        : 0 /* function */);
4296 
4297   // If too few arguments are available (and we don't have default
4298   // arguments for the remaining parameters), don't make the call.
4299   if (Args.size() < NumParams) {
4300     if (Args.size() < MinArgs) {
4301       TypoCorrection TC;
4302       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4303         unsigned diag_id =
4304             MinArgs == NumParams && !Proto->isVariadic()
4305                 ? diag::err_typecheck_call_too_few_args_suggest
4306                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4307         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4308                                         << static_cast<unsigned>(Args.size())
4309                                         << TC.getCorrectionRange());
4310       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4311         Diag(RParenLoc,
4312              MinArgs == NumParams && !Proto->isVariadic()
4313                  ? diag::err_typecheck_call_too_few_args_one
4314                  : diag::err_typecheck_call_too_few_args_at_least_one)
4315             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4316       else
4317         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4318                             ? diag::err_typecheck_call_too_few_args
4319                             : diag::err_typecheck_call_too_few_args_at_least)
4320             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4321             << Fn->getSourceRange();
4322 
4323       // Emit the location of the prototype.
4324       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4325         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4326           << FDecl;
4327 
4328       return true;
4329     }
4330     Call->setNumArgs(Context, NumParams);
4331   }
4332 
4333   // If too many are passed and not variadic, error on the extras and drop
4334   // them.
4335   if (Args.size() > NumParams) {
4336     if (!Proto->isVariadic()) {
4337       TypoCorrection TC;
4338       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4339         unsigned diag_id =
4340             MinArgs == NumParams && !Proto->isVariadic()
4341                 ? diag::err_typecheck_call_too_many_args_suggest
4342                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4343         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4344                                         << static_cast<unsigned>(Args.size())
4345                                         << TC.getCorrectionRange());
4346       } else if (NumParams == 1 && FDecl &&
4347                  FDecl->getParamDecl(0)->getDeclName())
4348         Diag(Args[NumParams]->getLocStart(),
4349              MinArgs == NumParams
4350                  ? diag::err_typecheck_call_too_many_args_one
4351                  : diag::err_typecheck_call_too_many_args_at_most_one)
4352             << FnKind << FDecl->getParamDecl(0)
4353             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4354             << SourceRange(Args[NumParams]->getLocStart(),
4355                            Args.back()->getLocEnd());
4356       else
4357         Diag(Args[NumParams]->getLocStart(),
4358              MinArgs == NumParams
4359                  ? diag::err_typecheck_call_too_many_args
4360                  : diag::err_typecheck_call_too_many_args_at_most)
4361             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4362             << Fn->getSourceRange()
4363             << SourceRange(Args[NumParams]->getLocStart(),
4364                            Args.back()->getLocEnd());
4365 
4366       // Emit the location of the prototype.
4367       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4368         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4369           << FDecl;
4370 
4371       // This deletes the extra arguments.
4372       Call->setNumArgs(Context, NumParams);
4373       return true;
4374     }
4375   }
4376   SmallVector<Expr *, 8> AllArgs;
4377   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4378 
4379   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4380                                    Proto, 0, Args, AllArgs, CallType);
4381   if (Invalid)
4382     return true;
4383   unsigned TotalNumArgs = AllArgs.size();
4384   for (unsigned i = 0; i < TotalNumArgs; ++i)
4385     Call->setArg(i, AllArgs[i]);
4386 
4387   return false;
4388 }
4389 
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)4390 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4391                                   const FunctionProtoType *Proto,
4392                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4393                                   SmallVectorImpl<Expr *> &AllArgs,
4394                                   VariadicCallType CallType, bool AllowExplicit,
4395                                   bool IsListInitialization) {
4396   unsigned NumParams = Proto->getNumParams();
4397   bool Invalid = false;
4398   unsigned ArgIx = 0;
4399   // Continue to check argument types (even if we have too few/many args).
4400   for (unsigned i = FirstParam; i < NumParams; i++) {
4401     QualType ProtoArgType = Proto->getParamType(i);
4402 
4403     Expr *Arg;
4404     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4405     if (ArgIx < Args.size()) {
4406       Arg = Args[ArgIx++];
4407 
4408       if (RequireCompleteType(Arg->getLocStart(),
4409                               ProtoArgType,
4410                               diag::err_call_incomplete_argument, Arg))
4411         return true;
4412 
4413       // Strip the unbridged-cast placeholder expression off, if applicable.
4414       bool CFAudited = false;
4415       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4416           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4417           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4418         Arg = stripARCUnbridgedCast(Arg);
4419       else if (getLangOpts().ObjCAutoRefCount &&
4420                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4421                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4422         CFAudited = true;
4423 
4424       InitializedEntity Entity =
4425           Param ? InitializedEntity::InitializeParameter(Context, Param,
4426                                                          ProtoArgType)
4427                 : InitializedEntity::InitializeParameter(
4428                       Context, ProtoArgType, Proto->isParamConsumed(i));
4429 
4430       // Remember that parameter belongs to a CF audited API.
4431       if (CFAudited)
4432         Entity.setParameterCFAudited();
4433 
4434       ExprResult ArgE = PerformCopyInitialization(
4435           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4436       if (ArgE.isInvalid())
4437         return true;
4438 
4439       Arg = ArgE.getAs<Expr>();
4440     } else {
4441       assert(Param && "can't use default arguments without a known callee");
4442 
4443       ExprResult ArgExpr =
4444         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4445       if (ArgExpr.isInvalid())
4446         return true;
4447 
4448       Arg = ArgExpr.getAs<Expr>();
4449     }
4450 
4451     // Check for array bounds violations for each argument to the call. This
4452     // check only triggers warnings when the argument isn't a more complex Expr
4453     // with its own checking, such as a BinaryOperator.
4454     CheckArrayAccess(Arg);
4455 
4456     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4457     CheckStaticArrayArgument(CallLoc, Param, Arg);
4458 
4459     AllArgs.push_back(Arg);
4460   }
4461 
4462   // If this is a variadic call, handle args passed through "...".
4463   if (CallType != VariadicDoesNotApply) {
4464     // Assume that extern "C" functions with variadic arguments that
4465     // return __unknown_anytype aren't *really* variadic.
4466     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4467         FDecl->isExternC()) {
4468       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4469         QualType paramType; // ignored
4470         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4471         Invalid |= arg.isInvalid();
4472         AllArgs.push_back(arg.get());
4473       }
4474 
4475     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4476     } else {
4477       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4478         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4479                                                           FDecl);
4480         Invalid |= Arg.isInvalid();
4481         AllArgs.push_back(Arg.get());
4482       }
4483     }
4484 
4485     // Check for array bounds violations.
4486     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4487       CheckArrayAccess(Args[i]);
4488   }
4489   return Invalid;
4490 }
4491 
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)4492 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4493   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4494   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4495     TL = DTL.getOriginalLoc();
4496   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4497     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4498       << ATL.getLocalSourceRange();
4499 }
4500 
4501 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4502 /// array parameter, check that it is non-null, and that if it is formed by
4503 /// array-to-pointer decay, the underlying array is sufficiently large.
4504 ///
4505 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4506 /// array type derivation, then for each call to the function, the value of the
4507 /// corresponding actual argument shall provide access to the first element of
4508 /// an array with at least as many elements as specified by the size expression.
4509 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)4510 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4511                                ParmVarDecl *Param,
4512                                const Expr *ArgExpr) {
4513   // Static array parameters are not supported in C++.
4514   if (!Param || getLangOpts().CPlusPlus)
4515     return;
4516 
4517   QualType OrigTy = Param->getOriginalType();
4518 
4519   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4520   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4521     return;
4522 
4523   if (ArgExpr->isNullPointerConstant(Context,
4524                                      Expr::NPC_NeverValueDependent)) {
4525     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4526     DiagnoseCalleeStaticArrayParam(*this, Param);
4527     return;
4528   }
4529 
4530   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4531   if (!CAT)
4532     return;
4533 
4534   const ConstantArrayType *ArgCAT =
4535     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4536   if (!ArgCAT)
4537     return;
4538 
4539   if (ArgCAT->getSize().ult(CAT->getSize())) {
4540     Diag(CallLoc, diag::warn_static_array_too_small)
4541       << ArgExpr->getSourceRange()
4542       << (unsigned) ArgCAT->getSize().getZExtValue()
4543       << (unsigned) CAT->getSize().getZExtValue();
4544     DiagnoseCalleeStaticArrayParam(*this, Param);
4545   }
4546 }
4547 
4548 /// Given a function expression of unknown-any type, try to rebuild it
4549 /// to have a function type.
4550 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4551 
4552 /// Is the given type a placeholder that we need to lower out
4553 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)4554 static bool isPlaceholderToRemoveAsArg(QualType type) {
4555   // Placeholders are never sugared.
4556   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4557   if (!placeholder) return false;
4558 
4559   switch (placeholder->getKind()) {
4560   // Ignore all the non-placeholder types.
4561 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4562 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4563 #include "clang/AST/BuiltinTypes.def"
4564     return false;
4565 
4566   // We cannot lower out overload sets; they might validly be resolved
4567   // by the call machinery.
4568   case BuiltinType::Overload:
4569     return false;
4570 
4571   // Unbridged casts in ARC can be handled in some call positions and
4572   // should be left in place.
4573   case BuiltinType::ARCUnbridgedCast:
4574     return false;
4575 
4576   // Pseudo-objects should be converted as soon as possible.
4577   case BuiltinType::PseudoObject:
4578     return true;
4579 
4580   // The debugger mode could theoretically but currently does not try
4581   // to resolve unknown-typed arguments based on known parameter types.
4582   case BuiltinType::UnknownAny:
4583     return true;
4584 
4585   // These are always invalid as call arguments and should be reported.
4586   case BuiltinType::BoundMember:
4587   case BuiltinType::BuiltinFn:
4588     return true;
4589   }
4590   llvm_unreachable("bad builtin type kind");
4591 }
4592 
4593 /// Check an argument list for placeholders that we won't try to
4594 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)4595 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4596   // Apply this processing to all the arguments at once instead of
4597   // dying at the first failure.
4598   bool hasInvalid = false;
4599   for (size_t i = 0, e = args.size(); i != e; i++) {
4600     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4601       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4602       if (result.isInvalid()) hasInvalid = true;
4603       else args[i] = result.get();
4604     } else if (hasInvalid) {
4605       (void)S.CorrectDelayedTyposInExpr(args[i]);
4606     }
4607   }
4608   return hasInvalid;
4609 }
4610 
4611 /// If a builtin function has a pointer argument with no explicit address
4612 /// space, than it should be able to accept a pointer to any address
4613 /// space as input.  In order to do this, we need to replace the
4614 /// standard builtin declaration with one that uses the same address space
4615 /// as the call.
4616 ///
4617 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4618 ///                  it does not contain any pointer arguments without
4619 ///                  an address space qualifer.  Otherwise the rewritten
4620 ///                  FunctionDecl is returned.
4621 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,const FunctionDecl * FDecl,MultiExprArg ArgExprs)4622 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4623                                                 const FunctionDecl *FDecl,
4624                                                 MultiExprArg ArgExprs) {
4625 
4626   QualType DeclType = FDecl->getType();
4627   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4628 
4629   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4630       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4631     return nullptr;
4632 
4633   bool NeedsNewDecl = false;
4634   unsigned i = 0;
4635   SmallVector<QualType, 8> OverloadParams;
4636 
4637   for (QualType ParamType : FT->param_types()) {
4638 
4639     // Convert array arguments to pointer to simplify type lookup.
4640     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4641     QualType ArgType = Arg->getType();
4642     if (!ParamType->isPointerType() ||
4643         ParamType.getQualifiers().hasAddressSpace() ||
4644         !ArgType->isPointerType() ||
4645         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4646       OverloadParams.push_back(ParamType);
4647       continue;
4648     }
4649 
4650     NeedsNewDecl = true;
4651     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4652 
4653     QualType PointeeType = ParamType->getPointeeType();
4654     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4655     OverloadParams.push_back(Context.getPointerType(PointeeType));
4656   }
4657 
4658   if (!NeedsNewDecl)
4659     return nullptr;
4660 
4661   FunctionProtoType::ExtProtoInfo EPI;
4662   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4663                                                 OverloadParams, EPI);
4664   DeclContext *Parent = Context.getTranslationUnitDecl();
4665   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4666                                                     FDecl->getLocation(),
4667                                                     FDecl->getLocation(),
4668                                                     FDecl->getIdentifier(),
4669                                                     OverloadTy,
4670                                                     /*TInfo=*/nullptr,
4671                                                     SC_Extern, false,
4672                                                     /*hasPrototype=*/true);
4673   SmallVector<ParmVarDecl*, 16> Params;
4674   FT = cast<FunctionProtoType>(OverloadTy);
4675   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4676     QualType ParamType = FT->getParamType(i);
4677     ParmVarDecl *Parm =
4678         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4679                                 SourceLocation(), nullptr, ParamType,
4680                                 /*TInfo=*/nullptr, SC_None, nullptr);
4681     Parm->setScopeInfo(0, i);
4682     Params.push_back(Parm);
4683   }
4684   OverloadDecl->setParams(Params);
4685   return OverloadDecl;
4686 }
4687 
4688 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4689 /// This provides the location of the left/right parens and a list of comma
4690 /// locations.
4691 ExprResult
ActOnCallExpr(Scope * S,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)4692 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4693                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4694                     Expr *ExecConfig, bool IsExecConfig) {
4695   // Since this might be a postfix expression, get rid of ParenListExprs.
4696   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4697   if (Result.isInvalid()) return ExprError();
4698   Fn = Result.get();
4699 
4700   if (checkArgsForPlaceholders(*this, ArgExprs))
4701     return ExprError();
4702 
4703   if (getLangOpts().CPlusPlus) {
4704     // If this is a pseudo-destructor expression, build the call immediately.
4705     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4706       if (!ArgExprs.empty()) {
4707         // Pseudo-destructor calls should not have any arguments.
4708         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4709           << FixItHint::CreateRemoval(
4710                                     SourceRange(ArgExprs[0]->getLocStart(),
4711                                                 ArgExprs.back()->getLocEnd()));
4712       }
4713 
4714       return new (Context)
4715           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4716     }
4717     if (Fn->getType() == Context.PseudoObjectTy) {
4718       ExprResult result = CheckPlaceholderExpr(Fn);
4719       if (result.isInvalid()) return ExprError();
4720       Fn = result.get();
4721     }
4722 
4723     // Determine whether this is a dependent call inside a C++ template,
4724     // in which case we won't do any semantic analysis now.
4725     // FIXME: Will need to cache the results of name lookup (including ADL) in
4726     // Fn.
4727     bool Dependent = false;
4728     if (Fn->isTypeDependent())
4729       Dependent = true;
4730     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4731       Dependent = true;
4732 
4733     if (Dependent) {
4734       if (ExecConfig) {
4735         return new (Context) CUDAKernelCallExpr(
4736             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4737             Context.DependentTy, VK_RValue, RParenLoc);
4738       } else {
4739         return new (Context) CallExpr(
4740             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4741       }
4742     }
4743 
4744     // Determine whether this is a call to an object (C++ [over.call.object]).
4745     if (Fn->getType()->isRecordType())
4746       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4747                                           RParenLoc);
4748 
4749     if (Fn->getType() == Context.UnknownAnyTy) {
4750       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4751       if (result.isInvalid()) return ExprError();
4752       Fn = result.get();
4753     }
4754 
4755     if (Fn->getType() == Context.BoundMemberTy) {
4756       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4757     }
4758   }
4759 
4760   // Check for overloaded calls.  This can happen even in C due to extensions.
4761   if (Fn->getType() == Context.OverloadTy) {
4762     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4763 
4764     // We aren't supposed to apply this logic for if there's an '&' involved.
4765     if (!find.HasFormOfMemberPointer) {
4766       OverloadExpr *ovl = find.Expression;
4767       if (isa<UnresolvedLookupExpr>(ovl)) {
4768         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4769         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4770                                        RParenLoc, ExecConfig);
4771       } else {
4772         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4773                                          RParenLoc);
4774       }
4775     }
4776   }
4777 
4778   // If we're directly calling a function, get the appropriate declaration.
4779   if (Fn->getType() == Context.UnknownAnyTy) {
4780     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4781     if (result.isInvalid()) return ExprError();
4782     Fn = result.get();
4783   }
4784 
4785   Expr *NakedFn = Fn->IgnoreParens();
4786 
4787   NamedDecl *NDecl = nullptr;
4788   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4789     if (UnOp->getOpcode() == UO_AddrOf)
4790       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4791 
4792   if (isa<DeclRefExpr>(NakedFn)) {
4793     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4794 
4795     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4796     if (FDecl && FDecl->getBuiltinID()) {
4797       // Rewrite the function decl for this builtin by replacing paramaters
4798       // with no explicit address space with the address space of the arguments
4799       // in ArgExprs.
4800       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4801         NDecl = FDecl;
4802         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4803                            SourceLocation(), FDecl, false,
4804                            SourceLocation(), FDecl->getType(),
4805                            Fn->getValueKind(), FDecl);
4806       }
4807     }
4808   } else if (isa<MemberExpr>(NakedFn))
4809     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4810 
4811   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4812     if (FD->hasAttr<EnableIfAttr>()) {
4813       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4814         Diag(Fn->getLocStart(),
4815              isa<CXXMethodDecl>(FD) ?
4816                  diag::err_ovl_no_viable_member_function_in_call :
4817                  diag::err_ovl_no_viable_function_in_call)
4818           << FD << FD->getSourceRange();
4819         Diag(FD->getLocation(),
4820              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4821             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4822       }
4823     }
4824   }
4825 
4826   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4827                                ExecConfig, IsExecConfig);
4828 }
4829 
4830 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4831 ///
4832 /// __builtin_astype( value, dst type )
4833 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4834 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4835                                  SourceLocation BuiltinLoc,
4836                                  SourceLocation RParenLoc) {
4837   ExprValueKind VK = VK_RValue;
4838   ExprObjectKind OK = OK_Ordinary;
4839   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4840   QualType SrcTy = E->getType();
4841   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4842     return ExprError(Diag(BuiltinLoc,
4843                           diag::err_invalid_astype_of_different_size)
4844                      << DstTy
4845                      << SrcTy
4846                      << E->getSourceRange());
4847   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4848 }
4849 
4850 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4851 /// provided arguments.
4852 ///
4853 /// __builtin_convertvector( value, dst type )
4854 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4855 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4856                                         SourceLocation BuiltinLoc,
4857                                         SourceLocation RParenLoc) {
4858   TypeSourceInfo *TInfo;
4859   GetTypeFromParser(ParsedDestTy, &TInfo);
4860   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4861 }
4862 
4863 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4864 /// i.e. an expression not of \p OverloadTy.  The expression should
4865 /// unary-convert to an expression of function-pointer or
4866 /// block-pointer type.
4867 ///
4868 /// \param NDecl the declaration being called, if available
4869 ExprResult
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig)4870 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4871                             SourceLocation LParenLoc,
4872                             ArrayRef<Expr *> Args,
4873                             SourceLocation RParenLoc,
4874                             Expr *Config, bool IsExecConfig) {
4875   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4876   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4877 
4878   // Promote the function operand.
4879   // We special-case function promotion here because we only allow promoting
4880   // builtin functions to function pointers in the callee of a call.
4881   ExprResult Result;
4882   if (BuiltinID &&
4883       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4884     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4885                                CK_BuiltinFnToFnPtr).get();
4886   } else {
4887     Result = CallExprUnaryConversions(Fn);
4888   }
4889   if (Result.isInvalid())
4890     return ExprError();
4891   Fn = Result.get();
4892 
4893   // Make the call expr early, before semantic checks.  This guarantees cleanup
4894   // of arguments and function on error.
4895   CallExpr *TheCall;
4896   if (Config)
4897     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4898                                                cast<CallExpr>(Config), Args,
4899                                                Context.BoolTy, VK_RValue,
4900                                                RParenLoc);
4901   else
4902     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4903                                      VK_RValue, RParenLoc);
4904 
4905   // Bail out early if calling a builtin with custom typechecking.
4906   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4907     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4908 
4909  retry:
4910   const FunctionType *FuncT;
4911   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4912     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4913     // have type pointer to function".
4914     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4915     if (!FuncT)
4916       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4917                          << Fn->getType() << Fn->getSourceRange());
4918   } else if (const BlockPointerType *BPT =
4919                Fn->getType()->getAs<BlockPointerType>()) {
4920     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4921   } else {
4922     // Handle calls to expressions of unknown-any type.
4923     if (Fn->getType() == Context.UnknownAnyTy) {
4924       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4925       if (rewrite.isInvalid()) return ExprError();
4926       Fn = rewrite.get();
4927       TheCall->setCallee(Fn);
4928       goto retry;
4929     }
4930 
4931     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4932       << Fn->getType() << Fn->getSourceRange());
4933   }
4934 
4935   if (getLangOpts().CUDA) {
4936     if (Config) {
4937       // CUDA: Kernel calls must be to global functions
4938       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4939         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4940             << FDecl->getName() << Fn->getSourceRange());
4941 
4942       // CUDA: Kernel function must have 'void' return type
4943       if (!FuncT->getReturnType()->isVoidType())
4944         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4945             << Fn->getType() << Fn->getSourceRange());
4946     } else {
4947       // CUDA: Calls to global functions must be configured
4948       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4949         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4950             << FDecl->getName() << Fn->getSourceRange());
4951     }
4952   }
4953 
4954   // Check for a valid return type
4955   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4956                           FDecl))
4957     return ExprError();
4958 
4959   // We know the result type of the call, set it.
4960   TheCall->setType(FuncT->getCallResultType(Context));
4961   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4962 
4963   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4964   if (Proto) {
4965     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4966                                 IsExecConfig))
4967       return ExprError();
4968   } else {
4969     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4970 
4971     if (FDecl) {
4972       // Check if we have too few/too many template arguments, based
4973       // on our knowledge of the function definition.
4974       const FunctionDecl *Def = nullptr;
4975       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4976         Proto = Def->getType()->getAs<FunctionProtoType>();
4977        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4978           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4979           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4980       }
4981 
4982       // If the function we're calling isn't a function prototype, but we have
4983       // a function prototype from a prior declaratiom, use that prototype.
4984       if (!FDecl->hasPrototype())
4985         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4986     }
4987 
4988     // Promote the arguments (C99 6.5.2.2p6).
4989     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4990       Expr *Arg = Args[i];
4991 
4992       if (Proto && i < Proto->getNumParams()) {
4993         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4994             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4995         ExprResult ArgE =
4996             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4997         if (ArgE.isInvalid())
4998           return true;
4999 
5000         Arg = ArgE.getAs<Expr>();
5001 
5002       } else {
5003         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5004 
5005         if (ArgE.isInvalid())
5006           return true;
5007 
5008         Arg = ArgE.getAs<Expr>();
5009       }
5010 
5011       if (RequireCompleteType(Arg->getLocStart(),
5012                               Arg->getType(),
5013                               diag::err_call_incomplete_argument, Arg))
5014         return ExprError();
5015 
5016       TheCall->setArg(i, Arg);
5017     }
5018   }
5019 
5020   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5021     if (!Method->isStatic())
5022       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5023         << Fn->getSourceRange());
5024 
5025   // Check for sentinels
5026   if (NDecl)
5027     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5028 
5029   // Do special checking on direct calls to functions.
5030   if (FDecl) {
5031     if (CheckFunctionCall(FDecl, TheCall, Proto))
5032       return ExprError();
5033 
5034     if (BuiltinID)
5035       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5036   } else if (NDecl) {
5037     if (CheckPointerCall(NDecl, TheCall, Proto))
5038       return ExprError();
5039   } else {
5040     if (CheckOtherCall(TheCall, Proto))
5041       return ExprError();
5042   }
5043 
5044   return MaybeBindToTemporary(TheCall);
5045 }
5046 
5047 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)5048 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5049                            SourceLocation RParenLoc, Expr *InitExpr) {
5050   assert(Ty && "ActOnCompoundLiteral(): missing type");
5051   // FIXME: put back this assert when initializers are worked out.
5052   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
5053 
5054   TypeSourceInfo *TInfo;
5055   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5056   if (!TInfo)
5057     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5058 
5059   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5060 }
5061 
5062 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)5063 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5064                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5065   QualType literalType = TInfo->getType();
5066 
5067   if (literalType->isArrayType()) {
5068     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5069           diag::err_illegal_decl_array_incomplete_type,
5070           SourceRange(LParenLoc,
5071                       LiteralExpr->getSourceRange().getEnd())))
5072       return ExprError();
5073     if (literalType->isVariableArrayType())
5074       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5075         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5076   } else if (!literalType->isDependentType() &&
5077              RequireCompleteType(LParenLoc, literalType,
5078                diag::err_typecheck_decl_incomplete_type,
5079                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5080     return ExprError();
5081 
5082   InitializedEntity Entity
5083     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5084   InitializationKind Kind
5085     = InitializationKind::CreateCStyleCast(LParenLoc,
5086                                            SourceRange(LParenLoc, RParenLoc),
5087                                            /*InitList=*/true);
5088   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5089   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5090                                       &literalType);
5091   if (Result.isInvalid())
5092     return ExprError();
5093   LiteralExpr = Result.get();
5094 
5095   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5096   if (isFileScope &&
5097       !LiteralExpr->isTypeDependent() &&
5098       !LiteralExpr->isValueDependent() &&
5099       !literalType->isDependentType()) { // 6.5.2.5p3
5100     if (CheckForConstantInitializer(LiteralExpr, literalType))
5101       return ExprError();
5102   }
5103 
5104   // In C, compound literals are l-values for some reason.
5105   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5106 
5107   return MaybeBindToTemporary(
5108            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5109                                              VK, LiteralExpr, isFileScope));
5110 }
5111 
5112 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)5113 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5114                     SourceLocation RBraceLoc) {
5115   // Immediately handle non-overload placeholders.  Overloads can be
5116   // resolved contextually, but everything else here can't.
5117   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5118     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5119       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5120 
5121       // Ignore failures; dropping the entire initializer list because
5122       // of one failure would be terrible for indexing/etc.
5123       if (result.isInvalid()) continue;
5124 
5125       InitArgList[I] = result.get();
5126     }
5127   }
5128 
5129   // Semantic analysis for initializers is done by ActOnDeclarator() and
5130   // CheckInitializer() - it requires knowledge of the object being intialized.
5131 
5132   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5133                                                RBraceLoc);
5134   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5135   return E;
5136 }
5137 
5138 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(Sema & S,ExprResult & E)5139 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
5140   assert(E.get()->getType()->isBlockPointerType());
5141   assert(E.get()->isRValue());
5142 
5143   // Only do this in an r-value context.
5144   if (!S.getLangOpts().ObjCAutoRefCount) return;
5145 
5146   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
5147                                CK_ARCExtendBlockObject, E.get(),
5148                                /*base path*/ nullptr, VK_RValue);
5149   S.ExprNeedsCleanups = true;
5150 }
5151 
5152 /// Prepare a conversion of the given expression to an ObjC object
5153 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)5154 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5155   QualType type = E.get()->getType();
5156   if (type->isObjCObjectPointerType()) {
5157     return CK_BitCast;
5158   } else if (type->isBlockPointerType()) {
5159     maybeExtendBlockObject(*this, E);
5160     return CK_BlockPointerToObjCPointerCast;
5161   } else {
5162     assert(type->isPointerType());
5163     return CK_CPointerToObjCPointerCast;
5164   }
5165 }
5166 
5167 /// Prepares for a scalar cast, performing all the necessary stages
5168 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)5169 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5170   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5171   // Also, callers should have filtered out the invalid cases with
5172   // pointers.  Everything else should be possible.
5173 
5174   QualType SrcTy = Src.get()->getType();
5175   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5176     return CK_NoOp;
5177 
5178   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5179   case Type::STK_MemberPointer:
5180     llvm_unreachable("member pointer type in C");
5181 
5182   case Type::STK_CPointer:
5183   case Type::STK_BlockPointer:
5184   case Type::STK_ObjCObjectPointer:
5185     switch (DestTy->getScalarTypeKind()) {
5186     case Type::STK_CPointer: {
5187       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5188       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5189       if (SrcAS != DestAS)
5190         return CK_AddressSpaceConversion;
5191       return CK_BitCast;
5192     }
5193     case Type::STK_BlockPointer:
5194       return (SrcKind == Type::STK_BlockPointer
5195                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5196     case Type::STK_ObjCObjectPointer:
5197       if (SrcKind == Type::STK_ObjCObjectPointer)
5198         return CK_BitCast;
5199       if (SrcKind == Type::STK_CPointer)
5200         return CK_CPointerToObjCPointerCast;
5201       maybeExtendBlockObject(*this, Src);
5202       return CK_BlockPointerToObjCPointerCast;
5203     case Type::STK_Bool:
5204       return CK_PointerToBoolean;
5205     case Type::STK_Integral:
5206       return CK_PointerToIntegral;
5207     case Type::STK_Floating:
5208     case Type::STK_FloatingComplex:
5209     case Type::STK_IntegralComplex:
5210     case Type::STK_MemberPointer:
5211       llvm_unreachable("illegal cast from pointer");
5212     }
5213     llvm_unreachable("Should have returned before this");
5214 
5215   case Type::STK_Bool: // casting from bool is like casting from an integer
5216   case Type::STK_Integral:
5217     switch (DestTy->getScalarTypeKind()) {
5218     case Type::STK_CPointer:
5219     case Type::STK_ObjCObjectPointer:
5220     case Type::STK_BlockPointer:
5221       if (Src.get()->isNullPointerConstant(Context,
5222                                            Expr::NPC_ValueDependentIsNull))
5223         return CK_NullToPointer;
5224       return CK_IntegralToPointer;
5225     case Type::STK_Bool:
5226       return CK_IntegralToBoolean;
5227     case Type::STK_Integral:
5228       return CK_IntegralCast;
5229     case Type::STK_Floating:
5230       return CK_IntegralToFloating;
5231     case Type::STK_IntegralComplex:
5232       Src = ImpCastExprToType(Src.get(),
5233                               DestTy->castAs<ComplexType>()->getElementType(),
5234                               CK_IntegralCast);
5235       return CK_IntegralRealToComplex;
5236     case Type::STK_FloatingComplex:
5237       Src = ImpCastExprToType(Src.get(),
5238                               DestTy->castAs<ComplexType>()->getElementType(),
5239                               CK_IntegralToFloating);
5240       return CK_FloatingRealToComplex;
5241     case Type::STK_MemberPointer:
5242       llvm_unreachable("member pointer type in C");
5243     }
5244     llvm_unreachable("Should have returned before this");
5245 
5246   case Type::STK_Floating:
5247     switch (DestTy->getScalarTypeKind()) {
5248     case Type::STK_Floating:
5249       return CK_FloatingCast;
5250     case Type::STK_Bool:
5251       return CK_FloatingToBoolean;
5252     case Type::STK_Integral:
5253       return CK_FloatingToIntegral;
5254     case Type::STK_FloatingComplex:
5255       Src = ImpCastExprToType(Src.get(),
5256                               DestTy->castAs<ComplexType>()->getElementType(),
5257                               CK_FloatingCast);
5258       return CK_FloatingRealToComplex;
5259     case Type::STK_IntegralComplex:
5260       Src = ImpCastExprToType(Src.get(),
5261                               DestTy->castAs<ComplexType>()->getElementType(),
5262                               CK_FloatingToIntegral);
5263       return CK_IntegralRealToComplex;
5264     case Type::STK_CPointer:
5265     case Type::STK_ObjCObjectPointer:
5266     case Type::STK_BlockPointer:
5267       llvm_unreachable("valid float->pointer cast?");
5268     case Type::STK_MemberPointer:
5269       llvm_unreachable("member pointer type in C");
5270     }
5271     llvm_unreachable("Should have returned before this");
5272 
5273   case Type::STK_FloatingComplex:
5274     switch (DestTy->getScalarTypeKind()) {
5275     case Type::STK_FloatingComplex:
5276       return CK_FloatingComplexCast;
5277     case Type::STK_IntegralComplex:
5278       return CK_FloatingComplexToIntegralComplex;
5279     case Type::STK_Floating: {
5280       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5281       if (Context.hasSameType(ET, DestTy))
5282         return CK_FloatingComplexToReal;
5283       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5284       return CK_FloatingCast;
5285     }
5286     case Type::STK_Bool:
5287       return CK_FloatingComplexToBoolean;
5288     case Type::STK_Integral:
5289       Src = ImpCastExprToType(Src.get(),
5290                               SrcTy->castAs<ComplexType>()->getElementType(),
5291                               CK_FloatingComplexToReal);
5292       return CK_FloatingToIntegral;
5293     case Type::STK_CPointer:
5294     case Type::STK_ObjCObjectPointer:
5295     case Type::STK_BlockPointer:
5296       llvm_unreachable("valid complex float->pointer cast?");
5297     case Type::STK_MemberPointer:
5298       llvm_unreachable("member pointer type in C");
5299     }
5300     llvm_unreachable("Should have returned before this");
5301 
5302   case Type::STK_IntegralComplex:
5303     switch (DestTy->getScalarTypeKind()) {
5304     case Type::STK_FloatingComplex:
5305       return CK_IntegralComplexToFloatingComplex;
5306     case Type::STK_IntegralComplex:
5307       return CK_IntegralComplexCast;
5308     case Type::STK_Integral: {
5309       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5310       if (Context.hasSameType(ET, DestTy))
5311         return CK_IntegralComplexToReal;
5312       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5313       return CK_IntegralCast;
5314     }
5315     case Type::STK_Bool:
5316       return CK_IntegralComplexToBoolean;
5317     case Type::STK_Floating:
5318       Src = ImpCastExprToType(Src.get(),
5319                               SrcTy->castAs<ComplexType>()->getElementType(),
5320                               CK_IntegralComplexToReal);
5321       return CK_IntegralToFloating;
5322     case Type::STK_CPointer:
5323     case Type::STK_ObjCObjectPointer:
5324     case Type::STK_BlockPointer:
5325       llvm_unreachable("valid complex int->pointer cast?");
5326     case Type::STK_MemberPointer:
5327       llvm_unreachable("member pointer type in C");
5328     }
5329     llvm_unreachable("Should have returned before this");
5330   }
5331 
5332   llvm_unreachable("Unhandled scalar cast");
5333 }
5334 
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)5335 static bool breakDownVectorType(QualType type, uint64_t &len,
5336                                 QualType &eltType) {
5337   // Vectors are simple.
5338   if (const VectorType *vecType = type->getAs<VectorType>()) {
5339     len = vecType->getNumElements();
5340     eltType = vecType->getElementType();
5341     assert(eltType->isScalarType());
5342     return true;
5343   }
5344 
5345   // We allow lax conversion to and from non-vector types, but only if
5346   // they're real types (i.e. non-complex, non-pointer scalar types).
5347   if (!type->isRealType()) return false;
5348 
5349   len = 1;
5350   eltType = type;
5351   return true;
5352 }
5353 
VectorTypesMatch(Sema & S,QualType srcTy,QualType destTy)5354 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5355   uint64_t srcLen, destLen;
5356   QualType srcElt, destElt;
5357   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5358   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5359 
5360   // ASTContext::getTypeSize will return the size rounded up to a
5361   // power of 2, so instead of using that, we need to use the raw
5362   // element size multiplied by the element count.
5363   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5364   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5365 
5366   return (srcLen * srcEltSize == destLen * destEltSize);
5367 }
5368 
5369 /// Is this a legal conversion between two known vector types?
isLaxVectorConversion(QualType srcTy,QualType destTy)5370 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5371   assert(destTy->isVectorType() || srcTy->isVectorType());
5372 
5373   if (!Context.getLangOpts().LaxVectorConversions)
5374     return false;
5375   return VectorTypesMatch(*this, srcTy, destTy);
5376 }
5377 
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)5378 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5379                            CastKind &Kind) {
5380   assert(VectorTy->isVectorType() && "Not a vector type!");
5381 
5382   if (Ty->isVectorType() || Ty->isIntegerType()) {
5383     if (!VectorTypesMatch(*this, Ty, VectorTy))
5384       return Diag(R.getBegin(),
5385                   Ty->isVectorType() ?
5386                   diag::err_invalid_conversion_between_vectors :
5387                   diag::err_invalid_conversion_between_vector_and_integer)
5388         << VectorTy << Ty << R;
5389   } else
5390     return Diag(R.getBegin(),
5391                 diag::err_invalid_conversion_between_vector_and_scalar)
5392       << VectorTy << Ty << R;
5393 
5394   Kind = CK_BitCast;
5395   return false;
5396 }
5397 
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)5398 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5399                                     Expr *CastExpr, CastKind &Kind) {
5400   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5401 
5402   QualType SrcTy = CastExpr->getType();
5403 
5404   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5405   // an ExtVectorType.
5406   // In OpenCL, casts between vectors of different types are not allowed.
5407   // (See OpenCL 6.2).
5408   if (SrcTy->isVectorType()) {
5409     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5410         || (getLangOpts().OpenCL &&
5411             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5412       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5413         << DestTy << SrcTy << R;
5414       return ExprError();
5415     }
5416     Kind = CK_BitCast;
5417     return CastExpr;
5418   }
5419 
5420   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5421   // conversion will take place first from scalar to elt type, and then
5422   // splat from elt type to vector.
5423   if (SrcTy->isPointerType())
5424     return Diag(R.getBegin(),
5425                 diag::err_invalid_conversion_between_vector_and_scalar)
5426       << DestTy << SrcTy << R;
5427 
5428   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5429   ExprResult CastExprRes = CastExpr;
5430   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5431   if (CastExprRes.isInvalid())
5432     return ExprError();
5433   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5434 
5435   Kind = CK_VectorSplat;
5436   return CastExpr;
5437 }
5438 
5439 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)5440 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5441                     Declarator &D, ParsedType &Ty,
5442                     SourceLocation RParenLoc, Expr *CastExpr) {
5443   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5444          "ActOnCastExpr(): missing type or expr");
5445 
5446   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5447   if (D.isInvalidType())
5448     return ExprError();
5449 
5450   if (getLangOpts().CPlusPlus) {
5451     // Check that there are no default arguments (C++ only).
5452     CheckExtraCXXDefaultArguments(D);
5453   } else {
5454     // Make sure any TypoExprs have been dealt with.
5455     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5456     if (!Res.isUsable())
5457       return ExprError();
5458     CastExpr = Res.get();
5459   }
5460 
5461   checkUnusedDeclAttributes(D);
5462 
5463   QualType castType = castTInfo->getType();
5464   Ty = CreateParsedType(castType, castTInfo);
5465 
5466   bool isVectorLiteral = false;
5467 
5468   // Check for an altivec or OpenCL literal,
5469   // i.e. all the elements are integer constants.
5470   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5471   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5472   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5473        && castType->isVectorType() && (PE || PLE)) {
5474     if (PLE && PLE->getNumExprs() == 0) {
5475       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5476       return ExprError();
5477     }
5478     if (PE || PLE->getNumExprs() == 1) {
5479       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5480       if (!E->getType()->isVectorType())
5481         isVectorLiteral = true;
5482     }
5483     else
5484       isVectorLiteral = true;
5485   }
5486 
5487   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5488   // then handle it as such.
5489   if (isVectorLiteral)
5490     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5491 
5492   // If the Expr being casted is a ParenListExpr, handle it specially.
5493   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5494   // sequence of BinOp comma operators.
5495   if (isa<ParenListExpr>(CastExpr)) {
5496     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5497     if (Result.isInvalid()) return ExprError();
5498     CastExpr = Result.get();
5499   }
5500 
5501   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5502       !getSourceManager().isInSystemMacro(LParenLoc))
5503     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5504 
5505   CheckTollFreeBridgeCast(castType, CastExpr);
5506 
5507   CheckObjCBridgeRelatedCast(castType, CastExpr);
5508 
5509   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5510 }
5511 
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)5512 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5513                                     SourceLocation RParenLoc, Expr *E,
5514                                     TypeSourceInfo *TInfo) {
5515   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5516          "Expected paren or paren list expression");
5517 
5518   Expr **exprs;
5519   unsigned numExprs;
5520   Expr *subExpr;
5521   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5522   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5523     LiteralLParenLoc = PE->getLParenLoc();
5524     LiteralRParenLoc = PE->getRParenLoc();
5525     exprs = PE->getExprs();
5526     numExprs = PE->getNumExprs();
5527   } else { // isa<ParenExpr> by assertion at function entrance
5528     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5529     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5530     subExpr = cast<ParenExpr>(E)->getSubExpr();
5531     exprs = &subExpr;
5532     numExprs = 1;
5533   }
5534 
5535   QualType Ty = TInfo->getType();
5536   assert(Ty->isVectorType() && "Expected vector type");
5537 
5538   SmallVector<Expr *, 8> initExprs;
5539   const VectorType *VTy = Ty->getAs<VectorType>();
5540   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5541 
5542   // '(...)' form of vector initialization in AltiVec: the number of
5543   // initializers must be one or must match the size of the vector.
5544   // If a single value is specified in the initializer then it will be
5545   // replicated to all the components of the vector
5546   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5547     // The number of initializers must be one or must match the size of the
5548     // vector. If a single value is specified in the initializer then it will
5549     // be replicated to all the components of the vector
5550     if (numExprs == 1) {
5551       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5552       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5553       if (Literal.isInvalid())
5554         return ExprError();
5555       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5556                                   PrepareScalarCast(Literal, ElemTy));
5557       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5558     }
5559     else if (numExprs < numElems) {
5560       Diag(E->getExprLoc(),
5561            diag::err_incorrect_number_of_vector_initializers);
5562       return ExprError();
5563     }
5564     else
5565       initExprs.append(exprs, exprs + numExprs);
5566   }
5567   else {
5568     // For OpenCL, when the number of initializers is a single value,
5569     // it will be replicated to all components of the vector.
5570     if (getLangOpts().OpenCL &&
5571         VTy->getVectorKind() == VectorType::GenericVector &&
5572         numExprs == 1) {
5573         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5574         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5575         if (Literal.isInvalid())
5576           return ExprError();
5577         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5578                                     PrepareScalarCast(Literal, ElemTy));
5579         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5580     }
5581 
5582     initExprs.append(exprs, exprs + numExprs);
5583   }
5584   // FIXME: This means that pretty-printing the final AST will produce curly
5585   // braces instead of the original commas.
5586   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5587                                                    initExprs, LiteralRParenLoc);
5588   initE->setType(Ty);
5589   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5590 }
5591 
5592 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5593 /// the ParenListExpr into a sequence of comma binary operators.
5594 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)5595 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5596   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5597   if (!E)
5598     return OrigExpr;
5599 
5600   ExprResult Result(E->getExpr(0));
5601 
5602   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5603     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5604                         E->getExpr(i));
5605 
5606   if (Result.isInvalid()) return ExprError();
5607 
5608   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5609 }
5610 
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)5611 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5612                                     SourceLocation R,
5613                                     MultiExprArg Val) {
5614   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5615   return expr;
5616 }
5617 
5618 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5619 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5620 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)5621 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5622                                       SourceLocation QuestionLoc) {
5623   Expr *NullExpr = LHSExpr;
5624   Expr *NonPointerExpr = RHSExpr;
5625   Expr::NullPointerConstantKind NullKind =
5626       NullExpr->isNullPointerConstant(Context,
5627                                       Expr::NPC_ValueDependentIsNotNull);
5628 
5629   if (NullKind == Expr::NPCK_NotNull) {
5630     NullExpr = RHSExpr;
5631     NonPointerExpr = LHSExpr;
5632     NullKind =
5633         NullExpr->isNullPointerConstant(Context,
5634                                         Expr::NPC_ValueDependentIsNotNull);
5635   }
5636 
5637   if (NullKind == Expr::NPCK_NotNull)
5638     return false;
5639 
5640   if (NullKind == Expr::NPCK_ZeroExpression)
5641     return false;
5642 
5643   if (NullKind == Expr::NPCK_ZeroLiteral) {
5644     // In this case, check to make sure that we got here from a "NULL"
5645     // string in the source code.
5646     NullExpr = NullExpr->IgnoreParenImpCasts();
5647     SourceLocation loc = NullExpr->getExprLoc();
5648     if (!findMacroSpelling(loc, "NULL"))
5649       return false;
5650   }
5651 
5652   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5653   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5654       << NonPointerExpr->getType() << DiagType
5655       << NonPointerExpr->getSourceRange();
5656   return true;
5657 }
5658 
5659 /// \brief Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)5660 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
5661   QualType CondTy = Cond->getType();
5662 
5663   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5664   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5665     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5666       << CondTy << Cond->getSourceRange();
5667     return true;
5668   }
5669 
5670   // C99 6.5.15p2
5671   if (CondTy->isScalarType()) return false;
5672 
5673   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5674     << CondTy << Cond->getSourceRange();
5675   return true;
5676 }
5677 
5678 /// \brief Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)5679 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5680                                          ExprResult &RHS) {
5681     Expr *LHSExpr = LHS.get();
5682     Expr *RHSExpr = RHS.get();
5683 
5684     if (!LHSExpr->getType()->isVoidType())
5685       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5686         << RHSExpr->getSourceRange();
5687     if (!RHSExpr->getType()->isVoidType())
5688       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5689         << LHSExpr->getSourceRange();
5690     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5691     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5692     return S.Context.VoidTy;
5693 }
5694 
5695 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5696 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)5697 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5698                                         QualType PointerTy) {
5699   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5700       !NullExpr.get()->isNullPointerConstant(S.Context,
5701                                             Expr::NPC_ValueDependentIsNull))
5702     return true;
5703 
5704   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5705   return false;
5706 }
5707 
5708 /// \brief Checks compatibility between two pointers and return the resulting
5709 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5710 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5711                                                      ExprResult &RHS,
5712                                                      SourceLocation Loc) {
5713   QualType LHSTy = LHS.get()->getType();
5714   QualType RHSTy = RHS.get()->getType();
5715 
5716   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5717     // Two identical pointers types are always compatible.
5718     return LHSTy;
5719   }
5720 
5721   QualType lhptee, rhptee;
5722 
5723   // Get the pointee types.
5724   bool IsBlockPointer = false;
5725   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5726     lhptee = LHSBTy->getPointeeType();
5727     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5728     IsBlockPointer = true;
5729   } else {
5730     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5731     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5732   }
5733 
5734   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5735   // differently qualified versions of compatible types, the result type is
5736   // a pointer to an appropriately qualified version of the composite
5737   // type.
5738 
5739   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5740   // clause doesn't make sense for our extensions. E.g. address space 2 should
5741   // be incompatible with address space 3: they may live on different devices or
5742   // anything.
5743   Qualifiers lhQual = lhptee.getQualifiers();
5744   Qualifiers rhQual = rhptee.getQualifiers();
5745 
5746   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5747   lhQual.removeCVRQualifiers();
5748   rhQual.removeCVRQualifiers();
5749 
5750   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5751   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5752 
5753   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5754 
5755   if (CompositeTy.isNull()) {
5756     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5757       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5758       << RHS.get()->getSourceRange();
5759     // In this situation, we assume void* type. No especially good
5760     // reason, but this is what gcc does, and we do have to pick
5761     // to get a consistent AST.
5762     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5763     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5764     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5765     return incompatTy;
5766   }
5767 
5768   // The pointer types are compatible.
5769   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5770   if (IsBlockPointer)
5771     ResultTy = S.Context.getBlockPointerType(ResultTy);
5772   else
5773     ResultTy = S.Context.getPointerType(ResultTy);
5774 
5775   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5776   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5777   return ResultTy;
5778 }
5779 
5780 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5781 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5782 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
isObjCPtrBlockCompatible(Sema & S,ASTContext & C,QualType QT)5783 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5784   if (QT->isObjCIdType())
5785     return true;
5786 
5787   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5788   if (!OPT)
5789     return false;
5790 
5791   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5792     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5793       return false;
5794 
5795   ObjCProtocolDecl* PNSCopying =
5796     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5797   ObjCProtocolDecl* PNSObject =
5798     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5799 
5800   for (auto *Proto : OPT->quals()) {
5801     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5802         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5803       ;
5804     else
5805       return false;
5806   }
5807   return true;
5808 }
5809 
5810 /// \brief Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5811 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5812                                                           ExprResult &LHS,
5813                                                           ExprResult &RHS,
5814                                                           SourceLocation Loc) {
5815   QualType LHSTy = LHS.get()->getType();
5816   QualType RHSTy = RHS.get()->getType();
5817 
5818   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5819     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5820       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5821       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5822       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5823       return destType;
5824     }
5825     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5826       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5827       << RHS.get()->getSourceRange();
5828     return QualType();
5829   }
5830 
5831   // We have 2 block pointer types.
5832   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5833 }
5834 
5835 /// \brief Return the resulting type when the operands are both pointers.
5836 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5837 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5838                                             ExprResult &RHS,
5839                                             SourceLocation Loc) {
5840   // get the pointer types
5841   QualType LHSTy = LHS.get()->getType();
5842   QualType RHSTy = RHS.get()->getType();
5843 
5844   // get the "pointed to" types
5845   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5846   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5847 
5848   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5849   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5850     // Figure out necessary qualifiers (C99 6.5.15p6)
5851     QualType destPointee
5852       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5853     QualType destType = S.Context.getPointerType(destPointee);
5854     // Add qualifiers if necessary.
5855     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5856     // Promote to void*.
5857     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5858     return destType;
5859   }
5860   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5861     QualType destPointee
5862       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5863     QualType destType = S.Context.getPointerType(destPointee);
5864     // Add qualifiers if necessary.
5865     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5866     // Promote to void*.
5867     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5868     return destType;
5869   }
5870 
5871   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5872 }
5873 
5874 /// \brief Return false if the first expression is not an integer and the second
5875 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)5876 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5877                                         Expr* PointerExpr, SourceLocation Loc,
5878                                         bool IsIntFirstExpr) {
5879   if (!PointerExpr->getType()->isPointerType() ||
5880       !Int.get()->getType()->isIntegerType())
5881     return false;
5882 
5883   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5884   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5885 
5886   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5887     << Expr1->getType() << Expr2->getType()
5888     << Expr1->getSourceRange() << Expr2->getSourceRange();
5889   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5890                             CK_IntegralToPointer);
5891   return true;
5892 }
5893 
5894 /// \brief Simple conversion between integer and floating point types.
5895 ///
5896 /// Used when handling the OpenCL conditional operator where the
5897 /// condition is a vector while the other operands are scalar.
5898 ///
5899 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
5900 /// types are either integer or floating type. Between the two
5901 /// operands, the type with the higher rank is defined as the "result
5902 /// type". The other operand needs to be promoted to the same type. No
5903 /// other type promotion is allowed. We cannot use
5904 /// UsualArithmeticConversions() for this purpose, since it always
5905 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)5906 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
5907                                             ExprResult &RHS,
5908                                             SourceLocation QuestionLoc) {
5909   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
5910   if (LHS.isInvalid())
5911     return QualType();
5912   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
5913   if (RHS.isInvalid())
5914     return QualType();
5915 
5916   // For conversion purposes, we ignore any qualifiers.
5917   // For example, "const float" and "float" are equivalent.
5918   QualType LHSType =
5919     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5920   QualType RHSType =
5921     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5922 
5923   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
5924     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5925       << LHSType << LHS.get()->getSourceRange();
5926     return QualType();
5927   }
5928 
5929   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
5930     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5931       << RHSType << RHS.get()->getSourceRange();
5932     return QualType();
5933   }
5934 
5935   // If both types are identical, no conversion is needed.
5936   if (LHSType == RHSType)
5937     return LHSType;
5938 
5939   // Now handle "real" floating types (i.e. float, double, long double).
5940   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
5941     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
5942                                  /*IsCompAssign = */ false);
5943 
5944   // Finally, we have two differing integer types.
5945   return handleIntegerConversion<doIntegralCast, doIntegralCast>
5946   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
5947 }
5948 
5949 /// \brief Convert scalar operands to a vector that matches the
5950 ///        condition in length.
5951 ///
5952 /// Used when handling the OpenCL conditional operator where the
5953 /// condition is a vector while the other operands are scalar.
5954 ///
5955 /// We first compute the "result type" for the scalar operands
5956 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
5957 /// into a vector of that type where the length matches the condition
5958 /// vector type. s6.11.6 requires that the element types of the result
5959 /// and the condition must have the same number of bits.
5960 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)5961 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
5962                               QualType CondTy, SourceLocation QuestionLoc) {
5963   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
5964   if (ResTy.isNull()) return QualType();
5965 
5966   const VectorType *CV = CondTy->getAs<VectorType>();
5967   assert(CV);
5968 
5969   // Determine the vector result type
5970   unsigned NumElements = CV->getNumElements();
5971   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
5972 
5973   // Ensure that all types have the same number of bits
5974   if (S.Context.getTypeSize(CV->getElementType())
5975       != S.Context.getTypeSize(ResTy)) {
5976     // Since VectorTy is created internally, it does not pretty print
5977     // with an OpenCL name. Instead, we just print a description.
5978     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
5979     SmallString<64> Str;
5980     llvm::raw_svector_ostream OS(Str);
5981     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
5982     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5983       << CondTy << OS.str();
5984     return QualType();
5985   }
5986 
5987   // Convert operands to the vector result type
5988   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
5989   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
5990 
5991   return VectorTy;
5992 }
5993 
5994 /// \brief Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)5995 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
5996                                        SourceLocation QuestionLoc) {
5997   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
5998   // integral type.
5999   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6000   assert(CondTy);
6001   QualType EleTy = CondTy->getElementType();
6002   if (EleTy->isIntegerType()) return false;
6003 
6004   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6005     << Cond->getType() << Cond->getSourceRange();
6006   return true;
6007 }
6008 
6009 /// \brief Return false if the vector condition type and the vector
6010 ///        result type are compatible.
6011 ///
6012 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6013 /// number of elements, and their element types have the same number
6014 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)6015 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6016                               SourceLocation QuestionLoc) {
6017   const VectorType *CV = CondTy->getAs<VectorType>();
6018   const VectorType *RV = VecResTy->getAs<VectorType>();
6019   assert(CV && RV);
6020 
6021   if (CV->getNumElements() != RV->getNumElements()) {
6022     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6023       << CondTy << VecResTy;
6024     return true;
6025   }
6026 
6027   QualType CVE = CV->getElementType();
6028   QualType RVE = RV->getElementType();
6029 
6030   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6031     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6032       << CondTy << VecResTy;
6033     return true;
6034   }
6035 
6036   return false;
6037 }
6038 
6039 /// \brief Return the resulting type for the conditional operator in
6040 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6041 ///        s6.3.i) when the condition is a vector type.
6042 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6043 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6044                              ExprResult &LHS, ExprResult &RHS,
6045                              SourceLocation QuestionLoc) {
6046   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6047   if (Cond.isInvalid())
6048     return QualType();
6049   QualType CondTy = Cond.get()->getType();
6050 
6051   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6052     return QualType();
6053 
6054   // If either operand is a vector then find the vector type of the
6055   // result as specified in OpenCL v1.1 s6.3.i.
6056   if (LHS.get()->getType()->isVectorType() ||
6057       RHS.get()->getType()->isVectorType()) {
6058     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6059                                               /*isCompAssign*/false);
6060     if (VecResTy.isNull()) return QualType();
6061     // The result type must match the condition type as specified in
6062     // OpenCL v1.1 s6.11.6.
6063     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6064       return QualType();
6065     return VecResTy;
6066   }
6067 
6068   // Both operands are scalar.
6069   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6070 }
6071 
6072 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6073 /// In that case, LHS = cond.
6074 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)6075 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6076                                         ExprResult &RHS, ExprValueKind &VK,
6077                                         ExprObjectKind &OK,
6078                                         SourceLocation QuestionLoc) {
6079 
6080   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6081   if (!LHSResult.isUsable()) return QualType();
6082   LHS = LHSResult;
6083 
6084   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6085   if (!RHSResult.isUsable()) return QualType();
6086   RHS = RHSResult;
6087 
6088   // C++ is sufficiently different to merit its own checker.
6089   if (getLangOpts().CPlusPlus)
6090     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6091 
6092   VK = VK_RValue;
6093   OK = OK_Ordinary;
6094 
6095   // The OpenCL operator with a vector condition is sufficiently
6096   // different to merit its own checker.
6097   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6098     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6099 
6100   // First, check the condition.
6101   Cond = UsualUnaryConversions(Cond.get());
6102   if (Cond.isInvalid())
6103     return QualType();
6104   if (checkCondition(*this, Cond.get(), QuestionLoc))
6105     return QualType();
6106 
6107   // Now check the two expressions.
6108   if (LHS.get()->getType()->isVectorType() ||
6109       RHS.get()->getType()->isVectorType())
6110     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
6111 
6112   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6113   if (LHS.isInvalid() || RHS.isInvalid())
6114     return QualType();
6115 
6116   QualType LHSTy = LHS.get()->getType();
6117   QualType RHSTy = RHS.get()->getType();
6118 
6119   // If both operands have arithmetic type, do the usual arithmetic conversions
6120   // to find a common type: C99 6.5.15p3,5.
6121   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6122     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6123     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6124 
6125     return ResTy;
6126   }
6127 
6128   // If both operands are the same structure or union type, the result is that
6129   // type.
6130   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6131     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6132       if (LHSRT->getDecl() == RHSRT->getDecl())
6133         // "If both the operands have structure or union type, the result has
6134         // that type."  This implies that CV qualifiers are dropped.
6135         return LHSTy.getUnqualifiedType();
6136     // FIXME: Type of conditional expression must be complete in C mode.
6137   }
6138 
6139   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6140   // The following || allows only one side to be void (a GCC-ism).
6141   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6142     return checkConditionalVoidType(*this, LHS, RHS);
6143   }
6144 
6145   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6146   // the type of the other operand."
6147   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6148   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6149 
6150   // All objective-c pointer type analysis is done here.
6151   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6152                                                         QuestionLoc);
6153   if (LHS.isInvalid() || RHS.isInvalid())
6154     return QualType();
6155   if (!compositeType.isNull())
6156     return compositeType;
6157 
6158 
6159   // Handle block pointer types.
6160   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6161     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6162                                                      QuestionLoc);
6163 
6164   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6165   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6166     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6167                                                        QuestionLoc);
6168 
6169   // GCC compatibility: soften pointer/integer mismatch.  Note that
6170   // null pointers have been filtered out by this point.
6171   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6172       /*isIntFirstExpr=*/true))
6173     return RHSTy;
6174   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6175       /*isIntFirstExpr=*/false))
6176     return LHSTy;
6177 
6178   // Emit a better diagnostic if one of the expressions is a null pointer
6179   // constant and the other is not a pointer type. In this case, the user most
6180   // likely forgot to take the address of the other expression.
6181   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6182     return QualType();
6183 
6184   // Otherwise, the operands are not compatible.
6185   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6186     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6187     << RHS.get()->getSourceRange();
6188   return QualType();
6189 }
6190 
6191 /// FindCompositeObjCPointerType - Helper method to find composite type of
6192 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6193 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6194                                             SourceLocation QuestionLoc) {
6195   QualType LHSTy = LHS.get()->getType();
6196   QualType RHSTy = RHS.get()->getType();
6197 
6198   // Handle things like Class and struct objc_class*.  Here we case the result
6199   // to the pseudo-builtin, because that will be implicitly cast back to the
6200   // redefinition type if an attempt is made to access its fields.
6201   if (LHSTy->isObjCClassType() &&
6202       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6203     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6204     return LHSTy;
6205   }
6206   if (RHSTy->isObjCClassType() &&
6207       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6208     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6209     return RHSTy;
6210   }
6211   // And the same for struct objc_object* / id
6212   if (LHSTy->isObjCIdType() &&
6213       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6214     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6215     return LHSTy;
6216   }
6217   if (RHSTy->isObjCIdType() &&
6218       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6219     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6220     return RHSTy;
6221   }
6222   // And the same for struct objc_selector* / SEL
6223   if (Context.isObjCSelType(LHSTy) &&
6224       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6225     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6226     return LHSTy;
6227   }
6228   if (Context.isObjCSelType(RHSTy) &&
6229       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6230     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6231     return RHSTy;
6232   }
6233   // Check constraints for Objective-C object pointers types.
6234   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6235 
6236     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6237       // Two identical object pointer types are always compatible.
6238       return LHSTy;
6239     }
6240     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6241     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6242     QualType compositeType = LHSTy;
6243 
6244     // If both operands are interfaces and either operand can be
6245     // assigned to the other, use that type as the composite
6246     // type. This allows
6247     //   xxx ? (A*) a : (B*) b
6248     // where B is a subclass of A.
6249     //
6250     // Additionally, as for assignment, if either type is 'id'
6251     // allow silent coercion. Finally, if the types are
6252     // incompatible then make sure to use 'id' as the composite
6253     // type so the result is acceptable for sending messages to.
6254 
6255     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6256     // It could return the composite type.
6257     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6258       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6259     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6260       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6261     } else if ((LHSTy->isObjCQualifiedIdType() ||
6262                 RHSTy->isObjCQualifiedIdType()) &&
6263                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6264       // Need to handle "id<xx>" explicitly.
6265       // GCC allows qualified id and any Objective-C type to devolve to
6266       // id. Currently localizing to here until clear this should be
6267       // part of ObjCQualifiedIdTypesAreCompatible.
6268       compositeType = Context.getObjCIdType();
6269     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6270       compositeType = Context.getObjCIdType();
6271     } else if (!(compositeType =
6272                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6273       ;
6274     else {
6275       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6276       << LHSTy << RHSTy
6277       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6278       QualType incompatTy = Context.getObjCIdType();
6279       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6280       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6281       return incompatTy;
6282     }
6283     // The object pointer types are compatible.
6284     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6285     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6286     return compositeType;
6287   }
6288   // Check Objective-C object pointer types and 'void *'
6289   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6290     if (getLangOpts().ObjCAutoRefCount) {
6291       // ARC forbids the implicit conversion of object pointers to 'void *',
6292       // so these types are not compatible.
6293       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6294           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6295       LHS = RHS = true;
6296       return QualType();
6297     }
6298     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6299     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6300     QualType destPointee
6301     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6302     QualType destType = Context.getPointerType(destPointee);
6303     // Add qualifiers if necessary.
6304     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6305     // Promote to void*.
6306     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6307     return destType;
6308   }
6309   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6310     if (getLangOpts().ObjCAutoRefCount) {
6311       // ARC forbids the implicit conversion of object pointers to 'void *',
6312       // so these types are not compatible.
6313       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6314           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6315       LHS = RHS = true;
6316       return QualType();
6317     }
6318     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6319     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6320     QualType destPointee
6321     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6322     QualType destType = Context.getPointerType(destPointee);
6323     // Add qualifiers if necessary.
6324     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6325     // Promote to void*.
6326     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6327     return destType;
6328   }
6329   return QualType();
6330 }
6331 
6332 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6333 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)6334 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6335                                const PartialDiagnostic &Note,
6336                                SourceRange ParenRange) {
6337   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6338   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6339       EndLoc.isValid()) {
6340     Self.Diag(Loc, Note)
6341       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6342       << FixItHint::CreateInsertion(EndLoc, ")");
6343   } else {
6344     // We can't display the parentheses, so just show the bare note.
6345     Self.Diag(Loc, Note) << ParenRange;
6346   }
6347 }
6348 
IsArithmeticOp(BinaryOperatorKind Opc)6349 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6350   return Opc >= BO_Mul && Opc <= BO_Shr;
6351 }
6352 
6353 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6354 /// expression, either using a built-in or overloaded operator,
6355 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6356 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)6357 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6358                                    Expr **RHSExprs) {
6359   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6360   E = E->IgnoreImpCasts();
6361   E = E->IgnoreConversionOperator();
6362   E = E->IgnoreImpCasts();
6363 
6364   // Built-in binary operator.
6365   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6366     if (IsArithmeticOp(OP->getOpcode())) {
6367       *Opcode = OP->getOpcode();
6368       *RHSExprs = OP->getRHS();
6369       return true;
6370     }
6371   }
6372 
6373   // Overloaded operator.
6374   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6375     if (Call->getNumArgs() != 2)
6376       return false;
6377 
6378     // Make sure this is really a binary operator that is safe to pass into
6379     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6380     OverloadedOperatorKind OO = Call->getOperator();
6381     if (OO < OO_Plus || OO > OO_Arrow ||
6382         OO == OO_PlusPlus || OO == OO_MinusMinus)
6383       return false;
6384 
6385     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6386     if (IsArithmeticOp(OpKind)) {
6387       *Opcode = OpKind;
6388       *RHSExprs = Call->getArg(1);
6389       return true;
6390     }
6391   }
6392 
6393   return false;
6394 }
6395 
IsLogicOp(BinaryOperatorKind Opc)6396 static bool IsLogicOp(BinaryOperatorKind Opc) {
6397   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6398 }
6399 
6400 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6401 /// or is a logical expression such as (x==y) which has int type, but is
6402 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)6403 static bool ExprLooksBoolean(Expr *E) {
6404   E = E->IgnoreParenImpCasts();
6405 
6406   if (E->getType()->isBooleanType())
6407     return true;
6408   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6409     return IsLogicOp(OP->getOpcode());
6410   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6411     return OP->getOpcode() == UO_LNot;
6412   if (E->getType()->isPointerType())
6413     return true;
6414 
6415   return false;
6416 }
6417 
6418 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6419 /// and binary operator are mixed in a way that suggests the programmer assumed
6420 /// the conditional operator has higher precedence, for example:
6421 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)6422 static void DiagnoseConditionalPrecedence(Sema &Self,
6423                                           SourceLocation OpLoc,
6424                                           Expr *Condition,
6425                                           Expr *LHSExpr,
6426                                           Expr *RHSExpr) {
6427   BinaryOperatorKind CondOpcode;
6428   Expr *CondRHS;
6429 
6430   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6431     return;
6432   if (!ExprLooksBoolean(CondRHS))
6433     return;
6434 
6435   // The condition is an arithmetic binary expression, with a right-
6436   // hand side that looks boolean, so warn.
6437 
6438   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6439       << Condition->getSourceRange()
6440       << BinaryOperator::getOpcodeStr(CondOpcode);
6441 
6442   SuggestParentheses(Self, OpLoc,
6443     Self.PDiag(diag::note_precedence_silence)
6444       << BinaryOperator::getOpcodeStr(CondOpcode),
6445     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6446 
6447   SuggestParentheses(Self, OpLoc,
6448     Self.PDiag(diag::note_precedence_conditional_first),
6449     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6450 }
6451 
6452 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6453 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)6454 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6455                                     SourceLocation ColonLoc,
6456                                     Expr *CondExpr, Expr *LHSExpr,
6457                                     Expr *RHSExpr) {
6458   if (!getLangOpts().CPlusPlus) {
6459     // C cannot handle TypoExpr nodes in the condition because it
6460     // doesn't handle dependent types properly, so make sure any TypoExprs have
6461     // been dealt with before checking the operands.
6462     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6463     if (!CondResult.isUsable()) return ExprError();
6464     CondExpr = CondResult.get();
6465   }
6466 
6467   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6468   // was the condition.
6469   OpaqueValueExpr *opaqueValue = nullptr;
6470   Expr *commonExpr = nullptr;
6471   if (!LHSExpr) {
6472     commonExpr = CondExpr;
6473     // Lower out placeholder types first.  This is important so that we don't
6474     // try to capture a placeholder. This happens in few cases in C++; such
6475     // as Objective-C++'s dictionary subscripting syntax.
6476     if (commonExpr->hasPlaceholderType()) {
6477       ExprResult result = CheckPlaceholderExpr(commonExpr);
6478       if (!result.isUsable()) return ExprError();
6479       commonExpr = result.get();
6480     }
6481     // We usually want to apply unary conversions *before* saving, except
6482     // in the special case of a C++ l-value conditional.
6483     if (!(getLangOpts().CPlusPlus
6484           && !commonExpr->isTypeDependent()
6485           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6486           && commonExpr->isGLValue()
6487           && commonExpr->isOrdinaryOrBitFieldObject()
6488           && RHSExpr->isOrdinaryOrBitFieldObject()
6489           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6490       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6491       if (commonRes.isInvalid())
6492         return ExprError();
6493       commonExpr = commonRes.get();
6494     }
6495 
6496     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6497                                                 commonExpr->getType(),
6498                                                 commonExpr->getValueKind(),
6499                                                 commonExpr->getObjectKind(),
6500                                                 commonExpr);
6501     LHSExpr = CondExpr = opaqueValue;
6502   }
6503 
6504   ExprValueKind VK = VK_RValue;
6505   ExprObjectKind OK = OK_Ordinary;
6506   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6507   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6508                                              VK, OK, QuestionLoc);
6509   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6510       RHS.isInvalid())
6511     return ExprError();
6512 
6513   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6514                                 RHS.get());
6515 
6516   if (!commonExpr)
6517     return new (Context)
6518         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6519                             RHS.get(), result, VK, OK);
6520 
6521   return new (Context) BinaryConditionalOperator(
6522       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6523       ColonLoc, result, VK, OK);
6524 }
6525 
6526 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6527 // being closely modeled after the C99 spec:-). The odd characteristic of this
6528 // routine is it effectively iqnores the qualifiers on the top level pointee.
6529 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6530 // FIXME: add a couple examples in this comment.
6531 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6532 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6533   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6534   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6535 
6536   // get the "pointed to" type (ignoring qualifiers at the top level)
6537   const Type *lhptee, *rhptee;
6538   Qualifiers lhq, rhq;
6539   std::tie(lhptee, lhq) =
6540       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6541   std::tie(rhptee, rhq) =
6542       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6543 
6544   Sema::AssignConvertType ConvTy = Sema::Compatible;
6545 
6546   // C99 6.5.16.1p1: This following citation is common to constraints
6547   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6548   // qualifiers of the type *pointed to* by the right;
6549 
6550   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6551   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6552       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6553     // Ignore lifetime for further calculation.
6554     lhq.removeObjCLifetime();
6555     rhq.removeObjCLifetime();
6556   }
6557 
6558   if (!lhq.compatiblyIncludes(rhq)) {
6559     // Treat address-space mismatches as fatal.  TODO: address subspaces
6560     if (!lhq.isAddressSpaceSupersetOf(rhq))
6561       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6562 
6563     // It's okay to add or remove GC or lifetime qualifiers when converting to
6564     // and from void*.
6565     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6566                         .compatiblyIncludes(
6567                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6568              && (lhptee->isVoidType() || rhptee->isVoidType()))
6569       ; // keep old
6570 
6571     // Treat lifetime mismatches as fatal.
6572     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6573       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6574 
6575     // For GCC compatibility, other qualifier mismatches are treated
6576     // as still compatible in C.
6577     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6578   }
6579 
6580   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6581   // incomplete type and the other is a pointer to a qualified or unqualified
6582   // version of void...
6583   if (lhptee->isVoidType()) {
6584     if (rhptee->isIncompleteOrObjectType())
6585       return ConvTy;
6586 
6587     // As an extension, we allow cast to/from void* to function pointer.
6588     assert(rhptee->isFunctionType());
6589     return Sema::FunctionVoidPointer;
6590   }
6591 
6592   if (rhptee->isVoidType()) {
6593     if (lhptee->isIncompleteOrObjectType())
6594       return ConvTy;
6595 
6596     // As an extension, we allow cast to/from void* to function pointer.
6597     assert(lhptee->isFunctionType());
6598     return Sema::FunctionVoidPointer;
6599   }
6600 
6601   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6602   // unqualified versions of compatible types, ...
6603   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6604   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6605     // Check if the pointee types are compatible ignoring the sign.
6606     // We explicitly check for char so that we catch "char" vs
6607     // "unsigned char" on systems where "char" is unsigned.
6608     if (lhptee->isCharType())
6609       ltrans = S.Context.UnsignedCharTy;
6610     else if (lhptee->hasSignedIntegerRepresentation())
6611       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6612 
6613     if (rhptee->isCharType())
6614       rtrans = S.Context.UnsignedCharTy;
6615     else if (rhptee->hasSignedIntegerRepresentation())
6616       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6617 
6618     if (ltrans == rtrans) {
6619       // Types are compatible ignoring the sign. Qualifier incompatibility
6620       // takes priority over sign incompatibility because the sign
6621       // warning can be disabled.
6622       if (ConvTy != Sema::Compatible)
6623         return ConvTy;
6624 
6625       return Sema::IncompatiblePointerSign;
6626     }
6627 
6628     // If we are a multi-level pointer, it's possible that our issue is simply
6629     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6630     // the eventual target type is the same and the pointers have the same
6631     // level of indirection, this must be the issue.
6632     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6633       do {
6634         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6635         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6636       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6637 
6638       if (lhptee == rhptee)
6639         return Sema::IncompatibleNestedPointerQualifiers;
6640     }
6641 
6642     // General pointer incompatibility takes priority over qualifiers.
6643     return Sema::IncompatiblePointer;
6644   }
6645   if (!S.getLangOpts().CPlusPlus &&
6646       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6647     return Sema::IncompatiblePointer;
6648   return ConvTy;
6649 }
6650 
6651 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6652 /// block pointer types are compatible or whether a block and normal pointer
6653 /// are compatible. It is more restrict than comparing two function pointer
6654 // types.
6655 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6656 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6657                                     QualType RHSType) {
6658   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6659   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6660 
6661   QualType lhptee, rhptee;
6662 
6663   // get the "pointed to" type (ignoring qualifiers at the top level)
6664   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6665   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6666 
6667   // In C++, the types have to match exactly.
6668   if (S.getLangOpts().CPlusPlus)
6669     return Sema::IncompatibleBlockPointer;
6670 
6671   Sema::AssignConvertType ConvTy = Sema::Compatible;
6672 
6673   // For blocks we enforce that qualifiers are identical.
6674   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6675     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6676 
6677   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6678     return Sema::IncompatibleBlockPointer;
6679 
6680   return ConvTy;
6681 }
6682 
6683 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6684 /// for assignment compatibility.
6685 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6686 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6687                                    QualType RHSType) {
6688   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6689   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6690 
6691   if (LHSType->isObjCBuiltinType()) {
6692     // Class is not compatible with ObjC object pointers.
6693     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6694         !RHSType->isObjCQualifiedClassType())
6695       return Sema::IncompatiblePointer;
6696     return Sema::Compatible;
6697   }
6698   if (RHSType->isObjCBuiltinType()) {
6699     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6700         !LHSType->isObjCQualifiedClassType())
6701       return Sema::IncompatiblePointer;
6702     return Sema::Compatible;
6703   }
6704   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6705   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6706 
6707   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6708       // make an exception for id<P>
6709       !LHSType->isObjCQualifiedIdType())
6710     return Sema::CompatiblePointerDiscardsQualifiers;
6711 
6712   if (S.Context.typesAreCompatible(LHSType, RHSType))
6713     return Sema::Compatible;
6714   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6715     return Sema::IncompatibleObjCQualifiedId;
6716   return Sema::IncompatiblePointer;
6717 }
6718 
6719 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)6720 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6721                                  QualType LHSType, QualType RHSType) {
6722   // Fake up an opaque expression.  We don't actually care about what
6723   // cast operations are required, so if CheckAssignmentConstraints
6724   // adds casts to this they'll be wasted, but fortunately that doesn't
6725   // usually happen on valid code.
6726   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6727   ExprResult RHSPtr = &RHSExpr;
6728   CastKind K = CK_Invalid;
6729 
6730   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6731 }
6732 
6733 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6734 /// has code to accommodate several GCC extensions when type checking
6735 /// pointers. Here are some objectionable examples that GCC considers warnings:
6736 ///
6737 ///  int a, *pint;
6738 ///  short *pshort;
6739 ///  struct foo *pfoo;
6740 ///
6741 ///  pint = pshort; // warning: assignment from incompatible pointer type
6742 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6743 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6744 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6745 ///
6746 /// As a result, the code for dealing with pointers is more complex than the
6747 /// C99 spec dictates.
6748 ///
6749 /// Sets 'Kind' for any result kind except Incompatible.
6750 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind)6751 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6752                                  CastKind &Kind) {
6753   QualType RHSType = RHS.get()->getType();
6754   QualType OrigLHSType = LHSType;
6755 
6756   // Get canonical types.  We're not formatting these types, just comparing
6757   // them.
6758   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6759   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6760 
6761   // Common case: no conversion required.
6762   if (LHSType == RHSType) {
6763     Kind = CK_NoOp;
6764     return Compatible;
6765   }
6766 
6767   // If we have an atomic type, try a non-atomic assignment, then just add an
6768   // atomic qualification step.
6769   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6770     Sema::AssignConvertType result =
6771       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6772     if (result != Compatible)
6773       return result;
6774     if (Kind != CK_NoOp)
6775       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6776     Kind = CK_NonAtomicToAtomic;
6777     return Compatible;
6778   }
6779 
6780   // If the left-hand side is a reference type, then we are in a
6781   // (rare!) case where we've allowed the use of references in C,
6782   // e.g., as a parameter type in a built-in function. In this case,
6783   // just make sure that the type referenced is compatible with the
6784   // right-hand side type. The caller is responsible for adjusting
6785   // LHSType so that the resulting expression does not have reference
6786   // type.
6787   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6788     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6789       Kind = CK_LValueBitCast;
6790       return Compatible;
6791     }
6792     return Incompatible;
6793   }
6794 
6795   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6796   // to the same ExtVector type.
6797   if (LHSType->isExtVectorType()) {
6798     if (RHSType->isExtVectorType())
6799       return Incompatible;
6800     if (RHSType->isArithmeticType()) {
6801       // CK_VectorSplat does T -> vector T, so first cast to the
6802       // element type.
6803       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6804       if (elType != RHSType) {
6805         Kind = PrepareScalarCast(RHS, elType);
6806         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6807       }
6808       Kind = CK_VectorSplat;
6809       return Compatible;
6810     }
6811   }
6812 
6813   // Conversions to or from vector type.
6814   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6815     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6816       // Allow assignments of an AltiVec vector type to an equivalent GCC
6817       // vector type and vice versa
6818       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6819         Kind = CK_BitCast;
6820         return Compatible;
6821       }
6822 
6823       // If we are allowing lax vector conversions, and LHS and RHS are both
6824       // vectors, the total size only needs to be the same. This is a bitcast;
6825       // no bits are changed but the result type is different.
6826       if (isLaxVectorConversion(RHSType, LHSType)) {
6827         Kind = CK_BitCast;
6828         return IncompatibleVectors;
6829       }
6830     }
6831     return Incompatible;
6832   }
6833 
6834   // Arithmetic conversions.
6835   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6836       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6837     Kind = PrepareScalarCast(RHS, LHSType);
6838     return Compatible;
6839   }
6840 
6841   // Conversions to normal pointers.
6842   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6843     // U* -> T*
6844     if (isa<PointerType>(RHSType)) {
6845       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
6846       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
6847       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
6848       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6849     }
6850 
6851     // int -> T*
6852     if (RHSType->isIntegerType()) {
6853       Kind = CK_IntegralToPointer; // FIXME: null?
6854       return IntToPointer;
6855     }
6856 
6857     // C pointers are not compatible with ObjC object pointers,
6858     // with two exceptions:
6859     if (isa<ObjCObjectPointerType>(RHSType)) {
6860       //  - conversions to void*
6861       if (LHSPointer->getPointeeType()->isVoidType()) {
6862         Kind = CK_BitCast;
6863         return Compatible;
6864       }
6865 
6866       //  - conversions from 'Class' to the redefinition type
6867       if (RHSType->isObjCClassType() &&
6868           Context.hasSameType(LHSType,
6869                               Context.getObjCClassRedefinitionType())) {
6870         Kind = CK_BitCast;
6871         return Compatible;
6872       }
6873 
6874       Kind = CK_BitCast;
6875       return IncompatiblePointer;
6876     }
6877 
6878     // U^ -> void*
6879     if (RHSType->getAs<BlockPointerType>()) {
6880       if (LHSPointer->getPointeeType()->isVoidType()) {
6881         Kind = CK_BitCast;
6882         return Compatible;
6883       }
6884     }
6885 
6886     return Incompatible;
6887   }
6888 
6889   // Conversions to block pointers.
6890   if (isa<BlockPointerType>(LHSType)) {
6891     // U^ -> T^
6892     if (RHSType->isBlockPointerType()) {
6893       Kind = CK_BitCast;
6894       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6895     }
6896 
6897     // int or null -> T^
6898     if (RHSType->isIntegerType()) {
6899       Kind = CK_IntegralToPointer; // FIXME: null
6900       return IntToBlockPointer;
6901     }
6902 
6903     // id -> T^
6904     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6905       Kind = CK_AnyPointerToBlockPointerCast;
6906       return Compatible;
6907     }
6908 
6909     // void* -> T^
6910     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6911       if (RHSPT->getPointeeType()->isVoidType()) {
6912         Kind = CK_AnyPointerToBlockPointerCast;
6913         return Compatible;
6914       }
6915 
6916     return Incompatible;
6917   }
6918 
6919   // Conversions to Objective-C pointers.
6920   if (isa<ObjCObjectPointerType>(LHSType)) {
6921     // A* -> B*
6922     if (RHSType->isObjCObjectPointerType()) {
6923       Kind = CK_BitCast;
6924       Sema::AssignConvertType result =
6925         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6926       if (getLangOpts().ObjCAutoRefCount &&
6927           result == Compatible &&
6928           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6929         result = IncompatibleObjCWeakRef;
6930       return result;
6931     }
6932 
6933     // int or null -> A*
6934     if (RHSType->isIntegerType()) {
6935       Kind = CK_IntegralToPointer; // FIXME: null
6936       return IntToPointer;
6937     }
6938 
6939     // In general, C pointers are not compatible with ObjC object pointers,
6940     // with two exceptions:
6941     if (isa<PointerType>(RHSType)) {
6942       Kind = CK_CPointerToObjCPointerCast;
6943 
6944       //  - conversions from 'void*'
6945       if (RHSType->isVoidPointerType()) {
6946         return Compatible;
6947       }
6948 
6949       //  - conversions to 'Class' from its redefinition type
6950       if (LHSType->isObjCClassType() &&
6951           Context.hasSameType(RHSType,
6952                               Context.getObjCClassRedefinitionType())) {
6953         return Compatible;
6954       }
6955 
6956       return IncompatiblePointer;
6957     }
6958 
6959     // Only under strict condition T^ is compatible with an Objective-C pointer.
6960     if (RHSType->isBlockPointerType() &&
6961         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6962       maybeExtendBlockObject(*this, RHS);
6963       Kind = CK_BlockPointerToObjCPointerCast;
6964       return Compatible;
6965     }
6966 
6967     return Incompatible;
6968   }
6969 
6970   // Conversions from pointers that are not covered by the above.
6971   if (isa<PointerType>(RHSType)) {
6972     // T* -> _Bool
6973     if (LHSType == Context.BoolTy) {
6974       Kind = CK_PointerToBoolean;
6975       return Compatible;
6976     }
6977 
6978     // T* -> int
6979     if (LHSType->isIntegerType()) {
6980       Kind = CK_PointerToIntegral;
6981       return PointerToInt;
6982     }
6983 
6984     return Incompatible;
6985   }
6986 
6987   // Conversions from Objective-C pointers that are not covered by the above.
6988   if (isa<ObjCObjectPointerType>(RHSType)) {
6989     // T* -> _Bool
6990     if (LHSType == Context.BoolTy) {
6991       Kind = CK_PointerToBoolean;
6992       return Compatible;
6993     }
6994 
6995     // T* -> int
6996     if (LHSType->isIntegerType()) {
6997       Kind = CK_PointerToIntegral;
6998       return PointerToInt;
6999     }
7000 
7001     return Incompatible;
7002   }
7003 
7004   // struct A -> struct B
7005   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7006     if (Context.typesAreCompatible(LHSType, RHSType)) {
7007       Kind = CK_NoOp;
7008       return Compatible;
7009     }
7010   }
7011 
7012   return Incompatible;
7013 }
7014 
7015 /// \brief Constructs a transparent union from an expression that is
7016 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)7017 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7018                                       ExprResult &EResult, QualType UnionType,
7019                                       FieldDecl *Field) {
7020   // Build an initializer list that designates the appropriate member
7021   // of the transparent union.
7022   Expr *E = EResult.get();
7023   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7024                                                    E, SourceLocation());
7025   Initializer->setType(UnionType);
7026   Initializer->setInitializedFieldInUnion(Field);
7027 
7028   // Build a compound literal constructing a value of the transparent
7029   // union type from this initializer list.
7030   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7031   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7032                                         VK_RValue, Initializer, false);
7033 }
7034 
7035 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)7036 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7037                                                ExprResult &RHS) {
7038   QualType RHSType = RHS.get()->getType();
7039 
7040   // If the ArgType is a Union type, we want to handle a potential
7041   // transparent_union GCC extension.
7042   const RecordType *UT = ArgType->getAsUnionType();
7043   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7044     return Incompatible;
7045 
7046   // The field to initialize within the transparent union.
7047   RecordDecl *UD = UT->getDecl();
7048   FieldDecl *InitField = nullptr;
7049   // It's compatible if the expression matches any of the fields.
7050   for (auto *it : UD->fields()) {
7051     if (it->getType()->isPointerType()) {
7052       // If the transparent union contains a pointer type, we allow:
7053       // 1) void pointer
7054       // 2) null pointer constant
7055       if (RHSType->isPointerType())
7056         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7057           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7058           InitField = it;
7059           break;
7060         }
7061 
7062       if (RHS.get()->isNullPointerConstant(Context,
7063                                            Expr::NPC_ValueDependentIsNull)) {
7064         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7065                                 CK_NullToPointer);
7066         InitField = it;
7067         break;
7068       }
7069     }
7070 
7071     CastKind Kind = CK_Invalid;
7072     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7073           == Compatible) {
7074       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7075       InitField = it;
7076       break;
7077     }
7078   }
7079 
7080   if (!InitField)
7081     return Incompatible;
7082 
7083   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7084   return Compatible;
7085 }
7086 
7087 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & RHS,bool Diagnose,bool DiagnoseCFAudited)7088 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7089                                        bool Diagnose,
7090                                        bool DiagnoseCFAudited) {
7091   if (getLangOpts().CPlusPlus) {
7092     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7093       // C++ 5.17p3: If the left operand is not of class type, the
7094       // expression is implicitly converted (C++ 4) to the
7095       // cv-unqualified type of the left operand.
7096       ExprResult Res;
7097       if (Diagnose) {
7098         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7099                                         AA_Assigning);
7100       } else {
7101         ImplicitConversionSequence ICS =
7102             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7103                                   /*SuppressUserConversions=*/false,
7104                                   /*AllowExplicit=*/false,
7105                                   /*InOverloadResolution=*/false,
7106                                   /*CStyle=*/false,
7107                                   /*AllowObjCWritebackConversion=*/false);
7108         if (ICS.isFailure())
7109           return Incompatible;
7110         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7111                                         ICS, AA_Assigning);
7112       }
7113       if (Res.isInvalid())
7114         return Incompatible;
7115       Sema::AssignConvertType result = Compatible;
7116       if (getLangOpts().ObjCAutoRefCount &&
7117           !CheckObjCARCUnavailableWeakConversion(LHSType,
7118                                                  RHS.get()->getType()))
7119         result = IncompatibleObjCWeakRef;
7120       RHS = Res;
7121       return result;
7122     }
7123 
7124     // FIXME: Currently, we fall through and treat C++ classes like C
7125     // structures.
7126     // FIXME: We also fall through for atomics; not sure what should
7127     // happen there, though.
7128   }
7129 
7130   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7131   // a null pointer constant.
7132   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7133        LHSType->isBlockPointerType()) &&
7134       RHS.get()->isNullPointerConstant(Context,
7135                                        Expr::NPC_ValueDependentIsNull)) {
7136     CastKind Kind;
7137     CXXCastPath Path;
7138     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
7139     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7140     return Compatible;
7141   }
7142 
7143   // This check seems unnatural, however it is necessary to ensure the proper
7144   // conversion of functions/arrays. If the conversion were done for all
7145   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7146   // expressions that suppress this implicit conversion (&, sizeof).
7147   //
7148   // Suppress this for references: C++ 8.5.3p5.
7149   if (!LHSType->isReferenceType()) {
7150     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7151     if (RHS.isInvalid())
7152       return Incompatible;
7153   }
7154 
7155   Expr *PRE = RHS.get()->IgnoreParenCasts();
7156   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7157     ObjCProtocolDecl *PDecl = OPE->getProtocol();
7158     if (PDecl && !PDecl->hasDefinition()) {
7159       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7160       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7161     }
7162   }
7163 
7164   CastKind Kind = CK_Invalid;
7165   Sema::AssignConvertType result =
7166     CheckAssignmentConstraints(LHSType, RHS, Kind);
7167 
7168   // C99 6.5.16.1p2: The value of the right operand is converted to the
7169   // type of the assignment expression.
7170   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7171   // so that we can use references in built-in functions even in C.
7172   // The getNonReferenceType() call makes sure that the resulting expression
7173   // does not have reference type.
7174   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7175     QualType Ty = LHSType.getNonLValueExprType(Context);
7176     Expr *E = RHS.get();
7177     if (getLangOpts().ObjCAutoRefCount)
7178       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7179                              DiagnoseCFAudited);
7180     if (getLangOpts().ObjC1 &&
7181         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7182                                           LHSType, E->getType(), E) ||
7183          ConversionToObjCStringLiteralCheck(LHSType, E))) {
7184       RHS = E;
7185       return Compatible;
7186     }
7187 
7188     RHS = ImpCastExprToType(E, Ty, Kind);
7189   }
7190   return result;
7191 }
7192 
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)7193 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7194                                ExprResult &RHS) {
7195   Diag(Loc, diag::err_typecheck_invalid_operands)
7196     << LHS.get()->getType() << RHS.get()->getType()
7197     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7198   return QualType();
7199 }
7200 
7201 /// Try to convert a value of non-vector type to a vector type by converting
7202 /// the type to the element type of the vector and then performing a splat.
7203 /// If the language is OpenCL, we only use conversions that promote scalar
7204 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7205 /// for float->int.
7206 ///
7207 /// \param scalar - if non-null, actually perform the conversions
7208 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy)7209 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7210                                      QualType scalarTy,
7211                                      QualType vectorEltTy,
7212                                      QualType vectorTy) {
7213   // The conversion to apply to the scalar before splatting it,
7214   // if necessary.
7215   CastKind scalarCast = CK_Invalid;
7216 
7217   if (vectorEltTy->isIntegralType(S.Context)) {
7218     if (!scalarTy->isIntegralType(S.Context))
7219       return true;
7220     if (S.getLangOpts().OpenCL &&
7221         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7222       return true;
7223     scalarCast = CK_IntegralCast;
7224   } else if (vectorEltTy->isRealFloatingType()) {
7225     if (scalarTy->isRealFloatingType()) {
7226       if (S.getLangOpts().OpenCL &&
7227           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7228         return true;
7229       scalarCast = CK_FloatingCast;
7230     }
7231     else if (scalarTy->isIntegralType(S.Context))
7232       scalarCast = CK_IntegralToFloating;
7233     else
7234       return true;
7235   } else {
7236     return true;
7237   }
7238 
7239   // Adjust scalar if desired.
7240   if (scalar) {
7241     if (scalarCast != CK_Invalid)
7242       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7243     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7244   }
7245   return false;
7246 }
7247 
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)7248 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7249                                    SourceLocation Loc, bool IsCompAssign) {
7250   if (!IsCompAssign) {
7251     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7252     if (LHS.isInvalid())
7253       return QualType();
7254   }
7255   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7256   if (RHS.isInvalid())
7257     return QualType();
7258 
7259   // For conversion purposes, we ignore any qualifiers.
7260   // For example, "const float" and "float" are equivalent.
7261   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7262   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7263 
7264   // If the vector types are identical, return.
7265   if (Context.hasSameType(LHSType, RHSType))
7266     return LHSType;
7267 
7268   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7269   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7270   assert(LHSVecType || RHSVecType);
7271 
7272   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7273   if (LHSVecType && RHSVecType &&
7274       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7275     if (isa<ExtVectorType>(LHSVecType)) {
7276       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7277       return LHSType;
7278     }
7279 
7280     if (!IsCompAssign)
7281       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7282     return RHSType;
7283   }
7284 
7285   // If there's an ext-vector type and a scalar, try to convert the scalar to
7286   // the vector element type and splat.
7287   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7288     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7289                                   LHSVecType->getElementType(), LHSType))
7290       return LHSType;
7291   }
7292   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7293     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7294                                   LHSType, RHSVecType->getElementType(),
7295                                   RHSType))
7296       return RHSType;
7297   }
7298 
7299   // If we're allowing lax vector conversions, only the total (data) size
7300   // needs to be the same.
7301   // FIXME: Should we really be allowing this?
7302   // FIXME: We really just pick the LHS type arbitrarily?
7303   if (isLaxVectorConversion(RHSType, LHSType)) {
7304     QualType resultType = LHSType;
7305     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7306     return resultType;
7307   }
7308 
7309   // Okay, the expression is invalid.
7310 
7311   // If there's a non-vector, non-real operand, diagnose that.
7312   if ((!RHSVecType && !RHSType->isRealType()) ||
7313       (!LHSVecType && !LHSType->isRealType())) {
7314     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7315       << LHSType << RHSType
7316       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7317     return QualType();
7318   }
7319 
7320   // Otherwise, use the generic diagnostic.
7321   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7322     << LHSType << RHSType
7323     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7324   return QualType();
7325 }
7326 
7327 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7328 // expression.  These are mainly cases where the null pointer is used as an
7329 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)7330 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7331                                 SourceLocation Loc, bool IsCompare) {
7332   // The canonical way to check for a GNU null is with isNullPointerConstant,
7333   // but we use a bit of a hack here for speed; this is a relatively
7334   // hot path, and isNullPointerConstant is slow.
7335   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7336   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7337 
7338   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7339 
7340   // Avoid analyzing cases where the result will either be invalid (and
7341   // diagnosed as such) or entirely valid and not something to warn about.
7342   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7343       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7344     return;
7345 
7346   // Comparison operations would not make sense with a null pointer no matter
7347   // what the other expression is.
7348   if (!IsCompare) {
7349     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7350         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7351         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7352     return;
7353   }
7354 
7355   // The rest of the operations only make sense with a null pointer
7356   // if the other expression is a pointer.
7357   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7358       NonNullType->canDecayToPointerType())
7359     return;
7360 
7361   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7362       << LHSNull /* LHS is NULL */ << NonNullType
7363       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7364 }
7365 
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)7366 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7367                                            SourceLocation Loc,
7368                                            bool IsCompAssign, bool IsDiv) {
7369   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7370 
7371   if (LHS.get()->getType()->isVectorType() ||
7372       RHS.get()->getType()->isVectorType())
7373     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7374 
7375   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7376   if (LHS.isInvalid() || RHS.isInvalid())
7377     return QualType();
7378 
7379 
7380   if (compType.isNull() || !compType->isArithmeticType())
7381     return InvalidOperands(Loc, LHS, RHS);
7382 
7383   // Check for division by zero.
7384   llvm::APSInt RHSValue;
7385   if (IsDiv && !RHS.get()->isValueDependent() &&
7386       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7387     DiagRuntimeBehavior(Loc, RHS.get(),
7388                         PDiag(diag::warn_division_by_zero)
7389                           << RHS.get()->getSourceRange());
7390 
7391   return compType;
7392 }
7393 
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)7394 QualType Sema::CheckRemainderOperands(
7395   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7396   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7397 
7398   if (LHS.get()->getType()->isVectorType() ||
7399       RHS.get()->getType()->isVectorType()) {
7400     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7401         RHS.get()->getType()->hasIntegerRepresentation())
7402       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7403     return InvalidOperands(Loc, LHS, RHS);
7404   }
7405 
7406   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7407   if (LHS.isInvalid() || RHS.isInvalid())
7408     return QualType();
7409 
7410   if (compType.isNull() || !compType->isIntegerType())
7411     return InvalidOperands(Loc, LHS, RHS);
7412 
7413   // Check for remainder by zero.
7414   llvm::APSInt RHSValue;
7415   if (!RHS.get()->isValueDependent() &&
7416       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7417     DiagRuntimeBehavior(Loc, RHS.get(),
7418                         PDiag(diag::warn_remainder_by_zero)
7419                           << RHS.get()->getSourceRange());
7420 
7421   return compType;
7422 }
7423 
7424 /// \brief Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7425 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7426                                                 Expr *LHSExpr, Expr *RHSExpr) {
7427   S.Diag(Loc, S.getLangOpts().CPlusPlus
7428                 ? diag::err_typecheck_pointer_arith_void_type
7429                 : diag::ext_gnu_void_ptr)
7430     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7431                             << RHSExpr->getSourceRange();
7432 }
7433 
7434 /// \brief Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7435 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7436                                             Expr *Pointer) {
7437   S.Diag(Loc, S.getLangOpts().CPlusPlus
7438                 ? diag::err_typecheck_pointer_arith_void_type
7439                 : diag::ext_gnu_void_ptr)
7440     << 0 /* one pointer */ << Pointer->getSourceRange();
7441 }
7442 
7443 /// \brief Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)7444 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7445                                                     Expr *LHS, Expr *RHS) {
7446   assert(LHS->getType()->isAnyPointerType());
7447   assert(RHS->getType()->isAnyPointerType());
7448   S.Diag(Loc, S.getLangOpts().CPlusPlus
7449                 ? diag::err_typecheck_pointer_arith_function_type
7450                 : diag::ext_gnu_ptr_func_arith)
7451     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7452     // We only show the second type if it differs from the first.
7453     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7454                                                    RHS->getType())
7455     << RHS->getType()->getPointeeType()
7456     << LHS->getSourceRange() << RHS->getSourceRange();
7457 }
7458 
7459 /// \brief Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7460 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7461                                                 Expr *Pointer) {
7462   assert(Pointer->getType()->isAnyPointerType());
7463   S.Diag(Loc, S.getLangOpts().CPlusPlus
7464                 ? diag::err_typecheck_pointer_arith_function_type
7465                 : diag::ext_gnu_ptr_func_arith)
7466     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7467     << 0 /* one pointer, so only one type */
7468     << Pointer->getSourceRange();
7469 }
7470 
7471 /// \brief Emit error if Operand is incomplete pointer type
7472 ///
7473 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)7474 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7475                                                  Expr *Operand) {
7476   QualType ResType = Operand->getType();
7477   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7478     ResType = ResAtomicType->getValueType();
7479 
7480   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7481   QualType PointeeTy = ResType->getPointeeType();
7482   return S.RequireCompleteType(Loc, PointeeTy,
7483                                diag::err_typecheck_arithmetic_incomplete_type,
7484                                PointeeTy, Operand->getSourceRange());
7485 }
7486 
7487 /// \brief Check the validity of an arithmetic pointer operand.
7488 ///
7489 /// If the operand has pointer type, this code will check for pointer types
7490 /// which are invalid in arithmetic operations. These will be diagnosed
7491 /// appropriately, including whether or not the use is supported as an
7492 /// extension.
7493 ///
7494 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)7495 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7496                                             Expr *Operand) {
7497   QualType ResType = Operand->getType();
7498   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7499     ResType = ResAtomicType->getValueType();
7500 
7501   if (!ResType->isAnyPointerType()) return true;
7502 
7503   QualType PointeeTy = ResType->getPointeeType();
7504   if (PointeeTy->isVoidType()) {
7505     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7506     return !S.getLangOpts().CPlusPlus;
7507   }
7508   if (PointeeTy->isFunctionType()) {
7509     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7510     return !S.getLangOpts().CPlusPlus;
7511   }
7512 
7513   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7514 
7515   return true;
7516 }
7517 
7518 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7519 /// operands.
7520 ///
7521 /// This routine will diagnose any invalid arithmetic on pointer operands much
7522 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7523 /// for emitting a single diagnostic even for operations where both LHS and RHS
7524 /// are (potentially problematic) pointers.
7525 ///
7526 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7527 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7528                                                 Expr *LHSExpr, Expr *RHSExpr) {
7529   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7530   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7531   if (!isLHSPointer && !isRHSPointer) return true;
7532 
7533   QualType LHSPointeeTy, RHSPointeeTy;
7534   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7535   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7536 
7537   // if both are pointers check if operation is valid wrt address spaces
7538   if (isLHSPointer && isRHSPointer) {
7539     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7540     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7541     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7542       S.Diag(Loc,
7543              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7544           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7545           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7546       return false;
7547     }
7548   }
7549 
7550   // Check for arithmetic on pointers to incomplete types.
7551   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7552   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7553   if (isLHSVoidPtr || isRHSVoidPtr) {
7554     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7555     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7556     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7557 
7558     return !S.getLangOpts().CPlusPlus;
7559   }
7560 
7561   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7562   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7563   if (isLHSFuncPtr || isRHSFuncPtr) {
7564     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7565     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7566                                                                 RHSExpr);
7567     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7568 
7569     return !S.getLangOpts().CPlusPlus;
7570   }
7571 
7572   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7573     return false;
7574   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7575     return false;
7576 
7577   return true;
7578 }
7579 
7580 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7581 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7582 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7583                                   Expr *LHSExpr, Expr *RHSExpr) {
7584   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7585   Expr* IndexExpr = RHSExpr;
7586   if (!StrExpr) {
7587     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7588     IndexExpr = LHSExpr;
7589   }
7590 
7591   bool IsStringPlusInt = StrExpr &&
7592       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7593   if (!IsStringPlusInt || IndexExpr->isValueDependent())
7594     return;
7595 
7596   llvm::APSInt index;
7597   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7598     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7599     if (index.isNonNegative() &&
7600         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7601                               index.isUnsigned()))
7602       return;
7603   }
7604 
7605   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7606   Self.Diag(OpLoc, diag::warn_string_plus_int)
7607       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7608 
7609   // Only print a fixit for "str" + int, not for int + "str".
7610   if (IndexExpr == RHSExpr) {
7611     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7612     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7613         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7614         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7615         << FixItHint::CreateInsertion(EndLoc, "]");
7616   } else
7617     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7618 }
7619 
7620 /// \brief Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7621 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7622                                    Expr *LHSExpr, Expr *RHSExpr) {
7623   const Expr *StringRefExpr = LHSExpr;
7624   const CharacterLiteral *CharExpr =
7625       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7626 
7627   if (!CharExpr) {
7628     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7629     StringRefExpr = RHSExpr;
7630   }
7631 
7632   if (!CharExpr || !StringRefExpr)
7633     return;
7634 
7635   const QualType StringType = StringRefExpr->getType();
7636 
7637   // Return if not a PointerType.
7638   if (!StringType->isAnyPointerType())
7639     return;
7640 
7641   // Return if not a CharacterType.
7642   if (!StringType->getPointeeType()->isAnyCharacterType())
7643     return;
7644 
7645   ASTContext &Ctx = Self.getASTContext();
7646   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7647 
7648   const QualType CharType = CharExpr->getType();
7649   if (!CharType->isAnyCharacterType() &&
7650       CharType->isIntegerType() &&
7651       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7652     Self.Diag(OpLoc, diag::warn_string_plus_char)
7653         << DiagRange << Ctx.CharTy;
7654   } else {
7655     Self.Diag(OpLoc, diag::warn_string_plus_char)
7656         << DiagRange << CharExpr->getType();
7657   }
7658 
7659   // Only print a fixit for str + char, not for char + str.
7660   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7661     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7662     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7663         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7664         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7665         << FixItHint::CreateInsertion(EndLoc, "]");
7666   } else {
7667     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7668   }
7669 }
7670 
7671 /// \brief Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7672 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7673                                            Expr *LHSExpr, Expr *RHSExpr) {
7674   assert(LHSExpr->getType()->isAnyPointerType());
7675   assert(RHSExpr->getType()->isAnyPointerType());
7676   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7677     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7678     << RHSExpr->getSourceRange();
7679 }
7680 
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,QualType * CompLHSTy)7681 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7682     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7683     QualType* CompLHSTy) {
7684   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7685 
7686   if (LHS.get()->getType()->isVectorType() ||
7687       RHS.get()->getType()->isVectorType()) {
7688     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7689     if (CompLHSTy) *CompLHSTy = compType;
7690     return compType;
7691   }
7692 
7693   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7694   if (LHS.isInvalid() || RHS.isInvalid())
7695     return QualType();
7696 
7697   // Diagnose "string literal" '+' int and string '+' "char literal".
7698   if (Opc == BO_Add) {
7699     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7700     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7701   }
7702 
7703   // handle the common case first (both operands are arithmetic).
7704   if (!compType.isNull() && compType->isArithmeticType()) {
7705     if (CompLHSTy) *CompLHSTy = compType;
7706     return compType;
7707   }
7708 
7709   // Type-checking.  Ultimately the pointer's going to be in PExp;
7710   // note that we bias towards the LHS being the pointer.
7711   Expr *PExp = LHS.get(), *IExp = RHS.get();
7712 
7713   bool isObjCPointer;
7714   if (PExp->getType()->isPointerType()) {
7715     isObjCPointer = false;
7716   } else if (PExp->getType()->isObjCObjectPointerType()) {
7717     isObjCPointer = true;
7718   } else {
7719     std::swap(PExp, IExp);
7720     if (PExp->getType()->isPointerType()) {
7721       isObjCPointer = false;
7722     } else if (PExp->getType()->isObjCObjectPointerType()) {
7723       isObjCPointer = true;
7724     } else {
7725       return InvalidOperands(Loc, LHS, RHS);
7726     }
7727   }
7728   assert(PExp->getType()->isAnyPointerType());
7729 
7730   if (!IExp->getType()->isIntegerType())
7731     return InvalidOperands(Loc, LHS, RHS);
7732 
7733   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7734     return QualType();
7735 
7736   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7737     return QualType();
7738 
7739   // Check array bounds for pointer arithemtic
7740   CheckArrayAccess(PExp, IExp);
7741 
7742   if (CompLHSTy) {
7743     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7744     if (LHSTy.isNull()) {
7745       LHSTy = LHS.get()->getType();
7746       if (LHSTy->isPromotableIntegerType())
7747         LHSTy = Context.getPromotedIntegerType(LHSTy);
7748     }
7749     *CompLHSTy = LHSTy;
7750   }
7751 
7752   return PExp->getType();
7753 }
7754 
7755 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)7756 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7757                                         SourceLocation Loc,
7758                                         QualType* CompLHSTy) {
7759   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7760 
7761   if (LHS.get()->getType()->isVectorType() ||
7762       RHS.get()->getType()->isVectorType()) {
7763     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7764     if (CompLHSTy) *CompLHSTy = compType;
7765     return compType;
7766   }
7767 
7768   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7769   if (LHS.isInvalid() || RHS.isInvalid())
7770     return QualType();
7771 
7772   // Enforce type constraints: C99 6.5.6p3.
7773 
7774   // Handle the common case first (both operands are arithmetic).
7775   if (!compType.isNull() && compType->isArithmeticType()) {
7776     if (CompLHSTy) *CompLHSTy = compType;
7777     return compType;
7778   }
7779 
7780   // Either ptr - int   or   ptr - ptr.
7781   if (LHS.get()->getType()->isAnyPointerType()) {
7782     QualType lpointee = LHS.get()->getType()->getPointeeType();
7783 
7784     // Diagnose bad cases where we step over interface counts.
7785     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7786         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7787       return QualType();
7788 
7789     // The result type of a pointer-int computation is the pointer type.
7790     if (RHS.get()->getType()->isIntegerType()) {
7791       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7792         return QualType();
7793 
7794       // Check array bounds for pointer arithemtic
7795       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7796                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7797 
7798       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7799       return LHS.get()->getType();
7800     }
7801 
7802     // Handle pointer-pointer subtractions.
7803     if (const PointerType *RHSPTy
7804           = RHS.get()->getType()->getAs<PointerType>()) {
7805       QualType rpointee = RHSPTy->getPointeeType();
7806 
7807       if (getLangOpts().CPlusPlus) {
7808         // Pointee types must be the same: C++ [expr.add]
7809         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7810           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7811         }
7812       } else {
7813         // Pointee types must be compatible C99 6.5.6p3
7814         if (!Context.typesAreCompatible(
7815                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7816                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7817           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7818           return QualType();
7819         }
7820       }
7821 
7822       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7823                                                LHS.get(), RHS.get()))
7824         return QualType();
7825 
7826       // The pointee type may have zero size.  As an extension, a structure or
7827       // union may have zero size or an array may have zero length.  In this
7828       // case subtraction does not make sense.
7829       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7830         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7831         if (ElementSize.isZero()) {
7832           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7833             << rpointee.getUnqualifiedType()
7834             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7835         }
7836       }
7837 
7838       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7839       return Context.getPointerDiffType();
7840     }
7841   }
7842 
7843   return InvalidOperands(Loc, LHS, RHS);
7844 }
7845 
isScopedEnumerationType(QualType T)7846 static bool isScopedEnumerationType(QualType T) {
7847   if (const EnumType *ET = T->getAs<EnumType>())
7848     return ET->getDecl()->isScoped();
7849   return false;
7850 }
7851 
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,QualType LHSType)7852 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7853                                    SourceLocation Loc, unsigned Opc,
7854                                    QualType LHSType) {
7855   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7856   // so skip remaining warnings as we don't want to modify values within Sema.
7857   if (S.getLangOpts().OpenCL)
7858     return;
7859 
7860   llvm::APSInt Right;
7861   // Check right/shifter operand
7862   if (RHS.get()->isValueDependent() ||
7863       !RHS.get()->EvaluateAsInt(Right, S.Context))
7864     return;
7865 
7866   if (Right.isNegative()) {
7867     S.DiagRuntimeBehavior(Loc, RHS.get(),
7868                           S.PDiag(diag::warn_shift_negative)
7869                             << RHS.get()->getSourceRange());
7870     return;
7871   }
7872   llvm::APInt LeftBits(Right.getBitWidth(),
7873                        S.Context.getTypeSize(LHS.get()->getType()));
7874   if (Right.uge(LeftBits)) {
7875     S.DiagRuntimeBehavior(Loc, RHS.get(),
7876                           S.PDiag(diag::warn_shift_gt_typewidth)
7877                             << RHS.get()->getSourceRange());
7878     return;
7879   }
7880   if (Opc != BO_Shl)
7881     return;
7882 
7883   // When left shifting an ICE which is signed, we can check for overflow which
7884   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7885   // integers have defined behavior modulo one more than the maximum value
7886   // representable in the result type, so never warn for those.
7887   llvm::APSInt Left;
7888   if (LHS.get()->isValueDependent() ||
7889       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7890       LHSType->hasUnsignedIntegerRepresentation())
7891     return;
7892   llvm::APInt ResultBits =
7893       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7894   if (LeftBits.uge(ResultBits))
7895     return;
7896   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7897   Result = Result.shl(Right);
7898 
7899   // Print the bit representation of the signed integer as an unsigned
7900   // hexadecimal number.
7901   SmallString<40> HexResult;
7902   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7903 
7904   // If we are only missing a sign bit, this is less likely to result in actual
7905   // bugs -- if the result is cast back to an unsigned type, it will have the
7906   // expected value. Thus we place this behind a different warning that can be
7907   // turned off separately if needed.
7908   if (LeftBits == ResultBits - 1) {
7909     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7910         << HexResult << LHSType
7911         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7912     return;
7913   }
7914 
7915   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7916     << HexResult.str() << Result.getMinSignedBits() << LHSType
7917     << Left.getBitWidth() << LHS.get()->getSourceRange()
7918     << RHS.get()->getSourceRange();
7919 }
7920 
7921 /// \brief Return the resulting type when an OpenCL vector is shifted
7922 ///        by a scalar or vector shift amount.
checkOpenCLVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)7923 static QualType checkOpenCLVectorShift(Sema &S,
7924                                        ExprResult &LHS, ExprResult &RHS,
7925                                        SourceLocation Loc, bool IsCompAssign) {
7926   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
7927   if (!LHS.get()->getType()->isVectorType()) {
7928     S.Diag(Loc, diag::err_shift_rhs_only_vector)
7929       << RHS.get()->getType() << LHS.get()->getType()
7930       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7931     return QualType();
7932   }
7933 
7934   if (!IsCompAssign) {
7935     LHS = S.UsualUnaryConversions(LHS.get());
7936     if (LHS.isInvalid()) return QualType();
7937   }
7938 
7939   RHS = S.UsualUnaryConversions(RHS.get());
7940   if (RHS.isInvalid()) return QualType();
7941 
7942   QualType LHSType = LHS.get()->getType();
7943   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
7944   QualType LHSEleType = LHSVecTy->getElementType();
7945 
7946   // Note that RHS might not be a vector.
7947   QualType RHSType = RHS.get()->getType();
7948   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
7949   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
7950 
7951   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
7952   if (!LHSEleType->isIntegerType()) {
7953     S.Diag(Loc, diag::err_typecheck_expect_int)
7954       << LHS.get()->getType() << LHS.get()->getSourceRange();
7955     return QualType();
7956   }
7957 
7958   if (!RHSEleType->isIntegerType()) {
7959     S.Diag(Loc, diag::err_typecheck_expect_int)
7960       << RHS.get()->getType() << RHS.get()->getSourceRange();
7961     return QualType();
7962   }
7963 
7964   if (RHSVecTy) {
7965     // OpenCL v1.1 s6.3.j says that for vector types, the operators
7966     // are applied component-wise. So if RHS is a vector, then ensure
7967     // that the number of elements is the same as LHS...
7968     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
7969       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
7970         << LHS.get()->getType() << RHS.get()->getType()
7971         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7972       return QualType();
7973     }
7974   } else {
7975     // ...else expand RHS to match the number of elements in LHS.
7976     QualType VecTy =
7977       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
7978     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
7979   }
7980 
7981   return LHSType;
7982 }
7983 
7984 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc,bool IsCompAssign)7985 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7986                                   SourceLocation Loc, unsigned Opc,
7987                                   bool IsCompAssign) {
7988   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7989 
7990   // Vector shifts promote their scalar inputs to vector type.
7991   if (LHS.get()->getType()->isVectorType() ||
7992       RHS.get()->getType()->isVectorType()) {
7993     if (LangOpts.OpenCL)
7994       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
7995     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7996   }
7997 
7998   // Shifts don't perform usual arithmetic conversions, they just do integer
7999   // promotions on each operand. C99 6.5.7p3
8000 
8001   // For the LHS, do usual unary conversions, but then reset them away
8002   // if this is a compound assignment.
8003   ExprResult OldLHS = LHS;
8004   LHS = UsualUnaryConversions(LHS.get());
8005   if (LHS.isInvalid())
8006     return QualType();
8007   QualType LHSType = LHS.get()->getType();
8008   if (IsCompAssign) LHS = OldLHS;
8009 
8010   // The RHS is simpler.
8011   RHS = UsualUnaryConversions(RHS.get());
8012   if (RHS.isInvalid())
8013     return QualType();
8014   QualType RHSType = RHS.get()->getType();
8015 
8016   // C99 6.5.7p2: Each of the operands shall have integer type.
8017   if (!LHSType->hasIntegerRepresentation() ||
8018       !RHSType->hasIntegerRepresentation())
8019     return InvalidOperands(Loc, LHS, RHS);
8020 
8021   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8022   // hasIntegerRepresentation() above instead of this.
8023   if (isScopedEnumerationType(LHSType) ||
8024       isScopedEnumerationType(RHSType)) {
8025     return InvalidOperands(Loc, LHS, RHS);
8026   }
8027   // Sanity-check shift operands
8028   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8029 
8030   // "The type of the result is that of the promoted left operand."
8031   return LHSType;
8032 }
8033 
IsWithinTemplateSpecialization(Decl * D)8034 static bool IsWithinTemplateSpecialization(Decl *D) {
8035   if (DeclContext *DC = D->getDeclContext()) {
8036     if (isa<ClassTemplateSpecializationDecl>(DC))
8037       return true;
8038     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8039       return FD->isFunctionTemplateSpecialization();
8040   }
8041   return false;
8042 }
8043 
8044 /// If two different enums are compared, raise a warning.
checkEnumComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8045 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8046                                 Expr *RHS) {
8047   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8048   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8049 
8050   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8051   if (!LHSEnumType)
8052     return;
8053   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8054   if (!RHSEnumType)
8055     return;
8056 
8057   // Ignore anonymous enums.
8058   if (!LHSEnumType->getDecl()->getIdentifier())
8059     return;
8060   if (!RHSEnumType->getDecl()->getIdentifier())
8061     return;
8062 
8063   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8064     return;
8065 
8066   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8067       << LHSStrippedType << RHSStrippedType
8068       << LHS->getSourceRange() << RHS->getSourceRange();
8069 }
8070 
8071 /// \brief Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8072 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8073                                               ExprResult &LHS, ExprResult &RHS,
8074                                               bool IsError) {
8075   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8076                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8077     << LHS.get()->getType() << RHS.get()->getType()
8078     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8079 }
8080 
8081 /// \brief Returns false if the pointers are converted to a composite type,
8082 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)8083 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8084                                            ExprResult &LHS, ExprResult &RHS) {
8085   // C++ [expr.rel]p2:
8086   //   [...] Pointer conversions (4.10) and qualification
8087   //   conversions (4.4) are performed on pointer operands (or on
8088   //   a pointer operand and a null pointer constant) to bring
8089   //   them to their composite pointer type. [...]
8090   //
8091   // C++ [expr.eq]p1 uses the same notion for (in)equality
8092   // comparisons of pointers.
8093 
8094   // C++ [expr.eq]p2:
8095   //   In addition, pointers to members can be compared, or a pointer to
8096   //   member and a null pointer constant. Pointer to member conversions
8097   //   (4.11) and qualification conversions (4.4) are performed to bring
8098   //   them to a common type. If one operand is a null pointer constant,
8099   //   the common type is the type of the other operand. Otherwise, the
8100   //   common type is a pointer to member type similar (4.4) to the type
8101   //   of one of the operands, with a cv-qualification signature (4.4)
8102   //   that is the union of the cv-qualification signatures of the operand
8103   //   types.
8104 
8105   QualType LHSType = LHS.get()->getType();
8106   QualType RHSType = RHS.get()->getType();
8107   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8108          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8109 
8110   bool NonStandardCompositeType = false;
8111   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8112   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8113   if (T.isNull()) {
8114     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8115     return true;
8116   }
8117 
8118   if (NonStandardCompositeType)
8119     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8120       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8121       << RHS.get()->getSourceRange();
8122 
8123   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8124   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8125   return false;
8126 }
8127 
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8128 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8129                                                     ExprResult &LHS,
8130                                                     ExprResult &RHS,
8131                                                     bool IsError) {
8132   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8133                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8134     << LHS.get()->getType() << RHS.get()->getType()
8135     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8136 }
8137 
isObjCObjectLiteral(ExprResult & E)8138 static bool isObjCObjectLiteral(ExprResult &E) {
8139   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8140   case Stmt::ObjCArrayLiteralClass:
8141   case Stmt::ObjCDictionaryLiteralClass:
8142   case Stmt::ObjCStringLiteralClass:
8143   case Stmt::ObjCBoxedExprClass:
8144     return true;
8145   default:
8146     // Note that ObjCBoolLiteral is NOT an object literal!
8147     return false;
8148   }
8149 }
8150 
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)8151 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8152   const ObjCObjectPointerType *Type =
8153     LHS->getType()->getAs<ObjCObjectPointerType>();
8154 
8155   // If this is not actually an Objective-C object, bail out.
8156   if (!Type)
8157     return false;
8158 
8159   // Get the LHS object's interface type.
8160   QualType InterfaceType = Type->getPointeeType();
8161   if (const ObjCObjectType *iQFaceTy =
8162       InterfaceType->getAsObjCQualifiedInterfaceType())
8163     InterfaceType = iQFaceTy->getBaseType();
8164 
8165   // If the RHS isn't an Objective-C object, bail out.
8166   if (!RHS->getType()->isObjCObjectPointerType())
8167     return false;
8168 
8169   // Try to find the -isEqual: method.
8170   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8171   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8172                                                       InterfaceType,
8173                                                       /*instance=*/true);
8174   if (!Method) {
8175     if (Type->isObjCIdType()) {
8176       // For 'id', just check the global pool.
8177       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8178                                                   /*receiverId=*/true);
8179     } else {
8180       // Check protocols.
8181       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8182                                              /*instance=*/true);
8183     }
8184   }
8185 
8186   if (!Method)
8187     return false;
8188 
8189   QualType T = Method->parameters()[0]->getType();
8190   if (!T->isObjCObjectPointerType())
8191     return false;
8192 
8193   QualType R = Method->getReturnType();
8194   if (!R->isScalarType())
8195     return false;
8196 
8197   return true;
8198 }
8199 
CheckLiteralKind(Expr * FromE)8200 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8201   FromE = FromE->IgnoreParenImpCasts();
8202   switch (FromE->getStmtClass()) {
8203     default:
8204       break;
8205     case Stmt::ObjCStringLiteralClass:
8206       // "string literal"
8207       return LK_String;
8208     case Stmt::ObjCArrayLiteralClass:
8209       // "array literal"
8210       return LK_Array;
8211     case Stmt::ObjCDictionaryLiteralClass:
8212       // "dictionary literal"
8213       return LK_Dictionary;
8214     case Stmt::BlockExprClass:
8215       return LK_Block;
8216     case Stmt::ObjCBoxedExprClass: {
8217       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8218       switch (Inner->getStmtClass()) {
8219         case Stmt::IntegerLiteralClass:
8220         case Stmt::FloatingLiteralClass:
8221         case Stmt::CharacterLiteralClass:
8222         case Stmt::ObjCBoolLiteralExprClass:
8223         case Stmt::CXXBoolLiteralExprClass:
8224           // "numeric literal"
8225           return LK_Numeric;
8226         case Stmt::ImplicitCastExprClass: {
8227           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8228           // Boolean literals can be represented by implicit casts.
8229           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8230             return LK_Numeric;
8231           break;
8232         }
8233         default:
8234           break;
8235       }
8236       return LK_Boxed;
8237     }
8238   }
8239   return LK_None;
8240 }
8241 
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)8242 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8243                                           ExprResult &LHS, ExprResult &RHS,
8244                                           BinaryOperator::Opcode Opc){
8245   Expr *Literal;
8246   Expr *Other;
8247   if (isObjCObjectLiteral(LHS)) {
8248     Literal = LHS.get();
8249     Other = RHS.get();
8250   } else {
8251     Literal = RHS.get();
8252     Other = LHS.get();
8253   }
8254 
8255   // Don't warn on comparisons against nil.
8256   Other = Other->IgnoreParenCasts();
8257   if (Other->isNullPointerConstant(S.getASTContext(),
8258                                    Expr::NPC_ValueDependentIsNotNull))
8259     return;
8260 
8261   // This should be kept in sync with warn_objc_literal_comparison.
8262   // LK_String should always be after the other literals, since it has its own
8263   // warning flag.
8264   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8265   assert(LiteralKind != Sema::LK_Block);
8266   if (LiteralKind == Sema::LK_None) {
8267     llvm_unreachable("Unknown Objective-C object literal kind");
8268   }
8269 
8270   if (LiteralKind == Sema::LK_String)
8271     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8272       << Literal->getSourceRange();
8273   else
8274     S.Diag(Loc, diag::warn_objc_literal_comparison)
8275       << LiteralKind << Literal->getSourceRange();
8276 
8277   if (BinaryOperator::isEqualityOp(Opc) &&
8278       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8279     SourceLocation Start = LHS.get()->getLocStart();
8280     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8281     CharSourceRange OpRange =
8282       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
8283 
8284     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8285       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8286       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8287       << FixItHint::CreateInsertion(End, "]");
8288   }
8289 }
8290 
diagnoseLogicalNotOnLHSofComparison(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned OpaqueOpc)8291 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8292                                                 ExprResult &RHS,
8293                                                 SourceLocation Loc,
8294                                                 unsigned OpaqueOpc) {
8295   // This checking requires bools.
8296   if (!S.getLangOpts().Bool) return;
8297 
8298   // Check that left hand side is !something.
8299   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8300   if (!UO || UO->getOpcode() != UO_LNot) return;
8301 
8302   // Only check if the right hand side is non-bool arithmetic type.
8303   if (RHS.get()->getType()->isBooleanType()) return;
8304 
8305   // Make sure that the something in !something is not bool.
8306   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8307   if (SubExpr->getType()->isBooleanType()) return;
8308 
8309   // Emit warning.
8310   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8311       << Loc;
8312 
8313   // First note suggest !(x < y)
8314   SourceLocation FirstOpen = SubExpr->getLocStart();
8315   SourceLocation FirstClose = RHS.get()->getLocEnd();
8316   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
8317   if (FirstClose.isInvalid())
8318     FirstOpen = SourceLocation();
8319   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8320       << FixItHint::CreateInsertion(FirstOpen, "(")
8321       << FixItHint::CreateInsertion(FirstClose, ")");
8322 
8323   // Second note suggests (!x) < y
8324   SourceLocation SecondOpen = LHS.get()->getLocStart();
8325   SourceLocation SecondClose = LHS.get()->getLocEnd();
8326   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
8327   if (SecondClose.isInvalid())
8328     SecondOpen = SourceLocation();
8329   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8330       << FixItHint::CreateInsertion(SecondOpen, "(")
8331       << FixItHint::CreateInsertion(SecondClose, ")");
8332 }
8333 
8334 // Get the decl for a simple expression: a reference to a variable,
8335 // an implicit C++ field reference, or an implicit ObjC ivar reference.
getCompareDecl(Expr * E)8336 static ValueDecl *getCompareDecl(Expr *E) {
8337   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8338     return DR->getDecl();
8339   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8340     if (Ivar->isFreeIvar())
8341       return Ivar->getDecl();
8342   }
8343   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8344     if (Mem->isImplicitAccess())
8345       return Mem->getMemberDecl();
8346   }
8347   return nullptr;
8348 }
8349 
8350 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned OpaqueOpc,bool IsRelational)8351 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8352                                     SourceLocation Loc, unsigned OpaqueOpc,
8353                                     bool IsRelational) {
8354   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8355 
8356   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
8357 
8358   // Handle vector comparisons separately.
8359   if (LHS.get()->getType()->isVectorType() ||
8360       RHS.get()->getType()->isVectorType())
8361     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8362 
8363   QualType LHSType = LHS.get()->getType();
8364   QualType RHSType = RHS.get()->getType();
8365 
8366   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8367   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8368 
8369   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8370   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
8371 
8372   if (!LHSType->hasFloatingRepresentation() &&
8373       !(LHSType->isBlockPointerType() && IsRelational) &&
8374       !LHS.get()->getLocStart().isMacroID() &&
8375       !RHS.get()->getLocStart().isMacroID() &&
8376       ActiveTemplateInstantiations.empty()) {
8377     // For non-floating point types, check for self-comparisons of the form
8378     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8379     // often indicate logic errors in the program.
8380     //
8381     // NOTE: Don't warn about comparison expressions resulting from macro
8382     // expansion. Also don't warn about comparisons which are only self
8383     // comparisons within a template specialization. The warnings should catch
8384     // obvious cases in the definition of the template anyways. The idea is to
8385     // warn when the typed comparison operator will always evaluate to the same
8386     // result.
8387     ValueDecl *DL = getCompareDecl(LHSStripped);
8388     ValueDecl *DR = getCompareDecl(RHSStripped);
8389     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8390       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8391                           << 0 // self-
8392                           << (Opc == BO_EQ
8393                               || Opc == BO_LE
8394                               || Opc == BO_GE));
8395     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8396                !DL->getType()->isReferenceType() &&
8397                !DR->getType()->isReferenceType()) {
8398         // what is it always going to eval to?
8399         char always_evals_to;
8400         switch(Opc) {
8401         case BO_EQ: // e.g. array1 == array2
8402           always_evals_to = 0; // false
8403           break;
8404         case BO_NE: // e.g. array1 != array2
8405           always_evals_to = 1; // true
8406           break;
8407         default:
8408           // best we can say is 'a constant'
8409           always_evals_to = 2; // e.g. array1 <= array2
8410           break;
8411         }
8412         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8413                             << 1 // array
8414                             << always_evals_to);
8415     }
8416 
8417     if (isa<CastExpr>(LHSStripped))
8418       LHSStripped = LHSStripped->IgnoreParenCasts();
8419     if (isa<CastExpr>(RHSStripped))
8420       RHSStripped = RHSStripped->IgnoreParenCasts();
8421 
8422     // Warn about comparisons against a string constant (unless the other
8423     // operand is null), the user probably wants strcmp.
8424     Expr *literalString = nullptr;
8425     Expr *literalStringStripped = nullptr;
8426     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8427         !RHSStripped->isNullPointerConstant(Context,
8428                                             Expr::NPC_ValueDependentIsNull)) {
8429       literalString = LHS.get();
8430       literalStringStripped = LHSStripped;
8431     } else if ((isa<StringLiteral>(RHSStripped) ||
8432                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8433                !LHSStripped->isNullPointerConstant(Context,
8434                                             Expr::NPC_ValueDependentIsNull)) {
8435       literalString = RHS.get();
8436       literalStringStripped = RHSStripped;
8437     }
8438 
8439     if (literalString) {
8440       DiagRuntimeBehavior(Loc, nullptr,
8441         PDiag(diag::warn_stringcompare)
8442           << isa<ObjCEncodeExpr>(literalStringStripped)
8443           << literalString->getSourceRange());
8444     }
8445   }
8446 
8447   // C99 6.5.8p3 / C99 6.5.9p4
8448   UsualArithmeticConversions(LHS, RHS);
8449   if (LHS.isInvalid() || RHS.isInvalid())
8450     return QualType();
8451 
8452   LHSType = LHS.get()->getType();
8453   RHSType = RHS.get()->getType();
8454 
8455   // The result of comparisons is 'bool' in C++, 'int' in C.
8456   QualType ResultTy = Context.getLogicalOperationType();
8457 
8458   if (IsRelational) {
8459     if (LHSType->isRealType() && RHSType->isRealType())
8460       return ResultTy;
8461   } else {
8462     // Check for comparisons of floating point operands using != and ==.
8463     if (LHSType->hasFloatingRepresentation())
8464       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8465 
8466     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8467       return ResultTy;
8468   }
8469 
8470   const Expr::NullPointerConstantKind LHSNullKind =
8471       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8472   const Expr::NullPointerConstantKind RHSNullKind =
8473       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8474   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8475   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8476 
8477   if (!IsRelational && LHSIsNull != RHSIsNull) {
8478     bool IsEquality = Opc == BO_EQ;
8479     if (RHSIsNull)
8480       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8481                                    RHS.get()->getSourceRange());
8482     else
8483       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8484                                    LHS.get()->getSourceRange());
8485   }
8486 
8487   // All of the following pointer-related warnings are GCC extensions, except
8488   // when handling null pointer constants.
8489   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8490     QualType LCanPointeeTy =
8491       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8492     QualType RCanPointeeTy =
8493       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8494 
8495     if (getLangOpts().CPlusPlus) {
8496       if (LCanPointeeTy == RCanPointeeTy)
8497         return ResultTy;
8498       if (!IsRelational &&
8499           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8500         // Valid unless comparison between non-null pointer and function pointer
8501         // This is a gcc extension compatibility comparison.
8502         // In a SFINAE context, we treat this as a hard error to maintain
8503         // conformance with the C++ standard.
8504         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8505             && !LHSIsNull && !RHSIsNull) {
8506           diagnoseFunctionPointerToVoidComparison(
8507               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8508 
8509           if (isSFINAEContext())
8510             return QualType();
8511 
8512           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8513           return ResultTy;
8514         }
8515       }
8516 
8517       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8518         return QualType();
8519       else
8520         return ResultTy;
8521     }
8522     // C99 6.5.9p2 and C99 6.5.8p2
8523     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8524                                    RCanPointeeTy.getUnqualifiedType())) {
8525       // Valid unless a relational comparison of function pointers
8526       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8527         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8528           << LHSType << RHSType << LHS.get()->getSourceRange()
8529           << RHS.get()->getSourceRange();
8530       }
8531     } else if (!IsRelational &&
8532                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8533       // Valid unless comparison between non-null pointer and function pointer
8534       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8535           && !LHSIsNull && !RHSIsNull)
8536         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8537                                                 /*isError*/false);
8538     } else {
8539       // Invalid
8540       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8541     }
8542     if (LCanPointeeTy != RCanPointeeTy) {
8543       const PointerType *lhsPtr = LHSType->getAs<PointerType>();
8544       if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8545         Diag(Loc,
8546              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8547             << LHSType << RHSType << 0 /* comparison */
8548             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8549       }
8550       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8551       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8552       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8553                                                : CK_BitCast;
8554       if (LHSIsNull && !RHSIsNull)
8555         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8556       else
8557         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8558     }
8559     return ResultTy;
8560   }
8561 
8562   if (getLangOpts().CPlusPlus) {
8563     // Comparison of nullptr_t with itself.
8564     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8565       return ResultTy;
8566 
8567     // Comparison of pointers with null pointer constants and equality
8568     // comparisons of member pointers to null pointer constants.
8569     if (RHSIsNull &&
8570         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8571          (!IsRelational &&
8572           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8573       RHS = ImpCastExprToType(RHS.get(), LHSType,
8574                         LHSType->isMemberPointerType()
8575                           ? CK_NullToMemberPointer
8576                           : CK_NullToPointer);
8577       return ResultTy;
8578     }
8579     if (LHSIsNull &&
8580         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8581          (!IsRelational &&
8582           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8583       LHS = ImpCastExprToType(LHS.get(), RHSType,
8584                         RHSType->isMemberPointerType()
8585                           ? CK_NullToMemberPointer
8586                           : CK_NullToPointer);
8587       return ResultTy;
8588     }
8589 
8590     // Comparison of member pointers.
8591     if (!IsRelational &&
8592         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8593       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8594         return QualType();
8595       else
8596         return ResultTy;
8597     }
8598 
8599     // Handle scoped enumeration types specifically, since they don't promote
8600     // to integers.
8601     if (LHS.get()->getType()->isEnumeralType() &&
8602         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8603                                        RHS.get()->getType()))
8604       return ResultTy;
8605   }
8606 
8607   // Handle block pointer types.
8608   if (!IsRelational && LHSType->isBlockPointerType() &&
8609       RHSType->isBlockPointerType()) {
8610     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8611     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8612 
8613     if (!LHSIsNull && !RHSIsNull &&
8614         !Context.typesAreCompatible(lpointee, rpointee)) {
8615       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8616         << LHSType << RHSType << LHS.get()->getSourceRange()
8617         << RHS.get()->getSourceRange();
8618     }
8619     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8620     return ResultTy;
8621   }
8622 
8623   // Allow block pointers to be compared with null pointer constants.
8624   if (!IsRelational
8625       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8626           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8627     if (!LHSIsNull && !RHSIsNull) {
8628       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8629              ->getPointeeType()->isVoidType())
8630             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8631                 ->getPointeeType()->isVoidType())))
8632         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8633           << LHSType << RHSType << LHS.get()->getSourceRange()
8634           << RHS.get()->getSourceRange();
8635     }
8636     if (LHSIsNull && !RHSIsNull)
8637       LHS = ImpCastExprToType(LHS.get(), RHSType,
8638                               RHSType->isPointerType() ? CK_BitCast
8639                                 : CK_AnyPointerToBlockPointerCast);
8640     else
8641       RHS = ImpCastExprToType(RHS.get(), LHSType,
8642                               LHSType->isPointerType() ? CK_BitCast
8643                                 : CK_AnyPointerToBlockPointerCast);
8644     return ResultTy;
8645   }
8646 
8647   if (LHSType->isObjCObjectPointerType() ||
8648       RHSType->isObjCObjectPointerType()) {
8649     const PointerType *LPT = LHSType->getAs<PointerType>();
8650     const PointerType *RPT = RHSType->getAs<PointerType>();
8651     if (LPT || RPT) {
8652       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8653       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8654 
8655       if (!LPtrToVoid && !RPtrToVoid &&
8656           !Context.typesAreCompatible(LHSType, RHSType)) {
8657         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8658                                           /*isError*/false);
8659       }
8660       if (LHSIsNull && !RHSIsNull) {
8661         Expr *E = LHS.get();
8662         if (getLangOpts().ObjCAutoRefCount)
8663           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8664         LHS = ImpCastExprToType(E, RHSType,
8665                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8666       }
8667       else {
8668         Expr *E = RHS.get();
8669         if (getLangOpts().ObjCAutoRefCount)
8670           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8671                                  Opc);
8672         RHS = ImpCastExprToType(E, LHSType,
8673                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8674       }
8675       return ResultTy;
8676     }
8677     if (LHSType->isObjCObjectPointerType() &&
8678         RHSType->isObjCObjectPointerType()) {
8679       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8680         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8681                                           /*isError*/false);
8682       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8683         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8684 
8685       if (LHSIsNull && !RHSIsNull)
8686         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8687       else
8688         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8689       return ResultTy;
8690     }
8691   }
8692   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8693       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8694     unsigned DiagID = 0;
8695     bool isError = false;
8696     if (LangOpts.DebuggerSupport) {
8697       // Under a debugger, allow the comparison of pointers to integers,
8698       // since users tend to want to compare addresses.
8699     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8700         (RHSIsNull && RHSType->isIntegerType())) {
8701       if (IsRelational && !getLangOpts().CPlusPlus)
8702         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8703     } else if (IsRelational && !getLangOpts().CPlusPlus)
8704       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8705     else if (getLangOpts().CPlusPlus) {
8706       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8707       isError = true;
8708     } else
8709       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8710 
8711     if (DiagID) {
8712       Diag(Loc, DiagID)
8713         << LHSType << RHSType << LHS.get()->getSourceRange()
8714         << RHS.get()->getSourceRange();
8715       if (isError)
8716         return QualType();
8717     }
8718 
8719     if (LHSType->isIntegerType())
8720       LHS = ImpCastExprToType(LHS.get(), RHSType,
8721                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8722     else
8723       RHS = ImpCastExprToType(RHS.get(), LHSType,
8724                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8725     return ResultTy;
8726   }
8727 
8728   // Handle block pointers.
8729   if (!IsRelational && RHSIsNull
8730       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8731     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8732     return ResultTy;
8733   }
8734   if (!IsRelational && LHSIsNull
8735       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8736     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8737     return ResultTy;
8738   }
8739 
8740   return InvalidOperands(Loc, LHS, RHS);
8741 }
8742 
8743 
8744 // Return a signed type that is of identical size and number of elements.
8745 // For floating point vectors, return an integer type of identical size
8746 // and number of elements.
GetSignedVectorType(QualType V)8747 QualType Sema::GetSignedVectorType(QualType V) {
8748   const VectorType *VTy = V->getAs<VectorType>();
8749   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8750   if (TypeSize == Context.getTypeSize(Context.CharTy))
8751     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8752   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8753     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8754   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8755     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8756   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8757     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8758   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8759          "Unhandled vector element size in vector compare");
8760   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8761 }
8762 
8763 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8764 /// operates on extended vector types.  Instead of producing an IntTy result,
8765 /// like a scalar comparison, a vector comparison produces a vector of integer
8766 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsRelational)8767 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8768                                           SourceLocation Loc,
8769                                           bool IsRelational) {
8770   // Check to make sure we're operating on vectors of the same type and width,
8771   // Allowing one side to be a scalar of element type.
8772   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8773   if (vType.isNull())
8774     return vType;
8775 
8776   QualType LHSType = LHS.get()->getType();
8777 
8778   // If AltiVec, the comparison results in a numeric type, i.e.
8779   // bool for C++, int for C
8780   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8781     return Context.getLogicalOperationType();
8782 
8783   // For non-floating point types, check for self-comparisons of the form
8784   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8785   // often indicate logic errors in the program.
8786   if (!LHSType->hasFloatingRepresentation() &&
8787       ActiveTemplateInstantiations.empty()) {
8788     if (DeclRefExpr* DRL
8789           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8790       if (DeclRefExpr* DRR
8791             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8792         if (DRL->getDecl() == DRR->getDecl())
8793           DiagRuntimeBehavior(Loc, nullptr,
8794                               PDiag(diag::warn_comparison_always)
8795                                 << 0 // self-
8796                                 << 2 // "a constant"
8797                               );
8798   }
8799 
8800   // Check for comparisons of floating point operands using != and ==.
8801   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8802     assert (RHS.get()->getType()->hasFloatingRepresentation());
8803     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8804   }
8805 
8806   // Return a signed type for the vector.
8807   return GetSignedVectorType(LHSType);
8808 }
8809 
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)8810 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8811                                           SourceLocation Loc) {
8812   // Ensure that either both operands are of the same vector type, or
8813   // one operand is of a vector type and the other is of its element type.
8814   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8815   if (vType.isNull())
8816     return InvalidOperands(Loc, LHS, RHS);
8817   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8818       vType->hasFloatingRepresentation())
8819     return InvalidOperands(Loc, LHS, RHS);
8820 
8821   return GetSignedVectorType(LHS.get()->getType());
8822 }
8823 
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8824 inline QualType Sema::CheckBitwiseOperands(
8825   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8826   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8827 
8828   if (LHS.get()->getType()->isVectorType() ||
8829       RHS.get()->getType()->isVectorType()) {
8830     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8831         RHS.get()->getType()->hasIntegerRepresentation())
8832       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8833 
8834     return InvalidOperands(Loc, LHS, RHS);
8835   }
8836 
8837   ExprResult LHSResult = LHS, RHSResult = RHS;
8838   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8839                                                  IsCompAssign);
8840   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8841     return QualType();
8842   LHS = LHSResult.get();
8843   RHS = RHSResult.get();
8844 
8845   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8846     return compType;
8847   return InvalidOperands(Loc, LHS, RHS);
8848 }
8849 
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,unsigned Opc)8850 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8851   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8852 
8853   // Check vector operands differently.
8854   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8855     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8856 
8857   // Diagnose cases where the user write a logical and/or but probably meant a
8858   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8859   // is a constant.
8860   if (LHS.get()->getType()->isIntegerType() &&
8861       !LHS.get()->getType()->isBooleanType() &&
8862       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8863       // Don't warn in macros or template instantiations.
8864       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8865     // If the RHS can be constant folded, and if it constant folds to something
8866     // that isn't 0 or 1 (which indicate a potential logical operation that
8867     // happened to fold to true/false) then warn.
8868     // Parens on the RHS are ignored.
8869     llvm::APSInt Result;
8870     if (RHS.get()->EvaluateAsInt(Result, Context))
8871       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8872            !RHS.get()->getExprLoc().isMacroID()) ||
8873           (Result != 0 && Result != 1)) {
8874         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8875           << RHS.get()->getSourceRange()
8876           << (Opc == BO_LAnd ? "&&" : "||");
8877         // Suggest replacing the logical operator with the bitwise version
8878         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8879             << (Opc == BO_LAnd ? "&" : "|")
8880             << FixItHint::CreateReplacement(SourceRange(
8881                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8882                                                 getLangOpts())),
8883                                             Opc == BO_LAnd ? "&" : "|");
8884         if (Opc == BO_LAnd)
8885           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8886           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8887               << FixItHint::CreateRemoval(
8888                   SourceRange(
8889                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8890                                                  0, getSourceManager(),
8891                                                  getLangOpts()),
8892                       RHS.get()->getLocEnd()));
8893       }
8894   }
8895 
8896   if (!Context.getLangOpts().CPlusPlus) {
8897     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8898     // not operate on the built-in scalar and vector float types.
8899     if (Context.getLangOpts().OpenCL &&
8900         Context.getLangOpts().OpenCLVersion < 120) {
8901       if (LHS.get()->getType()->isFloatingType() ||
8902           RHS.get()->getType()->isFloatingType())
8903         return InvalidOperands(Loc, LHS, RHS);
8904     }
8905 
8906     LHS = UsualUnaryConversions(LHS.get());
8907     if (LHS.isInvalid())
8908       return QualType();
8909 
8910     RHS = UsualUnaryConversions(RHS.get());
8911     if (RHS.isInvalid())
8912       return QualType();
8913 
8914     if (!LHS.get()->getType()->isScalarType() ||
8915         !RHS.get()->getType()->isScalarType())
8916       return InvalidOperands(Loc, LHS, RHS);
8917 
8918     return Context.IntTy;
8919   }
8920 
8921   // The following is safe because we only use this method for
8922   // non-overloadable operands.
8923 
8924   // C++ [expr.log.and]p1
8925   // C++ [expr.log.or]p1
8926   // The operands are both contextually converted to type bool.
8927   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8928   if (LHSRes.isInvalid())
8929     return InvalidOperands(Loc, LHS, RHS);
8930   LHS = LHSRes;
8931 
8932   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8933   if (RHSRes.isInvalid())
8934     return InvalidOperands(Loc, LHS, RHS);
8935   RHS = RHSRes;
8936 
8937   // C++ [expr.log.and]p2
8938   // C++ [expr.log.or]p2
8939   // The result is a bool.
8940   return Context.BoolTy;
8941 }
8942 
IsReadonlyMessage(Expr * E,Sema & S)8943 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8944   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8945   if (!ME) return false;
8946   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8947   ObjCMessageExpr *Base =
8948     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8949   if (!Base) return false;
8950   return Base->getMethodDecl() != nullptr;
8951 }
8952 
8953 /// Is the given expression (which must be 'const') a reference to a
8954 /// variable which was originally non-const, but which has become
8955 /// 'const' due to being captured within a block?
8956 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)8957 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8958   assert(E->isLValue() && E->getType().isConstQualified());
8959   E = E->IgnoreParens();
8960 
8961   // Must be a reference to a declaration from an enclosing scope.
8962   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8963   if (!DRE) return NCCK_None;
8964   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
8965 
8966   // The declaration must be a variable which is not declared 'const'.
8967   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8968   if (!var) return NCCK_None;
8969   if (var->getType().isConstQualified()) return NCCK_None;
8970   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8971 
8972   // Decide whether the first capture was for a block or a lambda.
8973   DeclContext *DC = S.CurContext, *Prev = nullptr;
8974   while (DC != var->getDeclContext()) {
8975     Prev = DC;
8976     DC = DC->getParent();
8977   }
8978   // Unless we have an init-capture, we've gone one step too far.
8979   if (!var->isInitCapture())
8980     DC = Prev;
8981   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8982 }
8983 
IsTypeModifiable(QualType Ty,bool IsDereference)8984 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
8985   Ty = Ty.getNonReferenceType();
8986   if (IsDereference && Ty->isPointerType())
8987     Ty = Ty->getPointeeType();
8988   return !Ty.isConstQualified();
8989 }
8990 
8991 /// Emit the "read-only variable not assignable" error and print notes to give
8992 /// more information about why the variable is not assignable, such as pointing
8993 /// to the declaration of a const variable, showing that a method is const, or
8994 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)8995 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
8996                                     SourceLocation Loc) {
8997   // Update err_typecheck_assign_const and note_typecheck_assign_const
8998   // when this enum is changed.
8999   enum {
9000     ConstFunction,
9001     ConstVariable,
9002     ConstMember,
9003     ConstMethod,
9004     ConstUnknown,  // Keep as last element
9005   };
9006 
9007   SourceRange ExprRange = E->getSourceRange();
9008 
9009   // Only emit one error on the first const found.  All other consts will emit
9010   // a note to the error.
9011   bool DiagnosticEmitted = false;
9012 
9013   // Track if the current expression is the result of a derefence, and if the
9014   // next checked expression is the result of a derefence.
9015   bool IsDereference = false;
9016   bool NextIsDereference = false;
9017 
9018   // Loop to process MemberExpr chains.
9019   while (true) {
9020     IsDereference = NextIsDereference;
9021     NextIsDereference = false;
9022 
9023     E = E->IgnoreParenImpCasts();
9024     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9025       NextIsDereference = ME->isArrow();
9026       const ValueDecl *VD = ME->getMemberDecl();
9027       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9028         // Mutable fields can be modified even if the class is const.
9029         if (Field->isMutable()) {
9030           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9031           break;
9032         }
9033 
9034         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9035           if (!DiagnosticEmitted) {
9036             S.Diag(Loc, diag::err_typecheck_assign_const)
9037                 << ExprRange << ConstMember << false /*static*/ << Field
9038                 << Field->getType();
9039             DiagnosticEmitted = true;
9040           }
9041           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9042               << ConstMember << false /*static*/ << Field << Field->getType()
9043               << Field->getSourceRange();
9044         }
9045         E = ME->getBase();
9046         continue;
9047       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9048         if (VDecl->getType().isConstQualified()) {
9049           if (!DiagnosticEmitted) {
9050             S.Diag(Loc, diag::err_typecheck_assign_const)
9051                 << ExprRange << ConstMember << true /*static*/ << VDecl
9052                 << VDecl->getType();
9053             DiagnosticEmitted = true;
9054           }
9055           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9056               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9057               << VDecl->getSourceRange();
9058         }
9059         // Static fields do not inherit constness from parents.
9060         break;
9061       }
9062       break;
9063     } // End MemberExpr
9064     break;
9065   }
9066 
9067   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9068     // Function calls
9069     const FunctionDecl *FD = CE->getDirectCallee();
9070     if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9071       if (!DiagnosticEmitted) {
9072         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9073                                                       << ConstFunction << FD;
9074         DiagnosticEmitted = true;
9075       }
9076       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9077              diag::note_typecheck_assign_const)
9078           << ConstFunction << FD << FD->getReturnType()
9079           << FD->getReturnTypeSourceRange();
9080     }
9081   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9082     // Point to variable declaration.
9083     if (const ValueDecl *VD = DRE->getDecl()) {
9084       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9085         if (!DiagnosticEmitted) {
9086           S.Diag(Loc, diag::err_typecheck_assign_const)
9087               << ExprRange << ConstVariable << VD << VD->getType();
9088           DiagnosticEmitted = true;
9089         }
9090         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9091             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9092       }
9093     }
9094   } else if (isa<CXXThisExpr>(E)) {
9095     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9096       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9097         if (MD->isConst()) {
9098           if (!DiagnosticEmitted) {
9099             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9100                                                           << ConstMethod << MD;
9101             DiagnosticEmitted = true;
9102           }
9103           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9104               << ConstMethod << MD << MD->getSourceRange();
9105         }
9106       }
9107     }
9108   }
9109 
9110   if (DiagnosticEmitted)
9111     return;
9112 
9113   // Can't determine a more specific message, so display the generic error.
9114   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9115 }
9116 
9117 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9118 /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)9119 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9120   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9121   SourceLocation OrigLoc = Loc;
9122   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9123                                                               &Loc);
9124   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9125     IsLV = Expr::MLV_InvalidMessageExpression;
9126   if (IsLV == Expr::MLV_Valid)
9127     return false;
9128 
9129   unsigned DiagID = 0;
9130   bool NeedType = false;
9131   switch (IsLV) { // C99 6.5.16p2
9132   case Expr::MLV_ConstQualified:
9133     // Use a specialized diagnostic when we're assigning to an object
9134     // from an enclosing function or block.
9135     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9136       if (NCCK == NCCK_Block)
9137         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9138       else
9139         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9140       break;
9141     }
9142 
9143     // In ARC, use some specialized diagnostics for occasions where we
9144     // infer 'const'.  These are always pseudo-strong variables.
9145     if (S.getLangOpts().ObjCAutoRefCount) {
9146       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9147       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9148         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9149 
9150         // Use the normal diagnostic if it's pseudo-__strong but the
9151         // user actually wrote 'const'.
9152         if (var->isARCPseudoStrong() &&
9153             (!var->getTypeSourceInfo() ||
9154              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9155           // There are two pseudo-strong cases:
9156           //  - self
9157           ObjCMethodDecl *method = S.getCurMethodDecl();
9158           if (method && var == method->getSelfDecl())
9159             DiagID = method->isClassMethod()
9160               ? diag::err_typecheck_arc_assign_self_class_method
9161               : diag::err_typecheck_arc_assign_self;
9162 
9163           //  - fast enumeration variables
9164           else
9165             DiagID = diag::err_typecheck_arr_assign_enumeration;
9166 
9167           SourceRange Assign;
9168           if (Loc != OrigLoc)
9169             Assign = SourceRange(OrigLoc, OrigLoc);
9170           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9171           // We need to preserve the AST regardless, so migration tool
9172           // can do its job.
9173           return false;
9174         }
9175       }
9176     }
9177 
9178     // If none of the special cases above are triggered, then this is a
9179     // simple const assignment.
9180     if (DiagID == 0) {
9181       DiagnoseConstAssignment(S, E, Loc);
9182       return true;
9183     }
9184 
9185     break;
9186   case Expr::MLV_ArrayType:
9187   case Expr::MLV_ArrayTemporary:
9188     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9189     NeedType = true;
9190     break;
9191   case Expr::MLV_NotObjectType:
9192     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9193     NeedType = true;
9194     break;
9195   case Expr::MLV_LValueCast:
9196     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9197     break;
9198   case Expr::MLV_Valid:
9199     llvm_unreachable("did not take early return for MLV_Valid");
9200   case Expr::MLV_InvalidExpression:
9201   case Expr::MLV_MemberFunction:
9202   case Expr::MLV_ClassTemporary:
9203     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9204     break;
9205   case Expr::MLV_IncompleteType:
9206   case Expr::MLV_IncompleteVoidType:
9207     return S.RequireCompleteType(Loc, E->getType(),
9208              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9209   case Expr::MLV_DuplicateVectorComponents:
9210     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9211     break;
9212   case Expr::MLV_NoSetterProperty:
9213     llvm_unreachable("readonly properties should be processed differently");
9214   case Expr::MLV_InvalidMessageExpression:
9215     DiagID = diag::error_readonly_message_assignment;
9216     break;
9217   case Expr::MLV_SubObjCPropertySetting:
9218     DiagID = diag::error_no_subobject_property_setting;
9219     break;
9220   }
9221 
9222   SourceRange Assign;
9223   if (Loc != OrigLoc)
9224     Assign = SourceRange(OrigLoc, OrigLoc);
9225   if (NeedType)
9226     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9227   else
9228     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9229   return true;
9230 }
9231 
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)9232 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9233                                          SourceLocation Loc,
9234                                          Sema &Sema) {
9235   // C / C++ fields
9236   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9237   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9238   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9239     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9240       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9241   }
9242 
9243   // Objective-C instance variables
9244   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9245   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9246   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9247     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9248     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9249     if (RL && RR && RL->getDecl() == RR->getDecl())
9250       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9251   }
9252 }
9253 
9254 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)9255 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9256                                        SourceLocation Loc,
9257                                        QualType CompoundType) {
9258   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9259 
9260   // Verify that LHS is a modifiable lvalue, and emit error if not.
9261   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9262     return QualType();
9263 
9264   QualType LHSType = LHSExpr->getType();
9265   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9266                                              CompoundType;
9267   AssignConvertType ConvTy;
9268   if (CompoundType.isNull()) {
9269     Expr *RHSCheck = RHS.get();
9270 
9271     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9272 
9273     QualType LHSTy(LHSType);
9274     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9275     if (RHS.isInvalid())
9276       return QualType();
9277     // Special case of NSObject attributes on c-style pointer types.
9278     if (ConvTy == IncompatiblePointer &&
9279         ((Context.isObjCNSObjectType(LHSType) &&
9280           RHSType->isObjCObjectPointerType()) ||
9281          (Context.isObjCNSObjectType(RHSType) &&
9282           LHSType->isObjCObjectPointerType())))
9283       ConvTy = Compatible;
9284 
9285     if (ConvTy == Compatible &&
9286         LHSType->isObjCObjectType())
9287         Diag(Loc, diag::err_objc_object_assignment)
9288           << LHSType;
9289 
9290     // If the RHS is a unary plus or minus, check to see if they = and + are
9291     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9292     // instead of "x += 4".
9293     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9294       RHSCheck = ICE->getSubExpr();
9295     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9296       if ((UO->getOpcode() == UO_Plus ||
9297            UO->getOpcode() == UO_Minus) &&
9298           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9299           // Only if the two operators are exactly adjacent.
9300           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9301           // And there is a space or other character before the subexpr of the
9302           // unary +/-.  We don't want to warn on "x=-1".
9303           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9304           UO->getSubExpr()->getLocStart().isFileID()) {
9305         Diag(Loc, diag::warn_not_compound_assign)
9306           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9307           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9308       }
9309     }
9310 
9311     if (ConvTy == Compatible) {
9312       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9313         // Warn about retain cycles where a block captures the LHS, but
9314         // not if the LHS is a simple variable into which the block is
9315         // being stored...unless that variable can be captured by reference!
9316         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9317         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9318         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9319           checkRetainCycles(LHSExpr, RHS.get());
9320 
9321         // It is safe to assign a weak reference into a strong variable.
9322         // Although this code can still have problems:
9323         //   id x = self.weakProp;
9324         //   id y = self.weakProp;
9325         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9326         // paths through the function. This should be revisited if
9327         // -Wrepeated-use-of-weak is made flow-sensitive.
9328         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9329                              RHS.get()->getLocStart()))
9330           getCurFunction()->markSafeWeakUse(RHS.get());
9331 
9332       } else if (getLangOpts().ObjCAutoRefCount) {
9333         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9334       }
9335     }
9336   } else {
9337     // Compound assignment "x += y"
9338     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9339   }
9340 
9341   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9342                                RHS.get(), AA_Assigning))
9343     return QualType();
9344 
9345   CheckForNullPointerDereference(*this, LHSExpr);
9346 
9347   // C99 6.5.16p3: The type of an assignment expression is the type of the
9348   // left operand unless the left operand has qualified type, in which case
9349   // it is the unqualified version of the type of the left operand.
9350   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9351   // is converted to the type of the assignment expression (above).
9352   // C++ 5.17p1: the type of the assignment expression is that of its left
9353   // operand.
9354   return (getLangOpts().CPlusPlus
9355           ? LHSType : LHSType.getUnqualifiedType());
9356 }
9357 
9358 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)9359 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9360                                    SourceLocation Loc) {
9361   LHS = S.CheckPlaceholderExpr(LHS.get());
9362   RHS = S.CheckPlaceholderExpr(RHS.get());
9363   if (LHS.isInvalid() || RHS.isInvalid())
9364     return QualType();
9365 
9366   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9367   // operands, but not unary promotions.
9368   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9369 
9370   // So we treat the LHS as a ignored value, and in C++ we allow the
9371   // containing site to determine what should be done with the RHS.
9372   LHS = S.IgnoredValueConversions(LHS.get());
9373   if (LHS.isInvalid())
9374     return QualType();
9375 
9376   S.DiagnoseUnusedExprResult(LHS.get());
9377 
9378   if (!S.getLangOpts().CPlusPlus) {
9379     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9380     if (RHS.isInvalid())
9381       return QualType();
9382     if (!RHS.get()->getType()->isVoidType())
9383       S.RequireCompleteType(Loc, RHS.get()->getType(),
9384                             diag::err_incomplete_type);
9385   }
9386 
9387   return RHS.get()->getType();
9388 }
9389 
9390 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9391 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)9392 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9393                                                ExprValueKind &VK,
9394                                                ExprObjectKind &OK,
9395                                                SourceLocation OpLoc,
9396                                                bool IsInc, bool IsPrefix) {
9397   if (Op->isTypeDependent())
9398     return S.Context.DependentTy;
9399 
9400   QualType ResType = Op->getType();
9401   // Atomic types can be used for increment / decrement where the non-atomic
9402   // versions can, so ignore the _Atomic() specifier for the purpose of
9403   // checking.
9404   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9405     ResType = ResAtomicType->getValueType();
9406 
9407   assert(!ResType.isNull() && "no type for increment/decrement expression");
9408 
9409   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9410     // Decrement of bool is not allowed.
9411     if (!IsInc) {
9412       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9413       return QualType();
9414     }
9415     // Increment of bool sets it to true, but is deprecated.
9416     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
9417   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9418     // Error on enum increments and decrements in C++ mode
9419     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9420     return QualType();
9421   } else if (ResType->isRealType()) {
9422     // OK!
9423   } else if (ResType->isPointerType()) {
9424     // C99 6.5.2.4p2, 6.5.6p2
9425     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9426       return QualType();
9427   } else if (ResType->isObjCObjectPointerType()) {
9428     // On modern runtimes, ObjC pointer arithmetic is forbidden.
9429     // Otherwise, we just need a complete type.
9430     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9431         checkArithmeticOnObjCPointer(S, OpLoc, Op))
9432       return QualType();
9433   } else if (ResType->isAnyComplexType()) {
9434     // C99 does not support ++/-- on complex types, we allow as an extension.
9435     S.Diag(OpLoc, diag::ext_integer_increment_complex)
9436       << ResType << Op->getSourceRange();
9437   } else if (ResType->isPlaceholderType()) {
9438     ExprResult PR = S.CheckPlaceholderExpr(Op);
9439     if (PR.isInvalid()) return QualType();
9440     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9441                                           IsInc, IsPrefix);
9442   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9443     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9444   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9445             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9446     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9447   } else {
9448     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9449       << ResType << int(IsInc) << Op->getSourceRange();
9450     return QualType();
9451   }
9452   // At this point, we know we have a real, complex or pointer type.
9453   // Now make sure the operand is a modifiable lvalue.
9454   if (CheckForModifiableLvalue(Op, OpLoc, S))
9455     return QualType();
9456   // In C++, a prefix increment is the same type as the operand. Otherwise
9457   // (in C or with postfix), the increment is the unqualified type of the
9458   // operand.
9459   if (IsPrefix && S.getLangOpts().CPlusPlus) {
9460     VK = VK_LValue;
9461     OK = Op->getObjectKind();
9462     return ResType;
9463   } else {
9464     VK = VK_RValue;
9465     return ResType.getUnqualifiedType();
9466   }
9467 }
9468 
9469 
9470 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9471 /// This routine allows us to typecheck complex/recursive expressions
9472 /// where the declaration is needed for type checking. We only need to
9473 /// handle cases when the expression references a function designator
9474 /// or is an lvalue. Here are some examples:
9475 ///  - &(x) => x
9476 ///  - &*****f => f for f a function designator.
9477 ///  - &s.xx => s
9478 ///  - &s.zz[1].yy -> s, if zz is an array
9479 ///  - *(x + 1) -> x, if x is an array
9480 ///  - &"123"[2] -> 0
9481 ///  - & __real__ x -> x
getPrimaryDecl(Expr * E)9482 static ValueDecl *getPrimaryDecl(Expr *E) {
9483   switch (E->getStmtClass()) {
9484   case Stmt::DeclRefExprClass:
9485     return cast<DeclRefExpr>(E)->getDecl();
9486   case Stmt::MemberExprClass:
9487     // If this is an arrow operator, the address is an offset from
9488     // the base's value, so the object the base refers to is
9489     // irrelevant.
9490     if (cast<MemberExpr>(E)->isArrow())
9491       return nullptr;
9492     // Otherwise, the expression refers to a part of the base
9493     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9494   case Stmt::ArraySubscriptExprClass: {
9495     // FIXME: This code shouldn't be necessary!  We should catch the implicit
9496     // promotion of register arrays earlier.
9497     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9498     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9499       if (ICE->getSubExpr()->getType()->isArrayType())
9500         return getPrimaryDecl(ICE->getSubExpr());
9501     }
9502     return nullptr;
9503   }
9504   case Stmt::UnaryOperatorClass: {
9505     UnaryOperator *UO = cast<UnaryOperator>(E);
9506 
9507     switch(UO->getOpcode()) {
9508     case UO_Real:
9509     case UO_Imag:
9510     case UO_Extension:
9511       return getPrimaryDecl(UO->getSubExpr());
9512     default:
9513       return nullptr;
9514     }
9515   }
9516   case Stmt::ParenExprClass:
9517     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9518   case Stmt::ImplicitCastExprClass:
9519     // If the result of an implicit cast is an l-value, we care about
9520     // the sub-expression; otherwise, the result here doesn't matter.
9521     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9522   default:
9523     return nullptr;
9524   }
9525 }
9526 
9527 namespace {
9528   enum {
9529     AO_Bit_Field = 0,
9530     AO_Vector_Element = 1,
9531     AO_Property_Expansion = 2,
9532     AO_Register_Variable = 3,
9533     AO_No_Error = 4
9534   };
9535 }
9536 /// \brief Diagnose invalid operand for address of operations.
9537 ///
9538 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)9539 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9540                                          Expr *E, unsigned Type) {
9541   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9542 }
9543 
9544 /// CheckAddressOfOperand - The operand of & must be either a function
9545 /// designator or an lvalue designating an object. If it is an lvalue, the
9546 /// object cannot be declared with storage class register or be a bit field.
9547 /// Note: The usual conversions are *not* applied to the operand of the &
9548 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9549 /// In C++, the operand might be an overloaded function name, in which case
9550 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)9551 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9552   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9553     if (PTy->getKind() == BuiltinType::Overload) {
9554       Expr *E = OrigOp.get()->IgnoreParens();
9555       if (!isa<OverloadExpr>(E)) {
9556         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9557         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9558           << OrigOp.get()->getSourceRange();
9559         return QualType();
9560       }
9561 
9562       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9563       if (isa<UnresolvedMemberExpr>(Ovl))
9564         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9565           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9566             << OrigOp.get()->getSourceRange();
9567           return QualType();
9568         }
9569 
9570       return Context.OverloadTy;
9571     }
9572 
9573     if (PTy->getKind() == BuiltinType::UnknownAny)
9574       return Context.UnknownAnyTy;
9575 
9576     if (PTy->getKind() == BuiltinType::BoundMember) {
9577       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9578         << OrigOp.get()->getSourceRange();
9579       return QualType();
9580     }
9581 
9582     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9583     if (OrigOp.isInvalid()) return QualType();
9584   }
9585 
9586   if (OrigOp.get()->isTypeDependent())
9587     return Context.DependentTy;
9588 
9589   assert(!OrigOp.get()->getType()->isPlaceholderType());
9590 
9591   // Make sure to ignore parentheses in subsequent checks
9592   Expr *op = OrigOp.get()->IgnoreParens();
9593 
9594   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9595   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9596     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9597     return QualType();
9598   }
9599 
9600   if (getLangOpts().C99) {
9601     // Implement C99-only parts of addressof rules.
9602     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9603       if (uOp->getOpcode() == UO_Deref)
9604         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9605         // (assuming the deref expression is valid).
9606         return uOp->getSubExpr()->getType();
9607     }
9608     // Technically, there should be a check for array subscript
9609     // expressions here, but the result of one is always an lvalue anyway.
9610   }
9611   ValueDecl *dcl = getPrimaryDecl(op);
9612   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9613   unsigned AddressOfError = AO_No_Error;
9614 
9615   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9616     bool sfinae = (bool)isSFINAEContext();
9617     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9618                                   : diag::ext_typecheck_addrof_temporary)
9619       << op->getType() << op->getSourceRange();
9620     if (sfinae)
9621       return QualType();
9622     // Materialize the temporary as an lvalue so that we can take its address.
9623     OrigOp = op = new (Context)
9624         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9625   } else if (isa<ObjCSelectorExpr>(op)) {
9626     return Context.getPointerType(op->getType());
9627   } else if (lval == Expr::LV_MemberFunction) {
9628     // If it's an instance method, make a member pointer.
9629     // The expression must have exactly the form &A::foo.
9630 
9631     // If the underlying expression isn't a decl ref, give up.
9632     if (!isa<DeclRefExpr>(op)) {
9633       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9634         << OrigOp.get()->getSourceRange();
9635       return QualType();
9636     }
9637     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9638     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9639 
9640     // The id-expression was parenthesized.
9641     if (OrigOp.get() != DRE) {
9642       Diag(OpLoc, diag::err_parens_pointer_member_function)
9643         << OrigOp.get()->getSourceRange();
9644 
9645     // The method was named without a qualifier.
9646     } else if (!DRE->getQualifier()) {
9647       if (MD->getParent()->getName().empty())
9648         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9649           << op->getSourceRange();
9650       else {
9651         SmallString<32> Str;
9652         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9653         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9654           << op->getSourceRange()
9655           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9656       }
9657     }
9658 
9659     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9660     if (isa<CXXDestructorDecl>(MD))
9661       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9662 
9663     QualType MPTy = Context.getMemberPointerType(
9664         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9665     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9666       RequireCompleteType(OpLoc, MPTy, 0);
9667     return MPTy;
9668   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9669     // C99 6.5.3.2p1
9670     // The operand must be either an l-value or a function designator
9671     if (!op->getType()->isFunctionType()) {
9672       // Use a special diagnostic for loads from property references.
9673       if (isa<PseudoObjectExpr>(op)) {
9674         AddressOfError = AO_Property_Expansion;
9675       } else {
9676         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9677           << op->getType() << op->getSourceRange();
9678         return QualType();
9679       }
9680     }
9681   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9682     // The operand cannot be a bit-field
9683     AddressOfError = AO_Bit_Field;
9684   } else if (op->getObjectKind() == OK_VectorComponent) {
9685     // The operand cannot be an element of a vector
9686     AddressOfError = AO_Vector_Element;
9687   } else if (dcl) { // C99 6.5.3.2p1
9688     // We have an lvalue with a decl. Make sure the decl is not declared
9689     // with the register storage-class specifier.
9690     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9691       // in C++ it is not error to take address of a register
9692       // variable (c++03 7.1.1P3)
9693       if (vd->getStorageClass() == SC_Register &&
9694           !getLangOpts().CPlusPlus) {
9695         AddressOfError = AO_Register_Variable;
9696       }
9697     } else if (isa<MSPropertyDecl>(dcl)) {
9698       AddressOfError = AO_Property_Expansion;
9699     } else if (isa<FunctionTemplateDecl>(dcl)) {
9700       return Context.OverloadTy;
9701     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9702       // Okay: we can take the address of a field.
9703       // Could be a pointer to member, though, if there is an explicit
9704       // scope qualifier for the class.
9705       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9706         DeclContext *Ctx = dcl->getDeclContext();
9707         if (Ctx && Ctx->isRecord()) {
9708           if (dcl->getType()->isReferenceType()) {
9709             Diag(OpLoc,
9710                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9711               << dcl->getDeclName() << dcl->getType();
9712             return QualType();
9713           }
9714 
9715           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9716             Ctx = Ctx->getParent();
9717 
9718           QualType MPTy = Context.getMemberPointerType(
9719               op->getType(),
9720               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9721           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9722             RequireCompleteType(OpLoc, MPTy, 0);
9723           return MPTy;
9724         }
9725       }
9726     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9727       llvm_unreachable("Unknown/unexpected decl type");
9728   }
9729 
9730   if (AddressOfError != AO_No_Error) {
9731     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9732     return QualType();
9733   }
9734 
9735   if (lval == Expr::LV_IncompleteVoidType) {
9736     // Taking the address of a void variable is technically illegal, but we
9737     // allow it in cases which are otherwise valid.
9738     // Example: "extern void x; void* y = &x;".
9739     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9740   }
9741 
9742   // If the operand has type "type", the result has type "pointer to type".
9743   if (op->getType()->isObjCObjectType())
9744     return Context.getObjCObjectPointerType(op->getType());
9745   return Context.getPointerType(op->getType());
9746 }
9747 
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)9748 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9749   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9750   if (!DRE)
9751     return;
9752   const Decl *D = DRE->getDecl();
9753   if (!D)
9754     return;
9755   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
9756   if (!Param)
9757     return;
9758   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
9759     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
9760       return;
9761   if (FunctionScopeInfo *FD = S.getCurFunction())
9762     if (!FD->ModifiedNonNullParams.count(Param))
9763       FD->ModifiedNonNullParams.insert(Param);
9764 }
9765 
9766 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)9767 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9768                                         SourceLocation OpLoc) {
9769   if (Op->isTypeDependent())
9770     return S.Context.DependentTy;
9771 
9772   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9773   if (ConvResult.isInvalid())
9774     return QualType();
9775   Op = ConvResult.get();
9776   QualType OpTy = Op->getType();
9777   QualType Result;
9778 
9779   if (isa<CXXReinterpretCastExpr>(Op)) {
9780     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9781     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9782                                      Op->getSourceRange());
9783   }
9784 
9785   if (const PointerType *PT = OpTy->getAs<PointerType>())
9786     Result = PT->getPointeeType();
9787   else if (const ObjCObjectPointerType *OPT =
9788              OpTy->getAs<ObjCObjectPointerType>())
9789     Result = OPT->getPointeeType();
9790   else {
9791     ExprResult PR = S.CheckPlaceholderExpr(Op);
9792     if (PR.isInvalid()) return QualType();
9793     if (PR.get() != Op)
9794       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9795   }
9796 
9797   if (Result.isNull()) {
9798     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9799       << OpTy << Op->getSourceRange();
9800     return QualType();
9801   }
9802 
9803   // Note that per both C89 and C99, indirection is always legal, even if Result
9804   // is an incomplete type or void.  It would be possible to warn about
9805   // dereferencing a void pointer, but it's completely well-defined, and such a
9806   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9807   // for pointers to 'void' but is fine for any other pointer type:
9808   //
9809   // C++ [expr.unary.op]p1:
9810   //   [...] the expression to which [the unary * operator] is applied shall
9811   //   be a pointer to an object type, or a pointer to a function type
9812   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9813     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9814       << OpTy << Op->getSourceRange();
9815 
9816   // Dereferences are usually l-values...
9817   VK = VK_LValue;
9818 
9819   // ...except that certain expressions are never l-values in C.
9820   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9821     VK = VK_RValue;
9822 
9823   return Result;
9824 }
9825 
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)9826 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
9827   BinaryOperatorKind Opc;
9828   switch (Kind) {
9829   default: llvm_unreachable("Unknown binop!");
9830   case tok::periodstar:           Opc = BO_PtrMemD; break;
9831   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9832   case tok::star:                 Opc = BO_Mul; break;
9833   case tok::slash:                Opc = BO_Div; break;
9834   case tok::percent:              Opc = BO_Rem; break;
9835   case tok::plus:                 Opc = BO_Add; break;
9836   case tok::minus:                Opc = BO_Sub; break;
9837   case tok::lessless:             Opc = BO_Shl; break;
9838   case tok::greatergreater:       Opc = BO_Shr; break;
9839   case tok::lessequal:            Opc = BO_LE; break;
9840   case tok::less:                 Opc = BO_LT; break;
9841   case tok::greaterequal:         Opc = BO_GE; break;
9842   case tok::greater:              Opc = BO_GT; break;
9843   case tok::exclaimequal:         Opc = BO_NE; break;
9844   case tok::equalequal:           Opc = BO_EQ; break;
9845   case tok::amp:                  Opc = BO_And; break;
9846   case tok::caret:                Opc = BO_Xor; break;
9847   case tok::pipe:                 Opc = BO_Or; break;
9848   case tok::ampamp:               Opc = BO_LAnd; break;
9849   case tok::pipepipe:             Opc = BO_LOr; break;
9850   case tok::equal:                Opc = BO_Assign; break;
9851   case tok::starequal:            Opc = BO_MulAssign; break;
9852   case tok::slashequal:           Opc = BO_DivAssign; break;
9853   case tok::percentequal:         Opc = BO_RemAssign; break;
9854   case tok::plusequal:            Opc = BO_AddAssign; break;
9855   case tok::minusequal:           Opc = BO_SubAssign; break;
9856   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9857   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9858   case tok::ampequal:             Opc = BO_AndAssign; break;
9859   case tok::caretequal:           Opc = BO_XorAssign; break;
9860   case tok::pipeequal:            Opc = BO_OrAssign; break;
9861   case tok::comma:                Opc = BO_Comma; break;
9862   }
9863   return Opc;
9864 }
9865 
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)9866 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9867   tok::TokenKind Kind) {
9868   UnaryOperatorKind Opc;
9869   switch (Kind) {
9870   default: llvm_unreachable("Unknown unary op!");
9871   case tok::plusplus:     Opc = UO_PreInc; break;
9872   case tok::minusminus:   Opc = UO_PreDec; break;
9873   case tok::amp:          Opc = UO_AddrOf; break;
9874   case tok::star:         Opc = UO_Deref; break;
9875   case tok::plus:         Opc = UO_Plus; break;
9876   case tok::minus:        Opc = UO_Minus; break;
9877   case tok::tilde:        Opc = UO_Not; break;
9878   case tok::exclaim:      Opc = UO_LNot; break;
9879   case tok::kw___real:    Opc = UO_Real; break;
9880   case tok::kw___imag:    Opc = UO_Imag; break;
9881   case tok::kw___extension__: Opc = UO_Extension; break;
9882   }
9883   return Opc;
9884 }
9885 
9886 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9887 /// This warning is only emitted for builtin assignment operations. It is also
9888 /// suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc)9889 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9890                                    SourceLocation OpLoc) {
9891   if (!S.ActiveTemplateInstantiations.empty())
9892     return;
9893   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9894     return;
9895   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9896   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9897   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9898   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9899   if (!LHSDeclRef || !RHSDeclRef ||
9900       LHSDeclRef->getLocation().isMacroID() ||
9901       RHSDeclRef->getLocation().isMacroID())
9902     return;
9903   const ValueDecl *LHSDecl =
9904     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9905   const ValueDecl *RHSDecl =
9906     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9907   if (LHSDecl != RHSDecl)
9908     return;
9909   if (LHSDecl->getType().isVolatileQualified())
9910     return;
9911   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9912     if (RefTy->getPointeeType().isVolatileQualified())
9913       return;
9914 
9915   S.Diag(OpLoc, diag::warn_self_assignment)
9916       << LHSDeclRef->getType()
9917       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9918 }
9919 
9920 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9921 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)9922 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9923                                           SourceLocation OpLoc) {
9924   if (!S.getLangOpts().ObjC1)
9925     return;
9926 
9927   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9928   const Expr *LHS = L.get();
9929   const Expr *RHS = R.get();
9930 
9931   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9932     ObjCPointerExpr = LHS;
9933     OtherExpr = RHS;
9934   }
9935   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9936     ObjCPointerExpr = RHS;
9937     OtherExpr = LHS;
9938   }
9939 
9940   // This warning is deliberately made very specific to reduce false
9941   // positives with logic that uses '&' for hashing.  This logic mainly
9942   // looks for code trying to introspect into tagged pointers, which
9943   // code should generally never do.
9944   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9945     unsigned Diag = diag::warn_objc_pointer_masking;
9946     // Determine if we are introspecting the result of performSelectorXXX.
9947     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9948     // Special case messages to -performSelector and friends, which
9949     // can return non-pointer values boxed in a pointer value.
9950     // Some clients may wish to silence warnings in this subcase.
9951     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9952       Selector S = ME->getSelector();
9953       StringRef SelArg0 = S.getNameForSlot(0);
9954       if (SelArg0.startswith("performSelector"))
9955         Diag = diag::warn_objc_pointer_masking_performSelector;
9956     }
9957 
9958     S.Diag(OpLoc, Diag)
9959       << ObjCPointerExpr->getSourceRange();
9960   }
9961 }
9962 
getDeclFromExpr(Expr * E)9963 static NamedDecl *getDeclFromExpr(Expr *E) {
9964   if (!E)
9965     return nullptr;
9966   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
9967     return DRE->getDecl();
9968   if (auto *ME = dyn_cast<MemberExpr>(E))
9969     return ME->getMemberDecl();
9970   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
9971     return IRE->getDecl();
9972   return nullptr;
9973 }
9974 
9975 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9976 /// operator @p Opc at location @c TokLoc. This routine only supports
9977 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)9978 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9979                                     BinaryOperatorKind Opc,
9980                                     Expr *LHSExpr, Expr *RHSExpr) {
9981   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9982     // The syntax only allows initializer lists on the RHS of assignment,
9983     // so we don't need to worry about accepting invalid code for
9984     // non-assignment operators.
9985     // C++11 5.17p9:
9986     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9987     //   of x = {} is x = T().
9988     InitializationKind Kind =
9989         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9990     InitializedEntity Entity =
9991         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9992     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9993     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9994     if (Init.isInvalid())
9995       return Init;
9996     RHSExpr = Init.get();
9997   }
9998 
9999   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10000   QualType ResultTy;     // Result type of the binary operator.
10001   // The following two variables are used for compound assignment operators
10002   QualType CompLHSTy;    // Type of LHS after promotions for computation
10003   QualType CompResultTy; // Type of computation result
10004   ExprValueKind VK = VK_RValue;
10005   ExprObjectKind OK = OK_Ordinary;
10006 
10007   if (!getLangOpts().CPlusPlus) {
10008     // C cannot handle TypoExpr nodes on either side of a binop because it
10009     // doesn't handle dependent types properly, so make sure any TypoExprs have
10010     // been dealt with before checking the operands.
10011     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10012     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10013       if (Opc != BO_Assign)
10014         return ExprResult(E);
10015       // Avoid correcting the RHS to the same Expr as the LHS.
10016       Decl *D = getDeclFromExpr(E);
10017       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10018     });
10019     if (!LHS.isUsable() || !RHS.isUsable())
10020       return ExprError();
10021   }
10022 
10023   switch (Opc) {
10024   case BO_Assign:
10025     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10026     if (getLangOpts().CPlusPlus &&
10027         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10028       VK = LHS.get()->getValueKind();
10029       OK = LHS.get()->getObjectKind();
10030     }
10031     if (!ResultTy.isNull()) {
10032       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10033       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10034     }
10035     RecordModifiableNonNullParam(*this, LHS.get());
10036     break;
10037   case BO_PtrMemD:
10038   case BO_PtrMemI:
10039     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10040                                             Opc == BO_PtrMemI);
10041     break;
10042   case BO_Mul:
10043   case BO_Div:
10044     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10045                                            Opc == BO_Div);
10046     break;
10047   case BO_Rem:
10048     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10049     break;
10050   case BO_Add:
10051     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10052     break;
10053   case BO_Sub:
10054     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10055     break;
10056   case BO_Shl:
10057   case BO_Shr:
10058     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10059     break;
10060   case BO_LE:
10061   case BO_LT:
10062   case BO_GE:
10063   case BO_GT:
10064     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10065     break;
10066   case BO_EQ:
10067   case BO_NE:
10068     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10069     break;
10070   case BO_And:
10071     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10072   case BO_Xor:
10073   case BO_Or:
10074     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10075     break;
10076   case BO_LAnd:
10077   case BO_LOr:
10078     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10079     break;
10080   case BO_MulAssign:
10081   case BO_DivAssign:
10082     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10083                                                Opc == BO_DivAssign);
10084     CompLHSTy = CompResultTy;
10085     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10086       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10087     break;
10088   case BO_RemAssign:
10089     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10090     CompLHSTy = CompResultTy;
10091     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10092       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10093     break;
10094   case BO_AddAssign:
10095     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10096     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10097       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10098     break;
10099   case BO_SubAssign:
10100     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10101     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10102       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10103     break;
10104   case BO_ShlAssign:
10105   case BO_ShrAssign:
10106     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10107     CompLHSTy = CompResultTy;
10108     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10109       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10110     break;
10111   case BO_AndAssign:
10112   case BO_OrAssign: // fallthrough
10113 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10114   case BO_XorAssign:
10115     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10116     CompLHSTy = CompResultTy;
10117     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10118       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10119     break;
10120   case BO_Comma:
10121     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10122     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10123       VK = RHS.get()->getValueKind();
10124       OK = RHS.get()->getObjectKind();
10125     }
10126     break;
10127   }
10128   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10129     return ExprError();
10130 
10131   // Check for array bounds violations for both sides of the BinaryOperator
10132   CheckArrayAccess(LHS.get());
10133   CheckArrayAccess(RHS.get());
10134 
10135   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10136     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10137                                                  &Context.Idents.get("object_setClass"),
10138                                                  SourceLocation(), LookupOrdinaryName);
10139     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10140       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
10141       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10142       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10143       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10144       FixItHint::CreateInsertion(RHSLocEnd, ")");
10145     }
10146     else
10147       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10148   }
10149   else if (const ObjCIvarRefExpr *OIRE =
10150            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10151     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10152 
10153   if (CompResultTy.isNull())
10154     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10155                                         OK, OpLoc, FPFeatures.fp_contract);
10156   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10157       OK_ObjCProperty) {
10158     VK = VK_LValue;
10159     OK = LHS.get()->getObjectKind();
10160   }
10161   return new (Context) CompoundAssignOperator(
10162       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10163       OpLoc, FPFeatures.fp_contract);
10164 }
10165 
10166 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10167 /// operators are mixed in a way that suggests that the programmer forgot that
10168 /// comparison operators have higher precedence. The most typical example of
10169 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10170 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10171                                       SourceLocation OpLoc, Expr *LHSExpr,
10172                                       Expr *RHSExpr) {
10173   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10174   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10175 
10176   // Check that one of the sides is a comparison operator.
10177   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10178   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10179   if (!isLeftComp && !isRightComp)
10180     return;
10181 
10182   // Bitwise operations are sometimes used as eager logical ops.
10183   // Don't diagnose this.
10184   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10185   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10186   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
10187     return;
10188 
10189   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10190                                                    OpLoc)
10191                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10192   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10193   SourceRange ParensRange = isLeftComp ?
10194       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10195     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10196 
10197   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10198     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10199   SuggestParentheses(Self, OpLoc,
10200     Self.PDiag(diag::note_precedence_silence) << OpStr,
10201     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10202   SuggestParentheses(Self, OpLoc,
10203     Self.PDiag(diag::note_precedence_bitwise_first)
10204       << BinaryOperator::getOpcodeStr(Opc),
10205     ParensRange);
10206 }
10207 
10208 /// \brief It accepts a '&' expr that is inside a '|' one.
10209 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
10210 /// in parentheses.
10211 static void
EmitDiagnosticForBitwiseAndInBitwiseOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)10212 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
10213                                        BinaryOperator *Bop) {
10214   assert(Bop->getOpcode() == BO_And);
10215   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
10216       << Bop->getSourceRange() << OpLoc;
10217   SuggestParentheses(Self, Bop->getOperatorLoc(),
10218     Self.PDiag(diag::note_precedence_silence)
10219       << Bop->getOpcodeStr(),
10220     Bop->getSourceRange());
10221 }
10222 
10223 /// \brief It accepts a '&&' expr that is inside a '||' one.
10224 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10225 /// in parentheses.
10226 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)10227 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10228                                        BinaryOperator *Bop) {
10229   assert(Bop->getOpcode() == BO_LAnd);
10230   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10231       << Bop->getSourceRange() << OpLoc;
10232   SuggestParentheses(Self, Bop->getOperatorLoc(),
10233     Self.PDiag(diag::note_precedence_silence)
10234       << Bop->getOpcodeStr(),
10235     Bop->getSourceRange());
10236 }
10237 
10238 /// \brief Returns true if the given expression can be evaluated as a constant
10239 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)10240 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10241   bool Res;
10242   return !E->isValueDependent() &&
10243          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10244 }
10245 
10246 /// \brief Returns true if the given expression can be evaluated as a constant
10247 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)10248 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10249   bool Res;
10250   return !E->isValueDependent() &&
10251          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10252 }
10253 
10254 /// \brief Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10255 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10256                                              Expr *LHSExpr, Expr *RHSExpr) {
10257   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10258     if (Bop->getOpcode() == BO_LAnd) {
10259       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10260       if (EvaluatesAsFalse(S, RHSExpr))
10261         return;
10262       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10263       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10264         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10265     } else if (Bop->getOpcode() == BO_LOr) {
10266       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10267         // If it's "a || b && 1 || c" we didn't warn earlier for
10268         // "a || b && 1", but warn now.
10269         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10270           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10271       }
10272     }
10273   }
10274 }
10275 
10276 /// \brief Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10277 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10278                                              Expr *LHSExpr, Expr *RHSExpr) {
10279   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10280     if (Bop->getOpcode() == BO_LAnd) {
10281       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10282       if (EvaluatesAsFalse(S, LHSExpr))
10283         return;
10284       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10285       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10286         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10287     }
10288   }
10289 }
10290 
10291 /// \brief Look for '&' in the left or right hand of a '|' expr.
DiagnoseBitwiseAndInBitwiseOr(Sema & S,SourceLocation OpLoc,Expr * OrArg)10292 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
10293                                              Expr *OrArg) {
10294   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
10295     if (Bop->getOpcode() == BO_And)
10296       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
10297   }
10298 }
10299 
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)10300 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10301                                     Expr *SubExpr, StringRef Shift) {
10302   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10303     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10304       StringRef Op = Bop->getOpcodeStr();
10305       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10306           << Bop->getSourceRange() << OpLoc << Shift << Op;
10307       SuggestParentheses(S, Bop->getOperatorLoc(),
10308           S.PDiag(diag::note_precedence_silence) << Op,
10309           Bop->getSourceRange());
10310     }
10311   }
10312 }
10313 
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10314 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10315                                  Expr *LHSExpr, Expr *RHSExpr) {
10316   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10317   if (!OCE)
10318     return;
10319 
10320   FunctionDecl *FD = OCE->getDirectCallee();
10321   if (!FD || !FD->isOverloadedOperator())
10322     return;
10323 
10324   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10325   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10326     return;
10327 
10328   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10329       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10330       << (Kind == OO_LessLess);
10331   SuggestParentheses(S, OCE->getOperatorLoc(),
10332                      S.PDiag(diag::note_precedence_silence)
10333                          << (Kind == OO_LessLess ? "<<" : ">>"),
10334                      OCE->getSourceRange());
10335   SuggestParentheses(S, OpLoc,
10336                      S.PDiag(diag::note_evaluate_comparison_first),
10337                      SourceRange(OCE->getArg(1)->getLocStart(),
10338                                  RHSExpr->getLocEnd()));
10339 }
10340 
10341 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10342 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10343 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10344                                     SourceLocation OpLoc, Expr *LHSExpr,
10345                                     Expr *RHSExpr){
10346   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10347   if (BinaryOperator::isBitwiseOp(Opc))
10348     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10349 
10350   // Diagnose "arg1 & arg2 | arg3"
10351   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10352     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
10353     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
10354   }
10355 
10356   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10357   // We don't warn for 'assert(a || b && "bad")' since this is safe.
10358   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10359     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10360     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10361   }
10362 
10363   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10364       || Opc == BO_Shr) {
10365     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10366     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10367     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10368   }
10369 
10370   // Warn on overloaded shift operators and comparisons, such as:
10371   // cout << 5 == 4;
10372   if (BinaryOperator::isComparisonOp(Opc))
10373     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10374 }
10375 
10376 // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)10377 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10378                             tok::TokenKind Kind,
10379                             Expr *LHSExpr, Expr *RHSExpr) {
10380   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10381   assert(LHSExpr && "ActOnBinOp(): missing left expression");
10382   assert(RHSExpr && "ActOnBinOp(): missing right expression");
10383 
10384   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10385   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10386 
10387   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10388 }
10389 
10390 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)10391 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10392                                        BinaryOperatorKind Opc,
10393                                        Expr *LHS, Expr *RHS) {
10394   // Find all of the overloaded operators visible from this
10395   // point. We perform both an operator-name lookup from the local
10396   // scope and an argument-dependent lookup based on the types of
10397   // the arguments.
10398   UnresolvedSet<16> Functions;
10399   OverloadedOperatorKind OverOp
10400     = BinaryOperator::getOverloadedOperator(Opc);
10401   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10402     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10403                                    RHS->getType(), Functions);
10404 
10405   // Build the (potentially-overloaded, potentially-dependent)
10406   // binary operation.
10407   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10408 }
10409 
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)10410 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10411                             BinaryOperatorKind Opc,
10412                             Expr *LHSExpr, Expr *RHSExpr) {
10413   // We want to end up calling one of checkPseudoObjectAssignment
10414   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10415   // both expressions are overloadable or either is type-dependent),
10416   // or CreateBuiltinBinOp (in any other case).  We also want to get
10417   // any placeholder types out of the way.
10418 
10419   // Handle pseudo-objects in the LHS.
10420   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10421     // Assignments with a pseudo-object l-value need special analysis.
10422     if (pty->getKind() == BuiltinType::PseudoObject &&
10423         BinaryOperator::isAssignmentOp(Opc))
10424       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10425 
10426     // Don't resolve overloads if the other type is overloadable.
10427     if (pty->getKind() == BuiltinType::Overload) {
10428       // We can't actually test that if we still have a placeholder,
10429       // though.  Fortunately, none of the exceptions we see in that
10430       // code below are valid when the LHS is an overload set.  Note
10431       // that an overload set can be dependently-typed, but it never
10432       // instantiates to having an overloadable type.
10433       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10434       if (resolvedRHS.isInvalid()) return ExprError();
10435       RHSExpr = resolvedRHS.get();
10436 
10437       if (RHSExpr->isTypeDependent() ||
10438           RHSExpr->getType()->isOverloadableType())
10439         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10440     }
10441 
10442     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10443     if (LHS.isInvalid()) return ExprError();
10444     LHSExpr = LHS.get();
10445   }
10446 
10447   // Handle pseudo-objects in the RHS.
10448   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10449     // An overload in the RHS can potentially be resolved by the type
10450     // being assigned to.
10451     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10452       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10453         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10454 
10455       if (LHSExpr->getType()->isOverloadableType())
10456         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10457 
10458       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10459     }
10460 
10461     // Don't resolve overloads if the other type is overloadable.
10462     if (pty->getKind() == BuiltinType::Overload &&
10463         LHSExpr->getType()->isOverloadableType())
10464       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10465 
10466     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10467     if (!resolvedRHS.isUsable()) return ExprError();
10468     RHSExpr = resolvedRHS.get();
10469   }
10470 
10471   if (getLangOpts().CPlusPlus) {
10472     // If either expression is type-dependent, always build an
10473     // overloaded op.
10474     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10475       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10476 
10477     // Otherwise, build an overloaded op if either expression has an
10478     // overloadable type.
10479     if (LHSExpr->getType()->isOverloadableType() ||
10480         RHSExpr->getType()->isOverloadableType())
10481       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10482   }
10483 
10484   // Build a built-in binary operation.
10485   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10486 }
10487 
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)10488 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10489                                       UnaryOperatorKind Opc,
10490                                       Expr *InputExpr) {
10491   ExprResult Input = InputExpr;
10492   ExprValueKind VK = VK_RValue;
10493   ExprObjectKind OK = OK_Ordinary;
10494   QualType resultType;
10495   switch (Opc) {
10496   case UO_PreInc:
10497   case UO_PreDec:
10498   case UO_PostInc:
10499   case UO_PostDec:
10500     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10501                                                 OpLoc,
10502                                                 Opc == UO_PreInc ||
10503                                                 Opc == UO_PostInc,
10504                                                 Opc == UO_PreInc ||
10505                                                 Opc == UO_PreDec);
10506     break;
10507   case UO_AddrOf:
10508     resultType = CheckAddressOfOperand(Input, OpLoc);
10509     RecordModifiableNonNullParam(*this, InputExpr);
10510     break;
10511   case UO_Deref: {
10512     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10513     if (Input.isInvalid()) return ExprError();
10514     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10515     break;
10516   }
10517   case UO_Plus:
10518   case UO_Minus:
10519     Input = UsualUnaryConversions(Input.get());
10520     if (Input.isInvalid()) return ExprError();
10521     resultType = Input.get()->getType();
10522     if (resultType->isDependentType())
10523       break;
10524     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
10525         resultType->isVectorType())
10526       break;
10527     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
10528              Opc == UO_Plus &&
10529              resultType->isPointerType())
10530       break;
10531 
10532     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10533       << resultType << Input.get()->getSourceRange());
10534 
10535   case UO_Not: // bitwise complement
10536     Input = UsualUnaryConversions(Input.get());
10537     if (Input.isInvalid())
10538       return ExprError();
10539     resultType = Input.get()->getType();
10540     if (resultType->isDependentType())
10541       break;
10542     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10543     if (resultType->isComplexType() || resultType->isComplexIntegerType())
10544       // C99 does not support '~' for complex conjugation.
10545       Diag(OpLoc, diag::ext_integer_complement_complex)
10546           << resultType << Input.get()->getSourceRange();
10547     else if (resultType->hasIntegerRepresentation())
10548       break;
10549     else if (resultType->isExtVectorType()) {
10550       if (Context.getLangOpts().OpenCL) {
10551         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10552         // on vector float types.
10553         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10554         if (!T->isIntegerType())
10555           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10556                            << resultType << Input.get()->getSourceRange());
10557       }
10558       break;
10559     } else {
10560       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10561                        << resultType << Input.get()->getSourceRange());
10562     }
10563     break;
10564 
10565   case UO_LNot: // logical negation
10566     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10567     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10568     if (Input.isInvalid()) return ExprError();
10569     resultType = Input.get()->getType();
10570 
10571     // Though we still have to promote half FP to float...
10572     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10573       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10574       resultType = Context.FloatTy;
10575     }
10576 
10577     if (resultType->isDependentType())
10578       break;
10579     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10580       // C99 6.5.3.3p1: ok, fallthrough;
10581       if (Context.getLangOpts().CPlusPlus) {
10582         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10583         // operand contextually converted to bool.
10584         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10585                                   ScalarTypeToBooleanCastKind(resultType));
10586       } else if (Context.getLangOpts().OpenCL &&
10587                  Context.getLangOpts().OpenCLVersion < 120) {
10588         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10589         // operate on scalar float types.
10590         if (!resultType->isIntegerType())
10591           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10592                            << resultType << Input.get()->getSourceRange());
10593       }
10594     } else if (resultType->isExtVectorType()) {
10595       if (Context.getLangOpts().OpenCL &&
10596           Context.getLangOpts().OpenCLVersion < 120) {
10597         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10598         // operate on vector float types.
10599         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10600         if (!T->isIntegerType())
10601           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10602                            << resultType << Input.get()->getSourceRange());
10603       }
10604       // Vector logical not returns the signed variant of the operand type.
10605       resultType = GetSignedVectorType(resultType);
10606       break;
10607     } else {
10608       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10609         << resultType << Input.get()->getSourceRange());
10610     }
10611 
10612     // LNot always has type int. C99 6.5.3.3p5.
10613     // In C++, it's bool. C++ 5.3.1p8
10614     resultType = Context.getLogicalOperationType();
10615     break;
10616   case UO_Real:
10617   case UO_Imag:
10618     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10619     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10620     // complex l-values to ordinary l-values and all other values to r-values.
10621     if (Input.isInvalid()) return ExprError();
10622     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10623       if (Input.get()->getValueKind() != VK_RValue &&
10624           Input.get()->getObjectKind() == OK_Ordinary)
10625         VK = Input.get()->getValueKind();
10626     } else if (!getLangOpts().CPlusPlus) {
10627       // In C, a volatile scalar is read by __imag. In C++, it is not.
10628       Input = DefaultLvalueConversion(Input.get());
10629     }
10630     break;
10631   case UO_Extension:
10632     resultType = Input.get()->getType();
10633     VK = Input.get()->getValueKind();
10634     OK = Input.get()->getObjectKind();
10635     break;
10636   }
10637   if (resultType.isNull() || Input.isInvalid())
10638     return ExprError();
10639 
10640   // Check for array bounds violations in the operand of the UnaryOperator,
10641   // except for the '*' and '&' operators that have to be handled specially
10642   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10643   // that are explicitly defined as valid by the standard).
10644   if (Opc != UO_AddrOf && Opc != UO_Deref)
10645     CheckArrayAccess(Input.get());
10646 
10647   return new (Context)
10648       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10649 }
10650 
10651 /// \brief Determine whether the given expression is a qualified member
10652 /// access expression, of a form that could be turned into a pointer to member
10653 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)10654 static bool isQualifiedMemberAccess(Expr *E) {
10655   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10656     if (!DRE->getQualifier())
10657       return false;
10658 
10659     ValueDecl *VD = DRE->getDecl();
10660     if (!VD->isCXXClassMember())
10661       return false;
10662 
10663     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10664       return true;
10665     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10666       return Method->isInstance();
10667 
10668     return false;
10669   }
10670 
10671   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10672     if (!ULE->getQualifier())
10673       return false;
10674 
10675     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10676                                            DEnd = ULE->decls_end();
10677          D != DEnd; ++D) {
10678       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10679         if (Method->isInstance())
10680           return true;
10681       } else {
10682         // Overload set does not contain methods.
10683         break;
10684       }
10685     }
10686 
10687     return false;
10688   }
10689 
10690   return false;
10691 }
10692 
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)10693 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10694                               UnaryOperatorKind Opc, Expr *Input) {
10695   // First things first: handle placeholders so that the
10696   // overloaded-operator check considers the right type.
10697   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10698     // Increment and decrement of pseudo-object references.
10699     if (pty->getKind() == BuiltinType::PseudoObject &&
10700         UnaryOperator::isIncrementDecrementOp(Opc))
10701       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10702 
10703     // extension is always a builtin operator.
10704     if (Opc == UO_Extension)
10705       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10706 
10707     // & gets special logic for several kinds of placeholder.
10708     // The builtin code knows what to do.
10709     if (Opc == UO_AddrOf &&
10710         (pty->getKind() == BuiltinType::Overload ||
10711          pty->getKind() == BuiltinType::UnknownAny ||
10712          pty->getKind() == BuiltinType::BoundMember))
10713       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10714 
10715     // Anything else needs to be handled now.
10716     ExprResult Result = CheckPlaceholderExpr(Input);
10717     if (Result.isInvalid()) return ExprError();
10718     Input = Result.get();
10719   }
10720 
10721   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10722       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10723       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10724     // Find all of the overloaded operators visible from this
10725     // point. We perform both an operator-name lookup from the local
10726     // scope and an argument-dependent lookup based on the types of
10727     // the arguments.
10728     UnresolvedSet<16> Functions;
10729     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10730     if (S && OverOp != OO_None)
10731       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10732                                    Functions);
10733 
10734     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10735   }
10736 
10737   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10738 }
10739 
10740 // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)10741 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10742                               tok::TokenKind Op, Expr *Input) {
10743   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10744 }
10745 
10746 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)10747 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10748                                 LabelDecl *TheDecl) {
10749   TheDecl->markUsed(Context);
10750   // Create the AST node.  The address of a label always has type 'void*'.
10751   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10752                                      Context.getPointerType(Context.VoidTy));
10753 }
10754 
10755 /// Given the last statement in a statement-expression, check whether
10756 /// the result is a producing expression (like a call to an
10757 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10758 /// release out of the full-expression.  Otherwise, return null.
10759 /// Cannot fail.
maybeRebuildARCConsumingStmt(Stmt * Statement)10760 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10761   // Should always be wrapped with one of these.
10762   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10763   if (!cleanups) return nullptr;
10764 
10765   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10766   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10767     return nullptr;
10768 
10769   // Splice out the cast.  This shouldn't modify any interesting
10770   // features of the statement.
10771   Expr *producer = cast->getSubExpr();
10772   assert(producer->getType() == cast->getType());
10773   assert(producer->getValueKind() == cast->getValueKind());
10774   cleanups->setSubExpr(producer);
10775   return cleanups;
10776 }
10777 
ActOnStartStmtExpr()10778 void Sema::ActOnStartStmtExpr() {
10779   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10780 }
10781 
ActOnStmtExprError()10782 void Sema::ActOnStmtExprError() {
10783   // Note that function is also called by TreeTransform when leaving a
10784   // StmtExpr scope without rebuilding anything.
10785 
10786   DiscardCleanupsInEvaluationContext();
10787   PopExpressionEvaluationContext();
10788 }
10789 
10790 ExprResult
ActOnStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)10791 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10792                     SourceLocation RPLoc) { // "({..})"
10793   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10794   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10795 
10796   if (hasAnyUnrecoverableErrorsInThisFunction())
10797     DiscardCleanupsInEvaluationContext();
10798   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10799   PopExpressionEvaluationContext();
10800 
10801   // FIXME: there are a variety of strange constraints to enforce here, for
10802   // example, it is not possible to goto into a stmt expression apparently.
10803   // More semantic analysis is needed.
10804 
10805   // If there are sub-stmts in the compound stmt, take the type of the last one
10806   // as the type of the stmtexpr.
10807   QualType Ty = Context.VoidTy;
10808   bool StmtExprMayBindToTemp = false;
10809   if (!Compound->body_empty()) {
10810     Stmt *LastStmt = Compound->body_back();
10811     LabelStmt *LastLabelStmt = nullptr;
10812     // If LastStmt is a label, skip down through into the body.
10813     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10814       LastLabelStmt = Label;
10815       LastStmt = Label->getSubStmt();
10816     }
10817 
10818     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10819       // Do function/array conversion on the last expression, but not
10820       // lvalue-to-rvalue.  However, initialize an unqualified type.
10821       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10822       if (LastExpr.isInvalid())
10823         return ExprError();
10824       Ty = LastExpr.get()->getType().getUnqualifiedType();
10825 
10826       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10827         // In ARC, if the final expression ends in a consume, splice
10828         // the consume out and bind it later.  In the alternate case
10829         // (when dealing with a retainable type), the result
10830         // initialization will create a produce.  In both cases the
10831         // result will be +1, and we'll need to balance that out with
10832         // a bind.
10833         if (Expr *rebuiltLastStmt
10834               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10835           LastExpr = rebuiltLastStmt;
10836         } else {
10837           LastExpr = PerformCopyInitialization(
10838                             InitializedEntity::InitializeResult(LPLoc,
10839                                                                 Ty,
10840                                                                 false),
10841                                                    SourceLocation(),
10842                                                LastExpr);
10843         }
10844 
10845         if (LastExpr.isInvalid())
10846           return ExprError();
10847         if (LastExpr.get() != nullptr) {
10848           if (!LastLabelStmt)
10849             Compound->setLastStmt(LastExpr.get());
10850           else
10851             LastLabelStmt->setSubStmt(LastExpr.get());
10852           StmtExprMayBindToTemp = true;
10853         }
10854       }
10855     }
10856   }
10857 
10858   // FIXME: Check that expression type is complete/non-abstract; statement
10859   // expressions are not lvalues.
10860   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10861   if (StmtExprMayBindToTemp)
10862     return MaybeBindToTemporary(ResStmtExpr);
10863   return ResStmtExpr;
10864 }
10865 
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,OffsetOfComponent * CompPtr,unsigned NumComponents,SourceLocation RParenLoc)10866 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10867                                       TypeSourceInfo *TInfo,
10868                                       OffsetOfComponent *CompPtr,
10869                                       unsigned NumComponents,
10870                                       SourceLocation RParenLoc) {
10871   QualType ArgTy = TInfo->getType();
10872   bool Dependent = ArgTy->isDependentType();
10873   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10874 
10875   // We must have at least one component that refers to the type, and the first
10876   // one is known to be a field designator.  Verify that the ArgTy represents
10877   // a struct/union/class.
10878   if (!Dependent && !ArgTy->isRecordType())
10879     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10880                        << ArgTy << TypeRange);
10881 
10882   // Type must be complete per C99 7.17p3 because a declaring a variable
10883   // with an incomplete type would be ill-formed.
10884   if (!Dependent
10885       && RequireCompleteType(BuiltinLoc, ArgTy,
10886                              diag::err_offsetof_incomplete_type, TypeRange))
10887     return ExprError();
10888 
10889   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10890   // GCC extension, diagnose them.
10891   // FIXME: This diagnostic isn't actually visible because the location is in
10892   // a system header!
10893   if (NumComponents != 1)
10894     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10895       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10896 
10897   bool DidWarnAboutNonPOD = false;
10898   QualType CurrentType = ArgTy;
10899   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10900   SmallVector<OffsetOfNode, 4> Comps;
10901   SmallVector<Expr*, 4> Exprs;
10902   for (unsigned i = 0; i != NumComponents; ++i) {
10903     const OffsetOfComponent &OC = CompPtr[i];
10904     if (OC.isBrackets) {
10905       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10906       if (!CurrentType->isDependentType()) {
10907         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10908         if(!AT)
10909           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10910                            << CurrentType);
10911         CurrentType = AT->getElementType();
10912       } else
10913         CurrentType = Context.DependentTy;
10914 
10915       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10916       if (IdxRval.isInvalid())
10917         return ExprError();
10918       Expr *Idx = IdxRval.get();
10919 
10920       // The expression must be an integral expression.
10921       // FIXME: An integral constant expression?
10922       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10923           !Idx->getType()->isIntegerType())
10924         return ExprError(Diag(Idx->getLocStart(),
10925                               diag::err_typecheck_subscript_not_integer)
10926                          << Idx->getSourceRange());
10927 
10928       // Record this array index.
10929       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10930       Exprs.push_back(Idx);
10931       continue;
10932     }
10933 
10934     // Offset of a field.
10935     if (CurrentType->isDependentType()) {
10936       // We have the offset of a field, but we can't look into the dependent
10937       // type. Just record the identifier of the field.
10938       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10939       CurrentType = Context.DependentTy;
10940       continue;
10941     }
10942 
10943     // We need to have a complete type to look into.
10944     if (RequireCompleteType(OC.LocStart, CurrentType,
10945                             diag::err_offsetof_incomplete_type))
10946       return ExprError();
10947 
10948     // Look for the designated field.
10949     const RecordType *RC = CurrentType->getAs<RecordType>();
10950     if (!RC)
10951       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10952                        << CurrentType);
10953     RecordDecl *RD = RC->getDecl();
10954 
10955     // C++ [lib.support.types]p5:
10956     //   The macro offsetof accepts a restricted set of type arguments in this
10957     //   International Standard. type shall be a POD structure or a POD union
10958     //   (clause 9).
10959     // C++11 [support.types]p4:
10960     //   If type is not a standard-layout class (Clause 9), the results are
10961     //   undefined.
10962     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10963       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10964       unsigned DiagID =
10965         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10966                             : diag::ext_offsetof_non_pod_type;
10967 
10968       if (!IsSafe && !DidWarnAboutNonPOD &&
10969           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10970                               PDiag(DiagID)
10971                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10972                               << CurrentType))
10973         DidWarnAboutNonPOD = true;
10974     }
10975 
10976     // Look for the field.
10977     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10978     LookupQualifiedName(R, RD);
10979     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10980     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10981     if (!MemberDecl) {
10982       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10983         MemberDecl = IndirectMemberDecl->getAnonField();
10984     }
10985 
10986     if (!MemberDecl)
10987       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10988                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10989                                                               OC.LocEnd));
10990 
10991     // C99 7.17p3:
10992     //   (If the specified member is a bit-field, the behavior is undefined.)
10993     //
10994     // We diagnose this as an error.
10995     if (MemberDecl->isBitField()) {
10996       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10997         << MemberDecl->getDeclName()
10998         << SourceRange(BuiltinLoc, RParenLoc);
10999       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11000       return ExprError();
11001     }
11002 
11003     RecordDecl *Parent = MemberDecl->getParent();
11004     if (IndirectMemberDecl)
11005       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11006 
11007     // If the member was found in a base class, introduce OffsetOfNodes for
11008     // the base class indirections.
11009     CXXBasePaths Paths;
11010     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
11011       if (Paths.getDetectedVirtual()) {
11012         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11013           << MemberDecl->getDeclName()
11014           << SourceRange(BuiltinLoc, RParenLoc);
11015         return ExprError();
11016       }
11017 
11018       CXXBasePath &Path = Paths.front();
11019       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11020            B != BEnd; ++B)
11021         Comps.push_back(OffsetOfNode(B->Base));
11022     }
11023 
11024     if (IndirectMemberDecl) {
11025       for (auto *FI : IndirectMemberDecl->chain()) {
11026         assert(isa<FieldDecl>(FI));
11027         Comps.push_back(OffsetOfNode(OC.LocStart,
11028                                      cast<FieldDecl>(FI), OC.LocEnd));
11029       }
11030     } else
11031       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11032 
11033     CurrentType = MemberDecl->getType().getNonReferenceType();
11034   }
11035 
11036   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11037                               Comps, Exprs, RParenLoc);
11038 }
11039 
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,OffsetOfComponent * CompPtr,unsigned NumComponents,SourceLocation RParenLoc)11040 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11041                                       SourceLocation BuiltinLoc,
11042                                       SourceLocation TypeLoc,
11043                                       ParsedType ParsedArgTy,
11044                                       OffsetOfComponent *CompPtr,
11045                                       unsigned NumComponents,
11046                                       SourceLocation RParenLoc) {
11047 
11048   TypeSourceInfo *ArgTInfo;
11049   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11050   if (ArgTy.isNull())
11051     return ExprError();
11052 
11053   if (!ArgTInfo)
11054     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11055 
11056   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
11057                               RParenLoc);
11058 }
11059 
11060 
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)11061 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11062                                  Expr *CondExpr,
11063                                  Expr *LHSExpr, Expr *RHSExpr,
11064                                  SourceLocation RPLoc) {
11065   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11066 
11067   ExprValueKind VK = VK_RValue;
11068   ExprObjectKind OK = OK_Ordinary;
11069   QualType resType;
11070   bool ValueDependent = false;
11071   bool CondIsTrue = false;
11072   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11073     resType = Context.DependentTy;
11074     ValueDependent = true;
11075   } else {
11076     // The conditional expression is required to be a constant expression.
11077     llvm::APSInt condEval(32);
11078     ExprResult CondICE
11079       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11080           diag::err_typecheck_choose_expr_requires_constant, false);
11081     if (CondICE.isInvalid())
11082       return ExprError();
11083     CondExpr = CondICE.get();
11084     CondIsTrue = condEval.getZExtValue();
11085 
11086     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11087     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11088 
11089     resType = ActiveExpr->getType();
11090     ValueDependent = ActiveExpr->isValueDependent();
11091     VK = ActiveExpr->getValueKind();
11092     OK = ActiveExpr->getObjectKind();
11093   }
11094 
11095   return new (Context)
11096       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11097                  CondIsTrue, resType->isDependentType(), ValueDependent);
11098 }
11099 
11100 //===----------------------------------------------------------------------===//
11101 // Clang Extensions.
11102 //===----------------------------------------------------------------------===//
11103 
11104 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)11105 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11106   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11107 
11108   if (LangOpts.CPlusPlus) {
11109     Decl *ManglingContextDecl;
11110     if (MangleNumberingContext *MCtx =
11111             getCurrentMangleNumberContext(Block->getDeclContext(),
11112                                           ManglingContextDecl)) {
11113       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11114       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11115     }
11116   }
11117 
11118   PushBlockScope(CurScope, Block);
11119   CurContext->addDecl(Block);
11120   if (CurScope)
11121     PushDeclContext(CurScope, Block);
11122   else
11123     CurContext = Block;
11124 
11125   getCurBlock()->HasImplicitReturnType = true;
11126 
11127   // Enter a new evaluation context to insulate the block from any
11128   // cleanups from the enclosing full-expression.
11129   PushExpressionEvaluationContext(PotentiallyEvaluated);
11130 }
11131 
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)11132 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11133                                Scope *CurScope) {
11134   assert(ParamInfo.getIdentifier() == nullptr &&
11135          "block-id should have no identifier!");
11136   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11137   BlockScopeInfo *CurBlock = getCurBlock();
11138 
11139   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11140   QualType T = Sig->getType();
11141 
11142   // FIXME: We should allow unexpanded parameter packs here, but that would,
11143   // in turn, make the block expression contain unexpanded parameter packs.
11144   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11145     // Drop the parameters.
11146     FunctionProtoType::ExtProtoInfo EPI;
11147     EPI.HasTrailingReturn = false;
11148     EPI.TypeQuals |= DeclSpec::TQ_const;
11149     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11150     Sig = Context.getTrivialTypeSourceInfo(T);
11151   }
11152 
11153   // GetTypeForDeclarator always produces a function type for a block
11154   // literal signature.  Furthermore, it is always a FunctionProtoType
11155   // unless the function was written with a typedef.
11156   assert(T->isFunctionType() &&
11157          "GetTypeForDeclarator made a non-function block signature");
11158 
11159   // Look for an explicit signature in that function type.
11160   FunctionProtoTypeLoc ExplicitSignature;
11161 
11162   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11163   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11164 
11165     // Check whether that explicit signature was synthesized by
11166     // GetTypeForDeclarator.  If so, don't save that as part of the
11167     // written signature.
11168     if (ExplicitSignature.getLocalRangeBegin() ==
11169         ExplicitSignature.getLocalRangeEnd()) {
11170       // This would be much cheaper if we stored TypeLocs instead of
11171       // TypeSourceInfos.
11172       TypeLoc Result = ExplicitSignature.getReturnLoc();
11173       unsigned Size = Result.getFullDataSize();
11174       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11175       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11176 
11177       ExplicitSignature = FunctionProtoTypeLoc();
11178     }
11179   }
11180 
11181   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11182   CurBlock->FunctionType = T;
11183 
11184   const FunctionType *Fn = T->getAs<FunctionType>();
11185   QualType RetTy = Fn->getReturnType();
11186   bool isVariadic =
11187     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11188 
11189   CurBlock->TheDecl->setIsVariadic(isVariadic);
11190 
11191   // Context.DependentTy is used as a placeholder for a missing block
11192   // return type.  TODO:  what should we do with declarators like:
11193   //   ^ * { ... }
11194   // If the answer is "apply template argument deduction"....
11195   if (RetTy != Context.DependentTy) {
11196     CurBlock->ReturnType = RetTy;
11197     CurBlock->TheDecl->setBlockMissingReturnType(false);
11198     CurBlock->HasImplicitReturnType = false;
11199   }
11200 
11201   // Push block parameters from the declarator if we had them.
11202   SmallVector<ParmVarDecl*, 8> Params;
11203   if (ExplicitSignature) {
11204     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11205       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11206       if (Param->getIdentifier() == nullptr &&
11207           !Param->isImplicit() &&
11208           !Param->isInvalidDecl() &&
11209           !getLangOpts().CPlusPlus)
11210         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11211       Params.push_back(Param);
11212     }
11213 
11214   // Fake up parameter variables if we have a typedef, like
11215   //   ^ fntype { ... }
11216   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11217     for (const auto &I : Fn->param_types()) {
11218       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11219           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11220       Params.push_back(Param);
11221     }
11222   }
11223 
11224   // Set the parameters on the block decl.
11225   if (!Params.empty()) {
11226     CurBlock->TheDecl->setParams(Params);
11227     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11228                              CurBlock->TheDecl->param_end(),
11229                              /*CheckParameterNames=*/false);
11230   }
11231 
11232   // Finally we can process decl attributes.
11233   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11234 
11235   // Put the parameter variables in scope.
11236   for (auto AI : CurBlock->TheDecl->params()) {
11237     AI->setOwningFunction(CurBlock->TheDecl);
11238 
11239     // If this has an identifier, add it to the scope stack.
11240     if (AI->getIdentifier()) {
11241       CheckShadow(CurBlock->TheScope, AI);
11242 
11243       PushOnScopeChains(AI, CurBlock->TheScope);
11244     }
11245   }
11246 }
11247 
11248 /// ActOnBlockError - If there is an error parsing a block, this callback
11249 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)11250 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11251   // Leave the expression-evaluation context.
11252   DiscardCleanupsInEvaluationContext();
11253   PopExpressionEvaluationContext();
11254 
11255   // Pop off CurBlock, handle nested blocks.
11256   PopDeclContext();
11257   PopFunctionScopeInfo();
11258 }
11259 
11260 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11261 /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)11262 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11263                                     Stmt *Body, Scope *CurScope) {
11264   // If blocks are disabled, emit an error.
11265   if (!LangOpts.Blocks)
11266     Diag(CaretLoc, diag::err_blocks_disable);
11267 
11268   // Leave the expression-evaluation context.
11269   if (hasAnyUnrecoverableErrorsInThisFunction())
11270     DiscardCleanupsInEvaluationContext();
11271   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11272   PopExpressionEvaluationContext();
11273 
11274   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11275 
11276   if (BSI->HasImplicitReturnType)
11277     deduceClosureReturnType(*BSI);
11278 
11279   PopDeclContext();
11280 
11281   QualType RetTy = Context.VoidTy;
11282   if (!BSI->ReturnType.isNull())
11283     RetTy = BSI->ReturnType;
11284 
11285   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11286   QualType BlockTy;
11287 
11288   // Set the captured variables on the block.
11289   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11290   SmallVector<BlockDecl::Capture, 4> Captures;
11291   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11292     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11293     if (Cap.isThisCapture())
11294       continue;
11295     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11296                               Cap.isNested(), Cap.getInitExpr());
11297     Captures.push_back(NewCap);
11298   }
11299   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
11300                             BSI->CXXThisCaptureIndex != 0);
11301 
11302   // If the user wrote a function type in some form, try to use that.
11303   if (!BSI->FunctionType.isNull()) {
11304     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11305 
11306     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11307     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11308 
11309     // Turn protoless block types into nullary block types.
11310     if (isa<FunctionNoProtoType>(FTy)) {
11311       FunctionProtoType::ExtProtoInfo EPI;
11312       EPI.ExtInfo = Ext;
11313       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11314 
11315     // Otherwise, if we don't need to change anything about the function type,
11316     // preserve its sugar structure.
11317     } else if (FTy->getReturnType() == RetTy &&
11318                (!NoReturn || FTy->getNoReturnAttr())) {
11319       BlockTy = BSI->FunctionType;
11320 
11321     // Otherwise, make the minimal modifications to the function type.
11322     } else {
11323       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11324       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11325       EPI.TypeQuals = 0; // FIXME: silently?
11326       EPI.ExtInfo = Ext;
11327       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11328     }
11329 
11330   // If we don't have a function type, just build one from nothing.
11331   } else {
11332     FunctionProtoType::ExtProtoInfo EPI;
11333     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11334     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11335   }
11336 
11337   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11338                            BSI->TheDecl->param_end());
11339   BlockTy = Context.getBlockPointerType(BlockTy);
11340 
11341   // If needed, diagnose invalid gotos and switches in the block.
11342   if (getCurFunction()->NeedsScopeChecking() &&
11343       !PP.isCodeCompletionEnabled())
11344     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11345 
11346   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11347 
11348   // Try to apply the named return value optimization. We have to check again
11349   // if we can do this, though, because blocks keep return statements around
11350   // to deduce an implicit return type.
11351   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11352       !BSI->TheDecl->isDependentContext())
11353     computeNRVO(Body, BSI);
11354 
11355   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11356   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11357   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11358 
11359   // If the block isn't obviously global, i.e. it captures anything at
11360   // all, then we need to do a few things in the surrounding context:
11361   if (Result->getBlockDecl()->hasCaptures()) {
11362     // First, this expression has a new cleanup object.
11363     ExprCleanupObjects.push_back(Result->getBlockDecl());
11364     ExprNeedsCleanups = true;
11365 
11366     // It also gets a branch-protected scope if any of the captured
11367     // variables needs destruction.
11368     for (const auto &CI : Result->getBlockDecl()->captures()) {
11369       const VarDecl *var = CI.getVariable();
11370       if (var->getType().isDestructedType() != QualType::DK_none) {
11371         getCurFunction()->setHasBranchProtectedScope();
11372         break;
11373       }
11374     }
11375   }
11376 
11377   return Result;
11378 }
11379 
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)11380 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11381                                         Expr *E, ParsedType Ty,
11382                                         SourceLocation RPLoc) {
11383   TypeSourceInfo *TInfo;
11384   GetTypeFromParser(Ty, &TInfo);
11385   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11386 }
11387 
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)11388 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11389                                 Expr *E, TypeSourceInfo *TInfo,
11390                                 SourceLocation RPLoc) {
11391   Expr *OrigExpr = E;
11392 
11393   // Get the va_list type
11394   QualType VaListType = Context.getBuiltinVaListType();
11395   if (VaListType->isArrayType()) {
11396     // Deal with implicit array decay; for example, on x86-64,
11397     // va_list is an array, but it's supposed to decay to
11398     // a pointer for va_arg.
11399     VaListType = Context.getArrayDecayedType(VaListType);
11400     // Make sure the input expression also decays appropriately.
11401     ExprResult Result = UsualUnaryConversions(E);
11402     if (Result.isInvalid())
11403       return ExprError();
11404     E = Result.get();
11405   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11406     // If va_list is a record type and we are compiling in C++ mode,
11407     // check the argument using reference binding.
11408     InitializedEntity Entity
11409       = InitializedEntity::InitializeParameter(Context,
11410           Context.getLValueReferenceType(VaListType), false);
11411     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11412     if (Init.isInvalid())
11413       return ExprError();
11414     E = Init.getAs<Expr>();
11415   } else {
11416     // Otherwise, the va_list argument must be an l-value because
11417     // it is modified by va_arg.
11418     if (!E->isTypeDependent() &&
11419         CheckForModifiableLvalue(E, BuiltinLoc, *this))
11420       return ExprError();
11421   }
11422 
11423   if (!E->isTypeDependent() &&
11424       !Context.hasSameType(VaListType, E->getType())) {
11425     return ExprError(Diag(E->getLocStart(),
11426                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
11427       << OrigExpr->getType() << E->getSourceRange());
11428   }
11429 
11430   if (!TInfo->getType()->isDependentType()) {
11431     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11432                             diag::err_second_parameter_to_va_arg_incomplete,
11433                             TInfo->getTypeLoc()))
11434       return ExprError();
11435 
11436     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11437                                TInfo->getType(),
11438                                diag::err_second_parameter_to_va_arg_abstract,
11439                                TInfo->getTypeLoc()))
11440       return ExprError();
11441 
11442     if (!TInfo->getType().isPODType(Context)) {
11443       Diag(TInfo->getTypeLoc().getBeginLoc(),
11444            TInfo->getType()->isObjCLifetimeType()
11445              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11446              : diag::warn_second_parameter_to_va_arg_not_pod)
11447         << TInfo->getType()
11448         << TInfo->getTypeLoc().getSourceRange();
11449     }
11450 
11451     // Check for va_arg where arguments of the given type will be promoted
11452     // (i.e. this va_arg is guaranteed to have undefined behavior).
11453     QualType PromoteType;
11454     if (TInfo->getType()->isPromotableIntegerType()) {
11455       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11456       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11457         PromoteType = QualType();
11458     }
11459     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11460       PromoteType = Context.DoubleTy;
11461     if (!PromoteType.isNull())
11462       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11463                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11464                           << TInfo->getType()
11465                           << PromoteType
11466                           << TInfo->getTypeLoc().getSourceRange());
11467   }
11468 
11469   QualType T = TInfo->getType().getNonLValueExprType(Context);
11470   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
11471 }
11472 
ActOnGNUNullExpr(SourceLocation TokenLoc)11473 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11474   // The type of __null will be int or long, depending on the size of
11475   // pointers on the target.
11476   QualType Ty;
11477   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11478   if (pw == Context.getTargetInfo().getIntWidth())
11479     Ty = Context.IntTy;
11480   else if (pw == Context.getTargetInfo().getLongWidth())
11481     Ty = Context.LongTy;
11482   else if (pw == Context.getTargetInfo().getLongLongWidth())
11483     Ty = Context.LongLongTy;
11484   else {
11485     llvm_unreachable("I don't know size of pointer!");
11486   }
11487 
11488   return new (Context) GNUNullExpr(Ty, TokenLoc);
11489 }
11490 
11491 bool
ConversionToObjCStringLiteralCheck(QualType DstType,Expr * & Exp)11492 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11493   if (!getLangOpts().ObjC1)
11494     return false;
11495 
11496   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11497   if (!PT)
11498     return false;
11499 
11500   if (!PT->isObjCIdType()) {
11501     // Check if the destination is the 'NSString' interface.
11502     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11503     if (!ID || !ID->getIdentifier()->isStr("NSString"))
11504       return false;
11505   }
11506 
11507   // Ignore any parens, implicit casts (should only be
11508   // array-to-pointer decays), and not-so-opaque values.  The last is
11509   // important for making this trigger for property assignments.
11510   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11511   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11512     if (OV->getSourceExpr())
11513       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11514 
11515   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
11516   if (!SL || !SL->isAscii())
11517     return false;
11518   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11519     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
11520   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
11521   return true;
11522 }
11523 
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)11524 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11525                                     SourceLocation Loc,
11526                                     QualType DstType, QualType SrcType,
11527                                     Expr *SrcExpr, AssignmentAction Action,
11528                                     bool *Complained) {
11529   if (Complained)
11530     *Complained = false;
11531 
11532   // Decode the result (notice that AST's are still created for extensions).
11533   bool CheckInferredResultType = false;
11534   bool isInvalid = false;
11535   unsigned DiagKind = 0;
11536   FixItHint Hint;
11537   ConversionFixItGenerator ConvHints;
11538   bool MayHaveConvFixit = false;
11539   bool MayHaveFunctionDiff = false;
11540   const ObjCInterfaceDecl *IFace = nullptr;
11541   const ObjCProtocolDecl *PDecl = nullptr;
11542 
11543   switch (ConvTy) {
11544   case Compatible:
11545       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11546       return false;
11547 
11548   case PointerToInt:
11549     DiagKind = diag::ext_typecheck_convert_pointer_int;
11550     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11551     MayHaveConvFixit = true;
11552     break;
11553   case IntToPointer:
11554     DiagKind = diag::ext_typecheck_convert_int_pointer;
11555     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11556     MayHaveConvFixit = true;
11557     break;
11558   case IncompatiblePointer:
11559       DiagKind =
11560         (Action == AA_Passing_CFAudited ?
11561           diag::err_arc_typecheck_convert_incompatible_pointer :
11562           diag::ext_typecheck_convert_incompatible_pointer);
11563     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11564       SrcType->isObjCObjectPointerType();
11565     if (Hint.isNull() && !CheckInferredResultType) {
11566       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11567     }
11568     else if (CheckInferredResultType) {
11569       SrcType = SrcType.getUnqualifiedType();
11570       DstType = DstType.getUnqualifiedType();
11571     }
11572     MayHaveConvFixit = true;
11573     break;
11574   case IncompatiblePointerSign:
11575     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11576     break;
11577   case FunctionVoidPointer:
11578     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11579     break;
11580   case IncompatiblePointerDiscardsQualifiers: {
11581     // Perform array-to-pointer decay if necessary.
11582     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11583 
11584     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11585     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11586     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11587       DiagKind = diag::err_typecheck_incompatible_address_space;
11588       break;
11589 
11590 
11591     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11592       DiagKind = diag::err_typecheck_incompatible_ownership;
11593       break;
11594     }
11595 
11596     llvm_unreachable("unknown error case for discarding qualifiers!");
11597     // fallthrough
11598   }
11599   case CompatiblePointerDiscardsQualifiers:
11600     // If the qualifiers lost were because we were applying the
11601     // (deprecated) C++ conversion from a string literal to a char*
11602     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11603     // Ideally, this check would be performed in
11604     // checkPointerTypesForAssignment. However, that would require a
11605     // bit of refactoring (so that the second argument is an
11606     // expression, rather than a type), which should be done as part
11607     // of a larger effort to fix checkPointerTypesForAssignment for
11608     // C++ semantics.
11609     if (getLangOpts().CPlusPlus &&
11610         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11611       return false;
11612     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11613     break;
11614   case IncompatibleNestedPointerQualifiers:
11615     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11616     break;
11617   case IntToBlockPointer:
11618     DiagKind = diag::err_int_to_block_pointer;
11619     break;
11620   case IncompatibleBlockPointer:
11621     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11622     break;
11623   case IncompatibleObjCQualifiedId: {
11624     if (SrcType->isObjCQualifiedIdType()) {
11625       const ObjCObjectPointerType *srcOPT =
11626                 SrcType->getAs<ObjCObjectPointerType>();
11627       for (auto *srcProto : srcOPT->quals()) {
11628         PDecl = srcProto;
11629         break;
11630       }
11631       if (const ObjCInterfaceType *IFaceT =
11632             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11633         IFace = IFaceT->getDecl();
11634     }
11635     else if (DstType->isObjCQualifiedIdType()) {
11636       const ObjCObjectPointerType *dstOPT =
11637         DstType->getAs<ObjCObjectPointerType>();
11638       for (auto *dstProto : dstOPT->quals()) {
11639         PDecl = dstProto;
11640         break;
11641       }
11642       if (const ObjCInterfaceType *IFaceT =
11643             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11644         IFace = IFaceT->getDecl();
11645     }
11646     DiagKind = diag::warn_incompatible_qualified_id;
11647     break;
11648   }
11649   case IncompatibleVectors:
11650     DiagKind = diag::warn_incompatible_vectors;
11651     break;
11652   case IncompatibleObjCWeakRef:
11653     DiagKind = diag::err_arc_weak_unavailable_assign;
11654     break;
11655   case Incompatible:
11656     DiagKind = diag::err_typecheck_convert_incompatible;
11657     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11658     MayHaveConvFixit = true;
11659     isInvalid = true;
11660     MayHaveFunctionDiff = true;
11661     break;
11662   }
11663 
11664   QualType FirstType, SecondType;
11665   switch (Action) {
11666   case AA_Assigning:
11667   case AA_Initializing:
11668     // The destination type comes first.
11669     FirstType = DstType;
11670     SecondType = SrcType;
11671     break;
11672 
11673   case AA_Returning:
11674   case AA_Passing:
11675   case AA_Passing_CFAudited:
11676   case AA_Converting:
11677   case AA_Sending:
11678   case AA_Casting:
11679     // The source type comes first.
11680     FirstType = SrcType;
11681     SecondType = DstType;
11682     break;
11683   }
11684 
11685   PartialDiagnostic FDiag = PDiag(DiagKind);
11686   if (Action == AA_Passing_CFAudited)
11687     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11688   else
11689     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11690 
11691   // If we can fix the conversion, suggest the FixIts.
11692   assert(ConvHints.isNull() || Hint.isNull());
11693   if (!ConvHints.isNull()) {
11694     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11695          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11696       FDiag << *HI;
11697   } else {
11698     FDiag << Hint;
11699   }
11700   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11701 
11702   if (MayHaveFunctionDiff)
11703     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11704 
11705   Diag(Loc, FDiag);
11706   if (DiagKind == diag::warn_incompatible_qualified_id &&
11707       PDecl && IFace && !IFace->hasDefinition())
11708       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11709         << IFace->getName() << PDecl->getName();
11710 
11711   if (SecondType == Context.OverloadTy)
11712     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11713                               FirstType);
11714 
11715   if (CheckInferredResultType)
11716     EmitRelatedResultTypeNote(SrcExpr);
11717 
11718   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11719     EmitRelatedResultTypeNoteForReturn(DstType);
11720 
11721   if (Complained)
11722     *Complained = true;
11723   return isInvalid;
11724 }
11725 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)11726 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11727                                                  llvm::APSInt *Result) {
11728   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11729   public:
11730     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11731       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11732     }
11733   } Diagnoser;
11734 
11735   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11736 }
11737 
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)11738 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11739                                                  llvm::APSInt *Result,
11740                                                  unsigned DiagID,
11741                                                  bool AllowFold) {
11742   class IDDiagnoser : public VerifyICEDiagnoser {
11743     unsigned DiagID;
11744 
11745   public:
11746     IDDiagnoser(unsigned DiagID)
11747       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11748 
11749     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11750       S.Diag(Loc, DiagID) << SR;
11751     }
11752   } Diagnoser(DiagID);
11753 
11754   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11755 }
11756 
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)11757 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11758                                             SourceRange SR) {
11759   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11760 }
11761 
11762 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)11763 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11764                                       VerifyICEDiagnoser &Diagnoser,
11765                                       bool AllowFold) {
11766   SourceLocation DiagLoc = E->getLocStart();
11767 
11768   if (getLangOpts().CPlusPlus11) {
11769     // C++11 [expr.const]p5:
11770     //   If an expression of literal class type is used in a context where an
11771     //   integral constant expression is required, then that class type shall
11772     //   have a single non-explicit conversion function to an integral or
11773     //   unscoped enumeration type
11774     ExprResult Converted;
11775     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11776     public:
11777       CXX11ConvertDiagnoser(bool Silent)
11778           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11779                                 Silent, true) {}
11780 
11781       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11782                                            QualType T) override {
11783         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11784       }
11785 
11786       SemaDiagnosticBuilder diagnoseIncomplete(
11787           Sema &S, SourceLocation Loc, QualType T) override {
11788         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11789       }
11790 
11791       SemaDiagnosticBuilder diagnoseExplicitConv(
11792           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11793         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11794       }
11795 
11796       SemaDiagnosticBuilder noteExplicitConv(
11797           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11798         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11799                  << ConvTy->isEnumeralType() << ConvTy;
11800       }
11801 
11802       SemaDiagnosticBuilder diagnoseAmbiguous(
11803           Sema &S, SourceLocation Loc, QualType T) override {
11804         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11805       }
11806 
11807       SemaDiagnosticBuilder noteAmbiguous(
11808           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11809         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11810                  << ConvTy->isEnumeralType() << ConvTy;
11811       }
11812 
11813       SemaDiagnosticBuilder diagnoseConversion(
11814           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11815         llvm_unreachable("conversion functions are permitted");
11816       }
11817     } ConvertDiagnoser(Diagnoser.Suppress);
11818 
11819     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11820                                                     ConvertDiagnoser);
11821     if (Converted.isInvalid())
11822       return Converted;
11823     E = Converted.get();
11824     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11825       return ExprError();
11826   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11827     // An ICE must be of integral or unscoped enumeration type.
11828     if (!Diagnoser.Suppress)
11829       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11830     return ExprError();
11831   }
11832 
11833   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11834   // in the non-ICE case.
11835   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11836     if (Result)
11837       *Result = E->EvaluateKnownConstInt(Context);
11838     return E;
11839   }
11840 
11841   Expr::EvalResult EvalResult;
11842   SmallVector<PartialDiagnosticAt, 8> Notes;
11843   EvalResult.Diag = &Notes;
11844 
11845   // Try to evaluate the expression, and produce diagnostics explaining why it's
11846   // not a constant expression as a side-effect.
11847   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11848                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11849 
11850   // In C++11, we can rely on diagnostics being produced for any expression
11851   // which is not a constant expression. If no diagnostics were produced, then
11852   // this is a constant expression.
11853   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11854     if (Result)
11855       *Result = EvalResult.Val.getInt();
11856     return E;
11857   }
11858 
11859   // If our only note is the usual "invalid subexpression" note, just point
11860   // the caret at its location rather than producing an essentially
11861   // redundant note.
11862   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11863         diag::note_invalid_subexpr_in_const_expr) {
11864     DiagLoc = Notes[0].first;
11865     Notes.clear();
11866   }
11867 
11868   if (!Folded || !AllowFold) {
11869     if (!Diagnoser.Suppress) {
11870       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11871       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11872         Diag(Notes[I].first, Notes[I].second);
11873     }
11874 
11875     return ExprError();
11876   }
11877 
11878   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11879   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11880     Diag(Notes[I].first, Notes[I].second);
11881 
11882   if (Result)
11883     *Result = EvalResult.Val.getInt();
11884   return E;
11885 }
11886 
11887 namespace {
11888   // Handle the case where we conclude a expression which we speculatively
11889   // considered to be unevaluated is actually evaluated.
11890   class TransformToPE : public TreeTransform<TransformToPE> {
11891     typedef TreeTransform<TransformToPE> BaseTransform;
11892 
11893   public:
TransformToPE(Sema & SemaRef)11894     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11895 
11896     // Make sure we redo semantic analysis
AlwaysRebuild()11897     bool AlwaysRebuild() { return true; }
11898 
11899     // Make sure we handle LabelStmts correctly.
11900     // FIXME: This does the right thing, but maybe we need a more general
11901     // fix to TreeTransform?
TransformLabelStmt(LabelStmt * S)11902     StmtResult TransformLabelStmt(LabelStmt *S) {
11903       S->getDecl()->setStmt(nullptr);
11904       return BaseTransform::TransformLabelStmt(S);
11905     }
11906 
11907     // We need to special-case DeclRefExprs referring to FieldDecls which
11908     // are not part of a member pointer formation; normal TreeTransforming
11909     // doesn't catch this case because of the way we represent them in the AST.
11910     // FIXME: This is a bit ugly; is it really the best way to handle this
11911     // case?
11912     //
11913     // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)11914     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11915       if (isa<FieldDecl>(E->getDecl()) &&
11916           !SemaRef.isUnevaluatedContext())
11917         return SemaRef.Diag(E->getLocation(),
11918                             diag::err_invalid_non_static_member_use)
11919             << E->getDecl() << E->getSourceRange();
11920 
11921       return BaseTransform::TransformDeclRefExpr(E);
11922     }
11923 
11924     // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)11925     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11926       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11927         return E;
11928 
11929       return BaseTransform::TransformUnaryOperator(E);
11930     }
11931 
TransformLambdaExpr(LambdaExpr * E)11932     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11933       // Lambdas never need to be transformed.
11934       return E;
11935     }
11936   };
11937 }
11938 
TransformToPotentiallyEvaluated(Expr * E)11939 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11940   assert(isUnevaluatedContext() &&
11941          "Should only transform unevaluated expressions");
11942   ExprEvalContexts.back().Context =
11943       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11944   if (isUnevaluatedContext())
11945     return E;
11946   return TransformToPE(*this).TransformExpr(E);
11947 }
11948 
11949 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,bool IsDecltype)11950 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11951                                       Decl *LambdaContextDecl,
11952                                       bool IsDecltype) {
11953   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
11954                                 ExprNeedsCleanups, LambdaContextDecl,
11955                                 IsDecltype);
11956   ExprNeedsCleanups = false;
11957   if (!MaybeODRUseExprs.empty())
11958     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11959 }
11960 
11961 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,bool IsDecltype)11962 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11963                                       ReuseLambdaContextDecl_t,
11964                                       bool IsDecltype) {
11965   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11966   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11967 }
11968 
PopExpressionEvaluationContext()11969 void Sema::PopExpressionEvaluationContext() {
11970   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11971   unsigned NumTypos = Rec.NumTypos;
11972 
11973   if (!Rec.Lambdas.empty()) {
11974     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11975       unsigned D;
11976       if (Rec.isUnevaluated()) {
11977         // C++11 [expr.prim.lambda]p2:
11978         //   A lambda-expression shall not appear in an unevaluated operand
11979         //   (Clause 5).
11980         D = diag::err_lambda_unevaluated_operand;
11981       } else {
11982         // C++1y [expr.const]p2:
11983         //   A conditional-expression e is a core constant expression unless the
11984         //   evaluation of e, following the rules of the abstract machine, would
11985         //   evaluate [...] a lambda-expression.
11986         D = diag::err_lambda_in_constant_expression;
11987       }
11988       for (const auto *L : Rec.Lambdas)
11989         Diag(L->getLocStart(), D);
11990     } else {
11991       // Mark the capture expressions odr-used. This was deferred
11992       // during lambda expression creation.
11993       for (auto *Lambda : Rec.Lambdas) {
11994         for (auto *C : Lambda->capture_inits())
11995           MarkDeclarationsReferencedInExpr(C);
11996       }
11997     }
11998   }
11999 
12000   // When are coming out of an unevaluated context, clear out any
12001   // temporaries that we may have created as part of the evaluation of
12002   // the expression in that context: they aren't relevant because they
12003   // will never be constructed.
12004   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12005     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12006                              ExprCleanupObjects.end());
12007     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12008     CleanupVarDeclMarking();
12009     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12010   // Otherwise, merge the contexts together.
12011   } else {
12012     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12013     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12014                             Rec.SavedMaybeODRUseExprs.end());
12015   }
12016 
12017   // Pop the current expression evaluation context off the stack.
12018   ExprEvalContexts.pop_back();
12019 
12020   if (!ExprEvalContexts.empty())
12021     ExprEvalContexts.back().NumTypos += NumTypos;
12022   else
12023     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12024                             "last ExpressionEvaluationContextRecord");
12025 }
12026 
DiscardCleanupsInEvaluationContext()12027 void Sema::DiscardCleanupsInEvaluationContext() {
12028   ExprCleanupObjects.erase(
12029          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12030          ExprCleanupObjects.end());
12031   ExprNeedsCleanups = false;
12032   MaybeODRUseExprs.clear();
12033 }
12034 
HandleExprEvaluationContextForTypeof(Expr * E)12035 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12036   if (!E->getType()->isVariablyModifiedType())
12037     return E;
12038   return TransformToPotentiallyEvaluated(E);
12039 }
12040 
IsPotentiallyEvaluatedContext(Sema & SemaRef)12041 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12042   // Do not mark anything as "used" within a dependent context; wait for
12043   // an instantiation.
12044   if (SemaRef.CurContext->isDependentContext())
12045     return false;
12046 
12047   switch (SemaRef.ExprEvalContexts.back().Context) {
12048     case Sema::Unevaluated:
12049     case Sema::UnevaluatedAbstract:
12050       // We are in an expression that is not potentially evaluated; do nothing.
12051       // (Depending on how you read the standard, we actually do need to do
12052       // something here for null pointer constants, but the standard's
12053       // definition of a null pointer constant is completely crazy.)
12054       return false;
12055 
12056     case Sema::ConstantEvaluated:
12057     case Sema::PotentiallyEvaluated:
12058       // We are in a potentially evaluated expression (or a constant-expression
12059       // in C++03); we need to do implicit template instantiation, implicitly
12060       // define class members, and mark most declarations as used.
12061       return true;
12062 
12063     case Sema::PotentiallyEvaluatedIfUsed:
12064       // Referenced declarations will only be used if the construct in the
12065       // containing expression is used.
12066       return false;
12067   }
12068   llvm_unreachable("Invalid context");
12069 }
12070 
12071 /// \brief Mark a function referenced, and check whether it is odr-used
12072 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool OdrUse)12073 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12074                                   bool OdrUse) {
12075   assert(Func && "No function?");
12076 
12077   Func->setReferenced();
12078 
12079   // C++11 [basic.def.odr]p3:
12080   //   A function whose name appears as a potentially-evaluated expression is
12081   //   odr-used if it is the unique lookup result or the selected member of a
12082   //   set of overloaded functions [...].
12083   //
12084   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12085   // can just check that here. Skip the rest of this function if we've already
12086   // marked the function as used.
12087   if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12088       !IsPotentiallyEvaluatedContext(*this)) {
12089     // C++11 [temp.inst]p3:
12090     //   Unless a function template specialization has been explicitly
12091     //   instantiated or explicitly specialized, the function template
12092     //   specialization is implicitly instantiated when the specialization is
12093     //   referenced in a context that requires a function definition to exist.
12094     //
12095     // We consider constexpr function templates to be referenced in a context
12096     // that requires a definition to exist whenever they are referenced.
12097     //
12098     // FIXME: This instantiates constexpr functions too frequently. If this is
12099     // really an unevaluated context (and we're not just in the definition of a
12100     // function template or overload resolution or other cases which we
12101     // incorrectly consider to be unevaluated contexts), and we're not in a
12102     // subexpression which we actually need to evaluate (for instance, a
12103     // template argument, array bound or an expression in a braced-init-list),
12104     // we are not permitted to instantiate this constexpr function definition.
12105     //
12106     // FIXME: This also implicitly defines special members too frequently. They
12107     // are only supposed to be implicitly defined if they are odr-used, but they
12108     // are not odr-used from constant expressions in unevaluated contexts.
12109     // However, they cannot be referenced if they are deleted, and they are
12110     // deleted whenever the implicit definition of the special member would
12111     // fail.
12112     if (!Func->isConstexpr() || Func->getBody())
12113       return;
12114     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12115     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12116       return;
12117   }
12118 
12119   // Note that this declaration has been used.
12120   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12121     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12122     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12123       if (Constructor->isDefaultConstructor()) {
12124         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12125           return;
12126         DefineImplicitDefaultConstructor(Loc, Constructor);
12127       } else if (Constructor->isCopyConstructor()) {
12128         DefineImplicitCopyConstructor(Loc, Constructor);
12129       } else if (Constructor->isMoveConstructor()) {
12130         DefineImplicitMoveConstructor(Loc, Constructor);
12131       }
12132     } else if (Constructor->getInheritedConstructor()) {
12133       DefineInheritingConstructor(Loc, Constructor);
12134     }
12135   } else if (CXXDestructorDecl *Destructor =
12136                  dyn_cast<CXXDestructorDecl>(Func)) {
12137     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12138     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12139       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12140         return;
12141       DefineImplicitDestructor(Loc, Destructor);
12142     }
12143     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12144       MarkVTableUsed(Loc, Destructor->getParent());
12145   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12146     if (MethodDecl->isOverloadedOperator() &&
12147         MethodDecl->getOverloadedOperator() == OO_Equal) {
12148       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12149       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12150         if (MethodDecl->isCopyAssignmentOperator())
12151           DefineImplicitCopyAssignment(Loc, MethodDecl);
12152         else
12153           DefineImplicitMoveAssignment(Loc, MethodDecl);
12154       }
12155     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12156                MethodDecl->getParent()->isLambda()) {
12157       CXXConversionDecl *Conversion =
12158           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12159       if (Conversion->isLambdaToBlockPointerConversion())
12160         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12161       else
12162         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12163     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12164       MarkVTableUsed(Loc, MethodDecl->getParent());
12165   }
12166 
12167   // Recursive functions should be marked when used from another function.
12168   // FIXME: Is this really right?
12169   if (CurContext == Func) return;
12170 
12171   // Resolve the exception specification for any function which is
12172   // used: CodeGen will need it.
12173   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12174   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12175     ResolveExceptionSpec(Loc, FPT);
12176 
12177   if (!OdrUse) return;
12178 
12179   // Implicit instantiation of function templates and member functions of
12180   // class templates.
12181   if (Func->isImplicitlyInstantiable()) {
12182     bool AlreadyInstantiated = false;
12183     SourceLocation PointOfInstantiation = Loc;
12184     if (FunctionTemplateSpecializationInfo *SpecInfo
12185                               = Func->getTemplateSpecializationInfo()) {
12186       if (SpecInfo->getPointOfInstantiation().isInvalid())
12187         SpecInfo->setPointOfInstantiation(Loc);
12188       else if (SpecInfo->getTemplateSpecializationKind()
12189                  == TSK_ImplicitInstantiation) {
12190         AlreadyInstantiated = true;
12191         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12192       }
12193     } else if (MemberSpecializationInfo *MSInfo
12194                                 = Func->getMemberSpecializationInfo()) {
12195       if (MSInfo->getPointOfInstantiation().isInvalid())
12196         MSInfo->setPointOfInstantiation(Loc);
12197       else if (MSInfo->getTemplateSpecializationKind()
12198                  == TSK_ImplicitInstantiation) {
12199         AlreadyInstantiated = true;
12200         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12201       }
12202     }
12203 
12204     if (!AlreadyInstantiated || Func->isConstexpr()) {
12205       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12206           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12207           ActiveTemplateInstantiations.size())
12208         PendingLocalImplicitInstantiations.push_back(
12209             std::make_pair(Func, PointOfInstantiation));
12210       else if (Func->isConstexpr())
12211         // Do not defer instantiations of constexpr functions, to avoid the
12212         // expression evaluator needing to call back into Sema if it sees a
12213         // call to such a function.
12214         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12215       else {
12216         PendingInstantiations.push_back(std::make_pair(Func,
12217                                                        PointOfInstantiation));
12218         // Notify the consumer that a function was implicitly instantiated.
12219         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12220       }
12221     }
12222   } else {
12223     // Walk redefinitions, as some of them may be instantiable.
12224     for (auto i : Func->redecls()) {
12225       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12226         MarkFunctionReferenced(Loc, i);
12227     }
12228   }
12229 
12230   // Keep track of used but undefined functions.
12231   if (!Func->isDefined()) {
12232     if (mightHaveNonExternalLinkage(Func))
12233       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12234     else if (Func->getMostRecentDecl()->isInlined() &&
12235              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
12236              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12237       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12238   }
12239 
12240   // Normally the most current decl is marked used while processing the use and
12241   // any subsequent decls are marked used by decl merging. This fails with
12242   // template instantiation since marking can happen at the end of the file
12243   // and, because of the two phase lookup, this function is called with at
12244   // decl in the middle of a decl chain. We loop to maintain the invariant
12245   // that once a decl is used, all decls after it are also used.
12246   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12247     F->markUsed(Context);
12248     if (F == Func)
12249       break;
12250   }
12251 }
12252 
12253 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,VarDecl * var,DeclContext * DC)12254 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12255                                    VarDecl *var, DeclContext *DC) {
12256   DeclContext *VarDC = var->getDeclContext();
12257 
12258   //  If the parameter still belongs to the translation unit, then
12259   //  we're actually just using one parameter in the declaration of
12260   //  the next.
12261   if (isa<ParmVarDecl>(var) &&
12262       isa<TranslationUnitDecl>(VarDC))
12263     return;
12264 
12265   // For C code, don't diagnose about capture if we're not actually in code
12266   // right now; it's impossible to write a non-constant expression outside of
12267   // function context, so we'll get other (more useful) diagnostics later.
12268   //
12269   // For C++, things get a bit more nasty... it would be nice to suppress this
12270   // diagnostic for certain cases like using a local variable in an array bound
12271   // for a member of a local class, but the correct predicate is not obvious.
12272   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12273     return;
12274 
12275   if (isa<CXXMethodDecl>(VarDC) &&
12276       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12277     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12278       << var->getIdentifier();
12279   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12280     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12281       << var->getIdentifier() << fn->getDeclName();
12282   } else if (isa<BlockDecl>(VarDC)) {
12283     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12284       << var->getIdentifier();
12285   } else {
12286     // FIXME: Is there any other context where a local variable can be
12287     // declared?
12288     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12289       << var->getIdentifier();
12290   }
12291 
12292   S.Diag(var->getLocation(), diag::note_entity_declared_at)
12293       << var->getIdentifier();
12294 
12295   // FIXME: Add additional diagnostic info about class etc. which prevents
12296   // capture.
12297 }
12298 
12299 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)12300 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12301                                       bool &SubCapturesAreNested,
12302                                       QualType &CaptureType,
12303                                       QualType &DeclRefType) {
12304    // Check whether we've already captured it.
12305   if (CSI->CaptureMap.count(Var)) {
12306     // If we found a capture, any subcaptures are nested.
12307     SubCapturesAreNested = true;
12308 
12309     // Retrieve the capture type for this variable.
12310     CaptureType = CSI->getCapture(Var).getCaptureType();
12311 
12312     // Compute the type of an expression that refers to this variable.
12313     DeclRefType = CaptureType.getNonReferenceType();
12314 
12315     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12316     if (Cap.isCopyCapture() &&
12317         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
12318       DeclRefType.addConst();
12319     return true;
12320   }
12321   return false;
12322 }
12323 
12324 // Only block literals, captured statements, and lambda expressions can
12325 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)12326 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12327                                  SourceLocation Loc,
12328                                  const bool Diagnose, Sema &S) {
12329   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12330     return getLambdaAwareParentOfDeclContext(DC);
12331   else if (Var->hasLocalStorage()) {
12332     if (Diagnose)
12333        diagnoseUncapturableValueReference(S, Loc, Var, DC);
12334   }
12335   return nullptr;
12336 }
12337 
12338 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12339 // certain types of variables (unnamed, variably modified types etc.)
12340 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)12341 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12342                                  SourceLocation Loc,
12343                                  const bool Diagnose, Sema &S) {
12344 
12345   bool IsBlock = isa<BlockScopeInfo>(CSI);
12346   bool IsLambda = isa<LambdaScopeInfo>(CSI);
12347 
12348   // Lambdas are not allowed to capture unnamed variables
12349   // (e.g. anonymous unions).
12350   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12351   // assuming that's the intent.
12352   if (IsLambda && !Var->getDeclName()) {
12353     if (Diagnose) {
12354       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12355       S.Diag(Var->getLocation(), diag::note_declared_at);
12356     }
12357     return false;
12358   }
12359 
12360   // Prohibit variably-modified types in blocks; they're difficult to deal with.
12361   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12362     if (Diagnose) {
12363       S.Diag(Loc, diag::err_ref_vm_type);
12364       S.Diag(Var->getLocation(), diag::note_previous_decl)
12365         << Var->getDeclName();
12366     }
12367     return false;
12368   }
12369   // Prohibit structs with flexible array members too.
12370   // We cannot capture what is in the tail end of the struct.
12371   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12372     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12373       if (Diagnose) {
12374         if (IsBlock)
12375           S.Diag(Loc, diag::err_ref_flexarray_type);
12376         else
12377           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12378             << Var->getDeclName();
12379         S.Diag(Var->getLocation(), diag::note_previous_decl)
12380           << Var->getDeclName();
12381       }
12382       return false;
12383     }
12384   }
12385   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12386   // Lambdas and captured statements are not allowed to capture __block
12387   // variables; they don't support the expected semantics.
12388   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12389     if (Diagnose) {
12390       S.Diag(Loc, diag::err_capture_block_variable)
12391         << Var->getDeclName() << !IsLambda;
12392       S.Diag(Var->getLocation(), diag::note_previous_decl)
12393         << Var->getDeclName();
12394     }
12395     return false;
12396   }
12397 
12398   return true;
12399 }
12400 
12401 // 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)12402 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12403                                  SourceLocation Loc,
12404                                  const bool BuildAndDiagnose,
12405                                  QualType &CaptureType,
12406                                  QualType &DeclRefType,
12407                                  const bool Nested,
12408                                  Sema &S) {
12409   Expr *CopyExpr = nullptr;
12410   bool ByRef = false;
12411 
12412   // Blocks are not allowed to capture arrays.
12413   if (CaptureType->isArrayType()) {
12414     if (BuildAndDiagnose) {
12415       S.Diag(Loc, diag::err_ref_array_type);
12416       S.Diag(Var->getLocation(), diag::note_previous_decl)
12417       << Var->getDeclName();
12418     }
12419     return false;
12420   }
12421 
12422   // Forbid the block-capture of autoreleasing variables.
12423   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12424     if (BuildAndDiagnose) {
12425       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12426         << /*block*/ 0;
12427       S.Diag(Var->getLocation(), diag::note_previous_decl)
12428         << Var->getDeclName();
12429     }
12430     return false;
12431   }
12432   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12433   if (HasBlocksAttr || CaptureType->isReferenceType()) {
12434     // Block capture by reference does not change the capture or
12435     // declaration reference types.
12436     ByRef = true;
12437   } else {
12438     // Block capture by copy introduces 'const'.
12439     CaptureType = CaptureType.getNonReferenceType().withConst();
12440     DeclRefType = CaptureType;
12441 
12442     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12443       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12444         // The capture logic needs the destructor, so make sure we mark it.
12445         // Usually this is unnecessary because most local variables have
12446         // their destructors marked at declaration time, but parameters are
12447         // an exception because it's technically only the call site that
12448         // actually requires the destructor.
12449         if (isa<ParmVarDecl>(Var))
12450           S.FinalizeVarWithDestructor(Var, Record);
12451 
12452         // Enter a new evaluation context to insulate the copy
12453         // full-expression.
12454         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12455 
12456         // According to the blocks spec, the capture of a variable from
12457         // the stack requires a const copy constructor.  This is not true
12458         // of the copy/move done to move a __block variable to the heap.
12459         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12460                                                   DeclRefType.withConst(),
12461                                                   VK_LValue, Loc);
12462 
12463         ExprResult Result
12464           = S.PerformCopyInitialization(
12465               InitializedEntity::InitializeBlock(Var->getLocation(),
12466                                                   CaptureType, false),
12467               Loc, DeclRef);
12468 
12469         // Build a full-expression copy expression if initialization
12470         // succeeded and used a non-trivial constructor.  Recover from
12471         // errors by pretending that the copy isn't necessary.
12472         if (!Result.isInvalid() &&
12473             !cast<CXXConstructExpr>(Result.get())->getConstructor()
12474                 ->isTrivial()) {
12475           Result = S.MaybeCreateExprWithCleanups(Result);
12476           CopyExpr = Result.get();
12477         }
12478       }
12479     }
12480   }
12481 
12482   // Actually capture the variable.
12483   if (BuildAndDiagnose)
12484     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12485                     SourceLocation(), CaptureType, CopyExpr);
12486 
12487   return true;
12488 
12489 }
12490 
12491 
12492 /// \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)12493 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12494                                     VarDecl *Var,
12495                                     SourceLocation Loc,
12496                                     const bool BuildAndDiagnose,
12497                                     QualType &CaptureType,
12498                                     QualType &DeclRefType,
12499                                     const bool RefersToCapturedVariable,
12500                                     Sema &S) {
12501 
12502   // By default, capture variables by reference.
12503   bool ByRef = true;
12504   // Using an LValue reference type is consistent with Lambdas (see below).
12505   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12506   Expr *CopyExpr = nullptr;
12507   if (BuildAndDiagnose) {
12508     // The current implementation assumes that all variables are captured
12509     // by references. Since there is no capture by copy, no expression
12510     // evaluation will be needed.
12511     RecordDecl *RD = RSI->TheRecordDecl;
12512 
12513     FieldDecl *Field
12514       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
12515                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
12516                           nullptr, false, ICIS_NoInit);
12517     Field->setImplicit(true);
12518     Field->setAccess(AS_private);
12519     RD->addDecl(Field);
12520 
12521     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12522                                             DeclRefType, VK_LValue, Loc);
12523     Var->setReferenced(true);
12524     Var->markUsed(S.Context);
12525   }
12526 
12527   // Actually capture the variable.
12528   if (BuildAndDiagnose)
12529     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
12530                     SourceLocation(), CaptureType, CopyExpr);
12531 
12532 
12533   return true;
12534 }
12535 
12536 /// \brief Create a field within the lambda class for the variable
12537 ///  being captured.  Handle Array captures.
addAsFieldToClosureType(Sema & S,LambdaScopeInfo * LSI,VarDecl * Var,QualType FieldType,QualType DeclRefType,SourceLocation Loc,bool RefersToCapturedVariable)12538 static ExprResult addAsFieldToClosureType(Sema &S,
12539                                  LambdaScopeInfo *LSI,
12540                                   VarDecl *Var, QualType FieldType,
12541                                   QualType DeclRefType,
12542                                   SourceLocation Loc,
12543                                   bool RefersToCapturedVariable) {
12544   CXXRecordDecl *Lambda = LSI->Lambda;
12545 
12546   // Build the non-static data member.
12547   FieldDecl *Field
12548     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12549                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12550                         nullptr, false, ICIS_NoInit);
12551   Field->setImplicit(true);
12552   Field->setAccess(AS_private);
12553   Lambda->addDecl(Field);
12554 
12555   // C++11 [expr.prim.lambda]p21:
12556   //   When the lambda-expression is evaluated, the entities that
12557   //   are captured by copy are used to direct-initialize each
12558   //   corresponding non-static data member of the resulting closure
12559   //   object. (For array members, the array elements are
12560   //   direct-initialized in increasing subscript order.) These
12561   //   initializations are performed in the (unspecified) order in
12562   //   which the non-static data members are declared.
12563 
12564   // Introduce a new evaluation context for the initialization, so
12565   // that temporaries introduced as part of the capture are retained
12566   // to be re-"exported" from the lambda expression itself.
12567   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
12568 
12569   // C++ [expr.prim.labda]p12:
12570   //   An entity captured by a lambda-expression is odr-used (3.2) in
12571   //   the scope containing the lambda-expression.
12572   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12573                                           DeclRefType, VK_LValue, Loc);
12574   Var->setReferenced(true);
12575   Var->markUsed(S.Context);
12576 
12577   // When the field has array type, create index variables for each
12578   // dimension of the array. We use these index variables to subscript
12579   // the source array, and other clients (e.g., CodeGen) will perform
12580   // the necessary iteration with these index variables.
12581   SmallVector<VarDecl *, 4> IndexVariables;
12582   QualType BaseType = FieldType;
12583   QualType SizeType = S.Context.getSizeType();
12584   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
12585   while (const ConstantArrayType *Array
12586                         = S.Context.getAsConstantArrayType(BaseType)) {
12587     // Create the iteration variable for this array index.
12588     IdentifierInfo *IterationVarName = nullptr;
12589     {
12590       SmallString<8> Str;
12591       llvm::raw_svector_ostream OS(Str);
12592       OS << "__i" << IndexVariables.size();
12593       IterationVarName = &S.Context.Idents.get(OS.str());
12594     }
12595     VarDecl *IterationVar
12596       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12597                         IterationVarName, SizeType,
12598                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
12599                         SC_None);
12600     IndexVariables.push_back(IterationVar);
12601     LSI->ArrayIndexVars.push_back(IterationVar);
12602 
12603     // Create a reference to the iteration variable.
12604     ExprResult IterationVarRef
12605       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
12606     assert(!IterationVarRef.isInvalid() &&
12607            "Reference to invented variable cannot fail!");
12608     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
12609     assert(!IterationVarRef.isInvalid() &&
12610            "Conversion of invented variable cannot fail!");
12611 
12612     // Subscript the array with this iteration variable.
12613     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
12614                              Ref, Loc, IterationVarRef.get(), Loc);
12615     if (Subscript.isInvalid()) {
12616       S.CleanupVarDeclMarking();
12617       S.DiscardCleanupsInEvaluationContext();
12618       return ExprError();
12619     }
12620 
12621     Ref = Subscript.get();
12622     BaseType = Array->getElementType();
12623   }
12624 
12625   // Construct the entity that we will be initializing. For an array, this
12626   // will be first element in the array, which may require several levels
12627   // of array-subscript entities.
12628   SmallVector<InitializedEntity, 4> Entities;
12629   Entities.reserve(1 + IndexVariables.size());
12630   Entities.push_back(
12631     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
12632         Field->getType(), Loc));
12633   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
12634     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
12635                                                             0,
12636                                                             Entities.back()));
12637 
12638   InitializationKind InitKind
12639     = InitializationKind::CreateDirect(Loc, Loc, Loc);
12640   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
12641   ExprResult Result(true);
12642   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
12643     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
12644 
12645   // If this initialization requires any cleanups (e.g., due to a
12646   // default argument to a copy constructor), note that for the
12647   // lambda.
12648   if (S.ExprNeedsCleanups)
12649     LSI->ExprNeedsCleanups = true;
12650 
12651   // Exit the expression evaluation context used for the capture.
12652   S.CleanupVarDeclMarking();
12653   S.DiscardCleanupsInEvaluationContext();
12654   return Result;
12655 }
12656 
12657 
12658 
12659 /// \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)12660 static bool captureInLambda(LambdaScopeInfo *LSI,
12661                             VarDecl *Var,
12662                             SourceLocation Loc,
12663                             const bool BuildAndDiagnose,
12664                             QualType &CaptureType,
12665                             QualType &DeclRefType,
12666                             const bool RefersToCapturedVariable,
12667                             const Sema::TryCaptureKind Kind,
12668                             SourceLocation EllipsisLoc,
12669                             const bool IsTopScope,
12670                             Sema &S) {
12671 
12672   // Determine whether we are capturing by reference or by value.
12673   bool ByRef = false;
12674   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12675     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12676   } else {
12677     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12678   }
12679 
12680   // Compute the type of the field that will capture this variable.
12681   if (ByRef) {
12682     // C++11 [expr.prim.lambda]p15:
12683     //   An entity is captured by reference if it is implicitly or
12684     //   explicitly captured but not captured by copy. It is
12685     //   unspecified whether additional unnamed non-static data
12686     //   members are declared in the closure type for entities
12687     //   captured by reference.
12688     //
12689     // FIXME: It is not clear whether we want to build an lvalue reference
12690     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12691     // to do the former, while EDG does the latter. Core issue 1249 will
12692     // clarify, but for now we follow GCC because it's a more permissive and
12693     // easily defensible position.
12694     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12695   } else {
12696     // C++11 [expr.prim.lambda]p14:
12697     //   For each entity captured by copy, an unnamed non-static
12698     //   data member is declared in the closure type. The
12699     //   declaration order of these members is unspecified. The type
12700     //   of such a data member is the type of the corresponding
12701     //   captured entity if the entity is not a reference to an
12702     //   object, or the referenced type otherwise. [Note: If the
12703     //   captured entity is a reference to a function, the
12704     //   corresponding data member is also a reference to a
12705     //   function. - end note ]
12706     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12707       if (!RefType->getPointeeType()->isFunctionType())
12708         CaptureType = RefType->getPointeeType();
12709     }
12710 
12711     // Forbid the lambda copy-capture of autoreleasing variables.
12712     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12713       if (BuildAndDiagnose) {
12714         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12715         S.Diag(Var->getLocation(), diag::note_previous_decl)
12716           << Var->getDeclName();
12717       }
12718       return false;
12719     }
12720 
12721     // Make sure that by-copy captures are of a complete and non-abstract type.
12722     if (BuildAndDiagnose) {
12723       if (!CaptureType->isDependentType() &&
12724           S.RequireCompleteType(Loc, CaptureType,
12725                                 diag::err_capture_of_incomplete_type,
12726                                 Var->getDeclName()))
12727         return false;
12728 
12729       if (S.RequireNonAbstractType(Loc, CaptureType,
12730                                    diag::err_capture_of_abstract_type))
12731         return false;
12732     }
12733   }
12734 
12735   // Capture this variable in the lambda.
12736   Expr *CopyExpr = nullptr;
12737   if (BuildAndDiagnose) {
12738     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12739                                         CaptureType, DeclRefType, Loc,
12740                                         RefersToCapturedVariable);
12741     if (!Result.isInvalid())
12742       CopyExpr = Result.get();
12743   }
12744 
12745   // Compute the type of a reference to this captured variable.
12746   if (ByRef)
12747     DeclRefType = CaptureType.getNonReferenceType();
12748   else {
12749     // C++ [expr.prim.lambda]p5:
12750     //   The closure type for a lambda-expression has a public inline
12751     //   function call operator [...]. This function call operator is
12752     //   declared const (9.3.1) if and only if the lambda-expression’s
12753     //   parameter-declaration-clause is not followed by mutable.
12754     DeclRefType = CaptureType.getNonReferenceType();
12755     if (!LSI->Mutable && !CaptureType->isReferenceType())
12756       DeclRefType.addConst();
12757   }
12758 
12759   // Add the capture.
12760   if (BuildAndDiagnose)
12761     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
12762                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12763 
12764   return true;
12765 }
12766 
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)12767 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12768                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12769                               bool BuildAndDiagnose,
12770                               QualType &CaptureType,
12771                               QualType &DeclRefType,
12772 						                const unsigned *const FunctionScopeIndexToStopAt) {
12773   bool Nested = Var->isInitCapture();
12774 
12775   DeclContext *DC = CurContext;
12776   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12777       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12778   // We need to sync up the Declaration Context with the
12779   // FunctionScopeIndexToStopAt
12780   if (FunctionScopeIndexToStopAt) {
12781     unsigned FSIndex = FunctionScopes.size() - 1;
12782     while (FSIndex != MaxFunctionScopesIndex) {
12783       DC = getLambdaAwareParentOfDeclContext(DC);
12784       --FSIndex;
12785     }
12786   }
12787 
12788 
12789   // If the variable is declared in the current context (and is not an
12790   // init-capture), there is no need to capture it.
12791   if (!Nested && Var->getDeclContext() == DC) return true;
12792 
12793   // Capture global variables if it is required to use private copy of this
12794   // variable.
12795   bool IsGlobal = !Var->hasLocalStorage();
12796   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
12797     return true;
12798 
12799   // Walk up the stack to determine whether we can capture the variable,
12800   // performing the "simple" checks that don't depend on type. We stop when
12801   // we've either hit the declared scope of the variable or find an existing
12802   // capture of that variable.  We start from the innermost capturing-entity
12803   // (the DC) and ensure that all intervening capturing-entities
12804   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12805   // declcontext can either capture the variable or have already captured
12806   // the variable.
12807   CaptureType = Var->getType();
12808   DeclRefType = CaptureType.getNonReferenceType();
12809   bool Explicit = (Kind != TryCapture_Implicit);
12810   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12811   do {
12812     // Only block literals, captured statements, and lambda expressions can
12813     // capture; other scopes don't work.
12814     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12815                                                               ExprLoc,
12816                                                               BuildAndDiagnose,
12817                                                               *this);
12818     // We need to check for the parent *first* because, if we *have*
12819     // private-captured a global variable, we need to recursively capture it in
12820     // intermediate blocks, lambdas, etc.
12821     if (!ParentDC) {
12822       if (IsGlobal) {
12823         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
12824         break;
12825       }
12826       return true;
12827     }
12828 
12829     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12830     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12831 
12832 
12833     // Check whether we've already captured it.
12834     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12835                                              DeclRefType))
12836       break;
12837     // If we are instantiating a generic lambda call operator body,
12838     // we do not want to capture new variables.  What was captured
12839     // during either a lambdas transformation or initial parsing
12840     // should be used.
12841     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12842       if (BuildAndDiagnose) {
12843         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12844         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12845           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12846           Diag(Var->getLocation(), diag::note_previous_decl)
12847              << Var->getDeclName();
12848           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12849         } else
12850           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12851       }
12852       return true;
12853     }
12854     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12855     // certain types of variables (unnamed, variably modified types etc.)
12856     // so check for eligibility.
12857     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12858        return true;
12859 
12860     // Try to capture variable-length arrays types.
12861     if (Var->getType()->isVariablyModifiedType()) {
12862       // We're going to walk down into the type and look for VLA
12863       // expressions.
12864       QualType QTy = Var->getType();
12865       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12866         QTy = PVD->getOriginalType();
12867       do {
12868         const Type *Ty = QTy.getTypePtr();
12869         switch (Ty->getTypeClass()) {
12870 #define TYPE(Class, Base)
12871 #define ABSTRACT_TYPE(Class, Base)
12872 #define NON_CANONICAL_TYPE(Class, Base)
12873 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12874 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12875 #include "clang/AST/TypeNodes.def"
12876           QTy = QualType();
12877           break;
12878         // These types are never variably-modified.
12879         case Type::Builtin:
12880         case Type::Complex:
12881         case Type::Vector:
12882         case Type::ExtVector:
12883         case Type::Record:
12884         case Type::Enum:
12885         case Type::Elaborated:
12886         case Type::TemplateSpecialization:
12887         case Type::ObjCObject:
12888         case Type::ObjCInterface:
12889         case Type::ObjCObjectPointer:
12890           llvm_unreachable("type class is never variably-modified!");
12891         case Type::Adjusted:
12892           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12893           break;
12894         case Type::Decayed:
12895           QTy = cast<DecayedType>(Ty)->getPointeeType();
12896           break;
12897         case Type::Pointer:
12898           QTy = cast<PointerType>(Ty)->getPointeeType();
12899           break;
12900         case Type::BlockPointer:
12901           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12902           break;
12903         case Type::LValueReference:
12904         case Type::RValueReference:
12905           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12906           break;
12907         case Type::MemberPointer:
12908           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12909           break;
12910         case Type::ConstantArray:
12911         case Type::IncompleteArray:
12912           // Losing element qualification here is fine.
12913           QTy = cast<ArrayType>(Ty)->getElementType();
12914           break;
12915         case Type::VariableArray: {
12916           // Losing element qualification here is fine.
12917           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12918 
12919           // Unknown size indication requires no size computation.
12920           // Otherwise, evaluate and record it.
12921           if (auto Size = VAT->getSizeExpr()) {
12922             if (!CSI->isVLATypeCaptured(VAT)) {
12923               RecordDecl *CapRecord = nullptr;
12924               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12925                 CapRecord = LSI->Lambda;
12926               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12927                 CapRecord = CRSI->TheRecordDecl;
12928               }
12929               if (CapRecord) {
12930                 auto ExprLoc = Size->getExprLoc();
12931                 auto SizeType = Context.getSizeType();
12932                 // Build the non-static data member.
12933                 auto Field = FieldDecl::Create(
12934                     Context, CapRecord, ExprLoc, ExprLoc,
12935                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12936                     /*BW*/ nullptr, /*Mutable*/ false,
12937                     /*InitStyle*/ ICIS_NoInit);
12938                 Field->setImplicit(true);
12939                 Field->setAccess(AS_private);
12940                 Field->setCapturedVLAType(VAT);
12941                 CapRecord->addDecl(Field);
12942 
12943                 CSI->addVLATypeCapture(ExprLoc, SizeType);
12944               }
12945             }
12946           }
12947           QTy = VAT->getElementType();
12948           break;
12949         }
12950         case Type::FunctionProto:
12951         case Type::FunctionNoProto:
12952           QTy = cast<FunctionType>(Ty)->getReturnType();
12953           break;
12954         case Type::Paren:
12955         case Type::TypeOf:
12956         case Type::UnaryTransform:
12957         case Type::Attributed:
12958         case Type::SubstTemplateTypeParm:
12959         case Type::PackExpansion:
12960           // Keep walking after single level desugaring.
12961           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12962           break;
12963         case Type::Typedef:
12964           QTy = cast<TypedefType>(Ty)->desugar();
12965           break;
12966         case Type::Decltype:
12967           QTy = cast<DecltypeType>(Ty)->desugar();
12968           break;
12969         case Type::Auto:
12970           QTy = cast<AutoType>(Ty)->getDeducedType();
12971           break;
12972         case Type::TypeOfExpr:
12973           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12974           break;
12975         case Type::Atomic:
12976           QTy = cast<AtomicType>(Ty)->getValueType();
12977           break;
12978         }
12979       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12980     }
12981 
12982     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12983       // No capture-default, and this is not an explicit capture
12984       // so cannot capture this variable.
12985       if (BuildAndDiagnose) {
12986         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12987         Diag(Var->getLocation(), diag::note_previous_decl)
12988           << Var->getDeclName();
12989         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12990              diag::note_lambda_decl);
12991         // FIXME: If we error out because an outer lambda can not implicitly
12992         // capture a variable that an inner lambda explicitly captures, we
12993         // should have the inner lambda do the explicit capture - because
12994         // it makes for cleaner diagnostics later.  This would purely be done
12995         // so that the diagnostic does not misleadingly claim that a variable
12996         // can not be captured by a lambda implicitly even though it is captured
12997         // explicitly.  Suggestion:
12998         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12999         //    at the function head
13000         //  - cache the StartingDeclContext - this must be a lambda
13001         //  - captureInLambda in the innermost lambda the variable.
13002       }
13003       return true;
13004     }
13005 
13006     FunctionScopesIndex--;
13007     DC = ParentDC;
13008     Explicit = false;
13009   } while (!Var->getDeclContext()->Equals(DC));
13010 
13011   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13012   // computing the type of the capture at each step, checking type-specific
13013   // requirements, and adding captures if requested.
13014   // If the variable had already been captured previously, we start capturing
13015   // at the lambda nested within that one.
13016   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13017        ++I) {
13018     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13019 
13020     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13021       if (!captureInBlock(BSI, Var, ExprLoc,
13022                           BuildAndDiagnose, CaptureType,
13023                           DeclRefType, Nested, *this))
13024         return true;
13025       Nested = true;
13026     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13027       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13028                                    BuildAndDiagnose, CaptureType,
13029                                    DeclRefType, Nested, *this))
13030         return true;
13031       Nested = true;
13032     } else {
13033       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13034       if (!captureInLambda(LSI, Var, ExprLoc,
13035                            BuildAndDiagnose, CaptureType,
13036                            DeclRefType, Nested, Kind, EllipsisLoc,
13037                             /*IsTopScope*/I == N - 1, *this))
13038         return true;
13039       Nested = true;
13040     }
13041   }
13042   return false;
13043 }
13044 
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)13045 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13046                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13047   QualType CaptureType;
13048   QualType DeclRefType;
13049   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13050                             /*BuildAndDiagnose=*/true, CaptureType,
13051                             DeclRefType, nullptr);
13052 }
13053 
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)13054 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13055   QualType CaptureType;
13056   QualType DeclRefType;
13057   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13058                              /*BuildAndDiagnose=*/false, CaptureType,
13059                              DeclRefType, nullptr);
13060 }
13061 
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)13062 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13063   QualType CaptureType;
13064   QualType DeclRefType;
13065 
13066   // Determine whether we can capture this variable.
13067   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13068                          /*BuildAndDiagnose=*/false, CaptureType,
13069                          DeclRefType, nullptr))
13070     return QualType();
13071 
13072   return DeclRefType;
13073 }
13074 
13075 
13076 
13077 // If either the type of the variable or the initializer is dependent,
13078 // return false. Otherwise, determine whether the variable is a constant
13079 // expression. Use this if you need to know if a variable that might or
13080 // might not be dependent is truly a constant expression.
IsVariableNonDependentAndAConstantExpression(VarDecl * Var,ASTContext & Context)13081 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13082     ASTContext &Context) {
13083 
13084   if (Var->getType()->isDependentType())
13085     return false;
13086   const VarDecl *DefVD = nullptr;
13087   Var->getAnyInitializer(DefVD);
13088   if (!DefVD)
13089     return false;
13090   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13091   Expr *Init = cast<Expr>(Eval->Value);
13092   if (Init->isValueDependent())
13093     return false;
13094   return IsVariableAConstantExpression(Var, Context);
13095 }
13096 
13097 
UpdateMarkingForLValueToRValue(Expr * E)13098 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13099   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13100   // an object that satisfies the requirements for appearing in a
13101   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13102   // is immediately applied."  This function handles the lvalue-to-rvalue
13103   // conversion part.
13104   MaybeODRUseExprs.erase(E->IgnoreParens());
13105 
13106   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13107   // to a variable that is a constant expression, and if so, identify it as
13108   // a reference to a variable that does not involve an odr-use of that
13109   // variable.
13110   if (LambdaScopeInfo *LSI = getCurLambda()) {
13111     Expr *SansParensExpr = E->IgnoreParens();
13112     VarDecl *Var = nullptr;
13113     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13114       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13115     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13116       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13117 
13118     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13119       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13120   }
13121 }
13122 
ActOnConstantExpression(ExprResult Res)13123 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13124   Res = CorrectDelayedTyposInExpr(Res);
13125 
13126   if (!Res.isUsable())
13127     return Res;
13128 
13129   // If a constant-expression is a reference to a variable where we delay
13130   // deciding whether it is an odr-use, just assume we will apply the
13131   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13132   // (a non-type template argument), we have special handling anyway.
13133   UpdateMarkingForLValueToRValue(Res.get());
13134   return Res;
13135 }
13136 
CleanupVarDeclMarking()13137 void Sema::CleanupVarDeclMarking() {
13138   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13139                                         e = MaybeODRUseExprs.end();
13140        i != e; ++i) {
13141     VarDecl *Var;
13142     SourceLocation Loc;
13143     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
13144       Var = cast<VarDecl>(DRE->getDecl());
13145       Loc = DRE->getLocation();
13146     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13147       Var = cast<VarDecl>(ME->getMemberDecl());
13148       Loc = ME->getMemberLoc();
13149     } else {
13150       llvm_unreachable("Unexpected expression");
13151     }
13152 
13153     MarkVarDeclODRUsed(Var, Loc, *this,
13154                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13155   }
13156 
13157   MaybeODRUseExprs.clear();
13158 }
13159 
13160 
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)13161 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13162                                     VarDecl *Var, Expr *E) {
13163   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13164          "Invalid Expr argument to DoMarkVarDeclReferenced");
13165   Var->setReferenced();
13166 
13167   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13168   bool MarkODRUsed = true;
13169 
13170   // If the context is not potentially evaluated, this is not an odr-use and
13171   // does not trigger instantiation.
13172   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13173     if (SemaRef.isUnevaluatedContext())
13174       return;
13175 
13176     // If we don't yet know whether this context is going to end up being an
13177     // evaluated context, and we're referencing a variable from an enclosing
13178     // scope, add a potential capture.
13179     //
13180     // FIXME: Is this necessary? These contexts are only used for default
13181     // arguments, where local variables can't be used.
13182     const bool RefersToEnclosingScope =
13183         (SemaRef.CurContext != Var->getDeclContext() &&
13184          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13185     if (RefersToEnclosingScope) {
13186       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13187         // If a variable could potentially be odr-used, defer marking it so
13188         // until we finish analyzing the full expression for any
13189         // lvalue-to-rvalue
13190         // or discarded value conversions that would obviate odr-use.
13191         // Add it to the list of potential captures that will be analyzed
13192         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13193         // unless the variable is a reference that was initialized by a constant
13194         // expression (this will never need to be captured or odr-used).
13195         assert(E && "Capture variable should be used in an expression.");
13196         if (!Var->getType()->isReferenceType() ||
13197             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13198           LSI->addPotentialCapture(E->IgnoreParens());
13199       }
13200     }
13201 
13202     if (!isTemplateInstantiation(TSK))
13203     	return;
13204 
13205     // Instantiate, but do not mark as odr-used, variable templates.
13206     MarkODRUsed = false;
13207   }
13208 
13209   VarTemplateSpecializationDecl *VarSpec =
13210       dyn_cast<VarTemplateSpecializationDecl>(Var);
13211   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13212          "Can't instantiate a partial template specialization.");
13213 
13214   // Perform implicit instantiation of static data members, static data member
13215   // templates of class templates, and variable template specializations. Delay
13216   // instantiations of variable templates, except for those that could be used
13217   // in a constant expression.
13218   if (isTemplateInstantiation(TSK)) {
13219     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13220 
13221     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13222       if (Var->getPointOfInstantiation().isInvalid()) {
13223         // This is a modification of an existing AST node. Notify listeners.
13224         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13225           L->StaticDataMemberInstantiated(Var);
13226       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13227         // Don't bother trying to instantiate it again, unless we might need
13228         // its initializer before we get to the end of the TU.
13229         TryInstantiating = false;
13230     }
13231 
13232     if (Var->getPointOfInstantiation().isInvalid())
13233       Var->setTemplateSpecializationKind(TSK, Loc);
13234 
13235     if (TryInstantiating) {
13236       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13237       bool InstantiationDependent = false;
13238       bool IsNonDependent =
13239           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13240                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13241                   : true;
13242 
13243       // Do not instantiate specializations that are still type-dependent.
13244       if (IsNonDependent) {
13245         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13246           // Do not defer instantiations of variables which could be used in a
13247           // constant expression.
13248           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13249         } else {
13250           SemaRef.PendingInstantiations
13251               .push_back(std::make_pair(Var, PointOfInstantiation));
13252         }
13253       }
13254     }
13255   }
13256 
13257   if(!MarkODRUsed) return;
13258 
13259   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13260   // the requirements for appearing in a constant expression (5.19) and, if
13261   // it is an object, the lvalue-to-rvalue conversion (4.1)
13262   // is immediately applied."  We check the first part here, and
13263   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13264   // Note that we use the C++11 definition everywhere because nothing in
13265   // C++03 depends on whether we get the C++03 version correct. The second
13266   // part does not apply to references, since they are not objects.
13267   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13268     // A reference initialized by a constant expression can never be
13269     // odr-used, so simply ignore it.
13270     if (!Var->getType()->isReferenceType())
13271       SemaRef.MaybeODRUseExprs.insert(E);
13272   } else
13273     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13274                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13275 }
13276 
13277 /// \brief Mark a variable referenced, and check whether it is odr-used
13278 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13279 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)13280 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13281   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13282 }
13283 
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool OdrUse)13284 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13285                                Decl *D, Expr *E, bool OdrUse) {
13286   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13287     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13288     return;
13289   }
13290 
13291   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13292 
13293   // If this is a call to a method via a cast, also mark the method in the
13294   // derived class used in case codegen can devirtualize the call.
13295   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13296   if (!ME)
13297     return;
13298   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13299   if (!MD)
13300     return;
13301   // Only attempt to devirtualize if this is truly a virtual call.
13302   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
13303   if (!IsVirtualCall)
13304     return;
13305   const Expr *Base = ME->getBase();
13306   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13307   if (!MostDerivedClassDecl)
13308     return;
13309   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13310   if (!DM || DM->isPure())
13311     return;
13312   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13313 }
13314 
13315 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E)13316 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13317   // TODO: update this with DR# once a defect report is filed.
13318   // C++11 defect. The address of a pure member should not be an ODR use, even
13319   // if it's a qualified reference.
13320   bool OdrUse = true;
13321   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13322     if (Method->isVirtual())
13323       OdrUse = false;
13324   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13325 }
13326 
13327 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)13328 void Sema::MarkMemberReferenced(MemberExpr *E) {
13329   // C++11 [basic.def.odr]p2:
13330   //   A non-overloaded function whose name appears as a potentially-evaluated
13331   //   expression or a member of a set of candidate functions, if selected by
13332   //   overload resolution when referred to from a potentially-evaluated
13333   //   expression, is odr-used, unless it is a pure virtual function and its
13334   //   name is not explicitly qualified.
13335   bool OdrUse = true;
13336   if (!E->hasQualifier()) {
13337     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13338       if (Method->isPure())
13339         OdrUse = false;
13340   }
13341   SourceLocation Loc = E->getMemberLoc().isValid() ?
13342                             E->getMemberLoc() : E->getLocStart();
13343   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13344 }
13345 
13346 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13347 /// marks the declaration referenced, and performs odr-use checking for
13348 /// functions and variables. This method should not be used when building a
13349 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool OdrUse)13350 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13351   if (OdrUse) {
13352     if (auto *VD = dyn_cast<VarDecl>(D)) {
13353       MarkVariableReferenced(Loc, VD);
13354       return;
13355     }
13356   }
13357   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13358     MarkFunctionReferenced(Loc, FD, OdrUse);
13359     return;
13360   }
13361   D->setReferenced();
13362 }
13363 
13364 namespace {
13365   // Mark all of the declarations referenced
13366   // FIXME: Not fully implemented yet! We need to have a better understanding
13367   // of when we're entering
13368   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13369     Sema &S;
13370     SourceLocation Loc;
13371 
13372   public:
13373     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13374 
MarkReferencedDecls(Sema & S,SourceLocation Loc)13375     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13376 
13377     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13378     bool TraverseRecordType(RecordType *T);
13379   };
13380 }
13381 
TraverseTemplateArgument(const TemplateArgument & Arg)13382 bool MarkReferencedDecls::TraverseTemplateArgument(
13383     const TemplateArgument &Arg) {
13384   if (Arg.getKind() == TemplateArgument::Declaration) {
13385     if (Decl *D = Arg.getAsDecl())
13386       S.MarkAnyDeclReferenced(Loc, D, true);
13387   }
13388 
13389   return Inherited::TraverseTemplateArgument(Arg);
13390 }
13391 
TraverseRecordType(RecordType * T)13392 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13393   if (ClassTemplateSpecializationDecl *Spec
13394                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13395     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13396     return TraverseTemplateArguments(Args.data(), Args.size());
13397   }
13398 
13399   return true;
13400 }
13401 
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)13402 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13403   MarkReferencedDecls Marker(*this, Loc);
13404   Marker.TraverseType(Context.getCanonicalType(T));
13405 }
13406 
13407 namespace {
13408   /// \brief Helper class that marks all of the declarations referenced by
13409   /// potentially-evaluated subexpressions as "referenced".
13410   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13411     Sema &S;
13412     bool SkipLocalVariables;
13413 
13414   public:
13415     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13416 
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)13417     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13418       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13419 
VisitDeclRefExpr(DeclRefExpr * E)13420     void VisitDeclRefExpr(DeclRefExpr *E) {
13421       // If we were asked not to visit local variables, don't.
13422       if (SkipLocalVariables) {
13423         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13424           if (VD->hasLocalStorage())
13425             return;
13426       }
13427 
13428       S.MarkDeclRefReferenced(E);
13429     }
13430 
VisitMemberExpr(MemberExpr * E)13431     void VisitMemberExpr(MemberExpr *E) {
13432       S.MarkMemberReferenced(E);
13433       Inherited::VisitMemberExpr(E);
13434     }
13435 
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)13436     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13437       S.MarkFunctionReferenced(E->getLocStart(),
13438             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13439       Visit(E->getSubExpr());
13440     }
13441 
VisitCXXNewExpr(CXXNewExpr * E)13442     void VisitCXXNewExpr(CXXNewExpr *E) {
13443       if (E->getOperatorNew())
13444         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13445       if (E->getOperatorDelete())
13446         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13447       Inherited::VisitCXXNewExpr(E);
13448     }
13449 
VisitCXXDeleteExpr(CXXDeleteExpr * E)13450     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13451       if (E->getOperatorDelete())
13452         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13453       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13454       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13455         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13456         S.MarkFunctionReferenced(E->getLocStart(),
13457                                     S.LookupDestructor(Record));
13458       }
13459 
13460       Inherited::VisitCXXDeleteExpr(E);
13461     }
13462 
VisitCXXConstructExpr(CXXConstructExpr * E)13463     void VisitCXXConstructExpr(CXXConstructExpr *E) {
13464       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13465       Inherited::VisitCXXConstructExpr(E);
13466     }
13467 
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * E)13468     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13469       Visit(E->getExpr());
13470     }
13471 
VisitImplicitCastExpr(ImplicitCastExpr * E)13472     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13473       Inherited::VisitImplicitCastExpr(E);
13474 
13475       if (E->getCastKind() == CK_LValueToRValue)
13476         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13477     }
13478   };
13479 }
13480 
13481 /// \brief Mark any declarations that appear within this expression or any
13482 /// potentially-evaluated subexpressions as "referenced".
13483 ///
13484 /// \param SkipLocalVariables If true, don't mark local variables as
13485 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)13486 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13487                                             bool SkipLocalVariables) {
13488   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13489 }
13490 
13491 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13492 /// of the program being compiled.
13493 ///
13494 /// This routine emits the given diagnostic when the code currently being
13495 /// type-checked is "potentially evaluated", meaning that there is a
13496 /// possibility that the code will actually be executable. Code in sizeof()
13497 /// expressions, code used only during overload resolution, etc., are not
13498 /// potentially evaluated. This routine will suppress such diagnostics or,
13499 /// in the absolutely nutty case of potentially potentially evaluated
13500 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13501 /// later.
13502 ///
13503 /// This routine should be used for all diagnostics that describe the run-time
13504 /// behavior of a program, such as passing a non-POD value through an ellipsis.
13505 /// Failure to do so will likely result in spurious diagnostics or failures
13506 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)13507 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13508                                const PartialDiagnostic &PD) {
13509   switch (ExprEvalContexts.back().Context) {
13510   case Unevaluated:
13511   case UnevaluatedAbstract:
13512     // The argument will never be evaluated, so don't complain.
13513     break;
13514 
13515   case ConstantEvaluated:
13516     // Relevant diagnostics should be produced by constant evaluation.
13517     break;
13518 
13519   case PotentiallyEvaluated:
13520   case PotentiallyEvaluatedIfUsed:
13521     if (Statement && getCurFunctionOrMethodDecl()) {
13522       FunctionScopes.back()->PossiblyUnreachableDiags.
13523         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13524     }
13525     else
13526       Diag(Loc, PD);
13527 
13528     return true;
13529   }
13530 
13531   return false;
13532 }
13533 
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)13534 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13535                                CallExpr *CE, FunctionDecl *FD) {
13536   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13537     return false;
13538 
13539   // If we're inside a decltype's expression, don't check for a valid return
13540   // type or construct temporaries until we know whether this is the last call.
13541   if (ExprEvalContexts.back().IsDecltype) {
13542     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13543     return false;
13544   }
13545 
13546   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13547     FunctionDecl *FD;
13548     CallExpr *CE;
13549 
13550   public:
13551     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13552       : FD(FD), CE(CE) { }
13553 
13554     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13555       if (!FD) {
13556         S.Diag(Loc, diag::err_call_incomplete_return)
13557           << T << CE->getSourceRange();
13558         return;
13559       }
13560 
13561       S.Diag(Loc, diag::err_call_function_incomplete_return)
13562         << CE->getSourceRange() << FD->getDeclName() << T;
13563       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13564           << FD->getDeclName();
13565     }
13566   } Diagnoser(FD, CE);
13567 
13568   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13569     return true;
13570 
13571   return false;
13572 }
13573 
13574 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13575 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)13576 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13577   SourceLocation Loc;
13578 
13579   unsigned diagnostic = diag::warn_condition_is_assignment;
13580   bool IsOrAssign = false;
13581 
13582   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13583     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13584       return;
13585 
13586     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13587 
13588     // Greylist some idioms by putting them into a warning subcategory.
13589     if (ObjCMessageExpr *ME
13590           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13591       Selector Sel = ME->getSelector();
13592 
13593       // self = [<foo> init...]
13594       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13595         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13596 
13597       // <foo> = [<bar> nextObject]
13598       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13599         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13600     }
13601 
13602     Loc = Op->getOperatorLoc();
13603   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13604     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13605       return;
13606 
13607     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13608     Loc = Op->getOperatorLoc();
13609   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13610     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13611   else {
13612     // Not an assignment.
13613     return;
13614   }
13615 
13616   Diag(Loc, diagnostic) << E->getSourceRange();
13617 
13618   SourceLocation Open = E->getLocStart();
13619   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
13620   Diag(Loc, diag::note_condition_assign_silence)
13621         << FixItHint::CreateInsertion(Open, "(")
13622         << FixItHint::CreateInsertion(Close, ")");
13623 
13624   if (IsOrAssign)
13625     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13626       << FixItHint::CreateReplacement(Loc, "!=");
13627   else
13628     Diag(Loc, diag::note_condition_assign_to_comparison)
13629       << FixItHint::CreateReplacement(Loc, "==");
13630 }
13631 
13632 /// \brief Redundant parentheses over an equality comparison can indicate
13633 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)13634 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13635   // Don't warn if the parens came from a macro.
13636   SourceLocation parenLoc = ParenE->getLocStart();
13637   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13638     return;
13639   // Don't warn for dependent expressions.
13640   if (ParenE->isTypeDependent())
13641     return;
13642 
13643   Expr *E = ParenE->IgnoreParens();
13644 
13645   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13646     if (opE->getOpcode() == BO_EQ &&
13647         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13648                                                            == Expr::MLV_Valid) {
13649       SourceLocation Loc = opE->getOperatorLoc();
13650 
13651       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13652       SourceRange ParenERange = ParenE->getSourceRange();
13653       Diag(Loc, diag::note_equality_comparison_silence)
13654         << FixItHint::CreateRemoval(ParenERange.getBegin())
13655         << FixItHint::CreateRemoval(ParenERange.getEnd());
13656       Diag(Loc, diag::note_equality_comparison_to_assign)
13657         << FixItHint::CreateReplacement(Loc, "=");
13658     }
13659 }
13660 
CheckBooleanCondition(Expr * E,SourceLocation Loc)13661 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13662   DiagnoseAssignmentAsCondition(E);
13663   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13664     DiagnoseEqualityWithExtraParens(parenE);
13665 
13666   ExprResult result = CheckPlaceholderExpr(E);
13667   if (result.isInvalid()) return ExprError();
13668   E = result.get();
13669 
13670   if (!E->isTypeDependent()) {
13671     if (getLangOpts().CPlusPlus)
13672       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13673 
13674     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13675     if (ERes.isInvalid())
13676       return ExprError();
13677     E = ERes.get();
13678 
13679     QualType T = E->getType();
13680     if (!T->isScalarType()) { // C99 6.8.4.1p1
13681       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13682         << T << E->getSourceRange();
13683       return ExprError();
13684     }
13685     CheckBoolLikeConversion(E, Loc);
13686   }
13687 
13688   return E;
13689 }
13690 
ActOnBooleanCondition(Scope * S,SourceLocation Loc,Expr * SubExpr)13691 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13692                                        Expr *SubExpr) {
13693   if (!SubExpr)
13694     return ExprError();
13695 
13696   return CheckBooleanCondition(SubExpr, Loc);
13697 }
13698 
13699 namespace {
13700   /// A visitor for rebuilding a call to an __unknown_any expression
13701   /// to have an appropriate type.
13702   struct RebuildUnknownAnyFunction
13703     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13704 
13705     Sema &S;
13706 
RebuildUnknownAnyFunction__anon76e074960b11::RebuildUnknownAnyFunction13707     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13708 
VisitStmt__anon76e074960b11::RebuildUnknownAnyFunction13709     ExprResult VisitStmt(Stmt *S) {
13710       llvm_unreachable("unexpected statement!");
13711     }
13712 
VisitExpr__anon76e074960b11::RebuildUnknownAnyFunction13713     ExprResult VisitExpr(Expr *E) {
13714       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13715         << E->getSourceRange();
13716       return ExprError();
13717     }
13718 
13719     /// Rebuild an expression which simply semantically wraps another
13720     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon76e074960b11::RebuildUnknownAnyFunction13721     template <class T> ExprResult rebuildSugarExpr(T *E) {
13722       ExprResult SubResult = Visit(E->getSubExpr());
13723       if (SubResult.isInvalid()) return ExprError();
13724 
13725       Expr *SubExpr = SubResult.get();
13726       E->setSubExpr(SubExpr);
13727       E->setType(SubExpr->getType());
13728       E->setValueKind(SubExpr->getValueKind());
13729       assert(E->getObjectKind() == OK_Ordinary);
13730       return E;
13731     }
13732 
VisitParenExpr__anon76e074960b11::RebuildUnknownAnyFunction13733     ExprResult VisitParenExpr(ParenExpr *E) {
13734       return rebuildSugarExpr(E);
13735     }
13736 
VisitUnaryExtension__anon76e074960b11::RebuildUnknownAnyFunction13737     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13738       return rebuildSugarExpr(E);
13739     }
13740 
VisitUnaryAddrOf__anon76e074960b11::RebuildUnknownAnyFunction13741     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13742       ExprResult SubResult = Visit(E->getSubExpr());
13743       if (SubResult.isInvalid()) return ExprError();
13744 
13745       Expr *SubExpr = SubResult.get();
13746       E->setSubExpr(SubExpr);
13747       E->setType(S.Context.getPointerType(SubExpr->getType()));
13748       assert(E->getValueKind() == VK_RValue);
13749       assert(E->getObjectKind() == OK_Ordinary);
13750       return E;
13751     }
13752 
resolveDecl__anon76e074960b11::RebuildUnknownAnyFunction13753     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13754       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13755 
13756       E->setType(VD->getType());
13757 
13758       assert(E->getValueKind() == VK_RValue);
13759       if (S.getLangOpts().CPlusPlus &&
13760           !(isa<CXXMethodDecl>(VD) &&
13761             cast<CXXMethodDecl>(VD)->isInstance()))
13762         E->setValueKind(VK_LValue);
13763 
13764       return E;
13765     }
13766 
VisitMemberExpr__anon76e074960b11::RebuildUnknownAnyFunction13767     ExprResult VisitMemberExpr(MemberExpr *E) {
13768       return resolveDecl(E, E->getMemberDecl());
13769     }
13770 
VisitDeclRefExpr__anon76e074960b11::RebuildUnknownAnyFunction13771     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13772       return resolveDecl(E, E->getDecl());
13773     }
13774   };
13775 }
13776 
13777 /// Given a function expression of unknown-any type, try to rebuild it
13778 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)13779 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13780   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13781   if (Result.isInvalid()) return ExprError();
13782   return S.DefaultFunctionArrayConversion(Result.get());
13783 }
13784 
13785 namespace {
13786   /// A visitor for rebuilding an expression of type __unknown_anytype
13787   /// into one which resolves the type directly on the referring
13788   /// expression.  Strict preservation of the original source
13789   /// structure is not a goal.
13790   struct RebuildUnknownAnyExpr
13791     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13792 
13793     Sema &S;
13794 
13795     /// The current destination type.
13796     QualType DestType;
13797 
RebuildUnknownAnyExpr__anon76e074960c11::RebuildUnknownAnyExpr13798     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13799       : S(S), DestType(CastType) {}
13800 
VisitStmt__anon76e074960c11::RebuildUnknownAnyExpr13801     ExprResult VisitStmt(Stmt *S) {
13802       llvm_unreachable("unexpected statement!");
13803     }
13804 
VisitExpr__anon76e074960c11::RebuildUnknownAnyExpr13805     ExprResult VisitExpr(Expr *E) {
13806       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13807         << E->getSourceRange();
13808       return ExprError();
13809     }
13810 
13811     ExprResult VisitCallExpr(CallExpr *E);
13812     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13813 
13814     /// Rebuild an expression which simply semantically wraps another
13815     /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon76e074960c11::RebuildUnknownAnyExpr13816     template <class T> ExprResult rebuildSugarExpr(T *E) {
13817       ExprResult SubResult = Visit(E->getSubExpr());
13818       if (SubResult.isInvalid()) return ExprError();
13819       Expr *SubExpr = SubResult.get();
13820       E->setSubExpr(SubExpr);
13821       E->setType(SubExpr->getType());
13822       E->setValueKind(SubExpr->getValueKind());
13823       assert(E->getObjectKind() == OK_Ordinary);
13824       return E;
13825     }
13826 
VisitParenExpr__anon76e074960c11::RebuildUnknownAnyExpr13827     ExprResult VisitParenExpr(ParenExpr *E) {
13828       return rebuildSugarExpr(E);
13829     }
13830 
VisitUnaryExtension__anon76e074960c11::RebuildUnknownAnyExpr13831     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13832       return rebuildSugarExpr(E);
13833     }
13834 
VisitUnaryAddrOf__anon76e074960c11::RebuildUnknownAnyExpr13835     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13836       const PointerType *Ptr = DestType->getAs<PointerType>();
13837       if (!Ptr) {
13838         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13839           << E->getSourceRange();
13840         return ExprError();
13841       }
13842       assert(E->getValueKind() == VK_RValue);
13843       assert(E->getObjectKind() == OK_Ordinary);
13844       E->setType(DestType);
13845 
13846       // Build the sub-expression as if it were an object of the pointee type.
13847       DestType = Ptr->getPointeeType();
13848       ExprResult SubResult = Visit(E->getSubExpr());
13849       if (SubResult.isInvalid()) return ExprError();
13850       E->setSubExpr(SubResult.get());
13851       return E;
13852     }
13853 
13854     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13855 
13856     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13857 
VisitMemberExpr__anon76e074960c11::RebuildUnknownAnyExpr13858     ExprResult VisitMemberExpr(MemberExpr *E) {
13859       return resolveDecl(E, E->getMemberDecl());
13860     }
13861 
VisitDeclRefExpr__anon76e074960c11::RebuildUnknownAnyExpr13862     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13863       return resolveDecl(E, E->getDecl());
13864     }
13865   };
13866 }
13867 
13868 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)13869 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13870   Expr *CalleeExpr = E->getCallee();
13871 
13872   enum FnKind {
13873     FK_MemberFunction,
13874     FK_FunctionPointer,
13875     FK_BlockPointer
13876   };
13877 
13878   FnKind Kind;
13879   QualType CalleeType = CalleeExpr->getType();
13880   if (CalleeType == S.Context.BoundMemberTy) {
13881     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13882     Kind = FK_MemberFunction;
13883     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13884   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13885     CalleeType = Ptr->getPointeeType();
13886     Kind = FK_FunctionPointer;
13887   } else {
13888     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13889     Kind = FK_BlockPointer;
13890   }
13891   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13892 
13893   // Verify that this is a legal result type of a function.
13894   if (DestType->isArrayType() || DestType->isFunctionType()) {
13895     unsigned diagID = diag::err_func_returning_array_function;
13896     if (Kind == FK_BlockPointer)
13897       diagID = diag::err_block_returning_array_function;
13898 
13899     S.Diag(E->getExprLoc(), diagID)
13900       << DestType->isFunctionType() << DestType;
13901     return ExprError();
13902   }
13903 
13904   // Otherwise, go ahead and set DestType as the call's result.
13905   E->setType(DestType.getNonLValueExprType(S.Context));
13906   E->setValueKind(Expr::getValueKindForType(DestType));
13907   assert(E->getObjectKind() == OK_Ordinary);
13908 
13909   // Rebuild the function type, replacing the result type with DestType.
13910   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13911   if (Proto) {
13912     // __unknown_anytype(...) is a special case used by the debugger when
13913     // it has no idea what a function's signature is.
13914     //
13915     // We want to build this call essentially under the K&R
13916     // unprototyped rules, but making a FunctionNoProtoType in C++
13917     // would foul up all sorts of assumptions.  However, we cannot
13918     // simply pass all arguments as variadic arguments, nor can we
13919     // portably just call the function under a non-variadic type; see
13920     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13921     // However, it turns out that in practice it is generally safe to
13922     // call a function declared as "A foo(B,C,D);" under the prototype
13923     // "A foo(B,C,D,...);".  The only known exception is with the
13924     // Windows ABI, where any variadic function is implicitly cdecl
13925     // regardless of its normal CC.  Therefore we change the parameter
13926     // types to match the types of the arguments.
13927     //
13928     // This is a hack, but it is far superior to moving the
13929     // corresponding target-specific code from IR-gen to Sema/AST.
13930 
13931     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13932     SmallVector<QualType, 8> ArgTypes;
13933     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13934       ArgTypes.reserve(E->getNumArgs());
13935       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13936         Expr *Arg = E->getArg(i);
13937         QualType ArgType = Arg->getType();
13938         if (E->isLValue()) {
13939           ArgType = S.Context.getLValueReferenceType(ArgType);
13940         } else if (E->isXValue()) {
13941           ArgType = S.Context.getRValueReferenceType(ArgType);
13942         }
13943         ArgTypes.push_back(ArgType);
13944       }
13945       ParamTypes = ArgTypes;
13946     }
13947     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13948                                          Proto->getExtProtoInfo());
13949   } else {
13950     DestType = S.Context.getFunctionNoProtoType(DestType,
13951                                                 FnType->getExtInfo());
13952   }
13953 
13954   // Rebuild the appropriate pointer-to-function type.
13955   switch (Kind) {
13956   case FK_MemberFunction:
13957     // Nothing to do.
13958     break;
13959 
13960   case FK_FunctionPointer:
13961     DestType = S.Context.getPointerType(DestType);
13962     break;
13963 
13964   case FK_BlockPointer:
13965     DestType = S.Context.getBlockPointerType(DestType);
13966     break;
13967   }
13968 
13969   // Finally, we can recurse.
13970   ExprResult CalleeResult = Visit(CalleeExpr);
13971   if (!CalleeResult.isUsable()) return ExprError();
13972   E->setCallee(CalleeResult.get());
13973 
13974   // Bind a temporary if necessary.
13975   return S.MaybeBindToTemporary(E);
13976 }
13977 
VisitObjCMessageExpr(ObjCMessageExpr * E)13978 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13979   // Verify that this is a legal result type of a call.
13980   if (DestType->isArrayType() || DestType->isFunctionType()) {
13981     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13982       << DestType->isFunctionType() << DestType;
13983     return ExprError();
13984   }
13985 
13986   // Rewrite the method result type if available.
13987   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13988     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13989     Method->setReturnType(DestType);
13990   }
13991 
13992   // Change the type of the message.
13993   E->setType(DestType.getNonReferenceType());
13994   E->setValueKind(Expr::getValueKindForType(DestType));
13995 
13996   return S.MaybeBindToTemporary(E);
13997 }
13998 
VisitImplicitCastExpr(ImplicitCastExpr * E)13999 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14000   // The only case we should ever see here is a function-to-pointer decay.
14001   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14002     assert(E->getValueKind() == VK_RValue);
14003     assert(E->getObjectKind() == OK_Ordinary);
14004 
14005     E->setType(DestType);
14006 
14007     // Rebuild the sub-expression as the pointee (function) type.
14008     DestType = DestType->castAs<PointerType>()->getPointeeType();
14009 
14010     ExprResult Result = Visit(E->getSubExpr());
14011     if (!Result.isUsable()) return ExprError();
14012 
14013     E->setSubExpr(Result.get());
14014     return E;
14015   } else if (E->getCastKind() == CK_LValueToRValue) {
14016     assert(E->getValueKind() == VK_RValue);
14017     assert(E->getObjectKind() == OK_Ordinary);
14018 
14019     assert(isa<BlockPointerType>(E->getType()));
14020 
14021     E->setType(DestType);
14022 
14023     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14024     DestType = S.Context.getLValueReferenceType(DestType);
14025 
14026     ExprResult Result = Visit(E->getSubExpr());
14027     if (!Result.isUsable()) return ExprError();
14028 
14029     E->setSubExpr(Result.get());
14030     return E;
14031   } else {
14032     llvm_unreachable("Unhandled cast type!");
14033   }
14034 }
14035 
resolveDecl(Expr * E,ValueDecl * VD)14036 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14037   ExprValueKind ValueKind = VK_LValue;
14038   QualType Type = DestType;
14039 
14040   // We know how to make this work for certain kinds of decls:
14041 
14042   //  - functions
14043   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14044     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14045       DestType = Ptr->getPointeeType();
14046       ExprResult Result = resolveDecl(E, VD);
14047       if (Result.isInvalid()) return ExprError();
14048       return S.ImpCastExprToType(Result.get(), Type,
14049                                  CK_FunctionToPointerDecay, VK_RValue);
14050     }
14051 
14052     if (!Type->isFunctionType()) {
14053       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14054         << VD << E->getSourceRange();
14055       return ExprError();
14056     }
14057     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14058       // We must match the FunctionDecl's type to the hack introduced in
14059       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14060       // type. See the lengthy commentary in that routine.
14061       QualType FDT = FD->getType();
14062       const FunctionType *FnType = FDT->castAs<FunctionType>();
14063       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14064       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14065       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14066         SourceLocation Loc = FD->getLocation();
14067         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14068                                       FD->getDeclContext(),
14069                                       Loc, Loc, FD->getNameInfo().getName(),
14070                                       DestType, FD->getTypeSourceInfo(),
14071                                       SC_None, false/*isInlineSpecified*/,
14072                                       FD->hasPrototype(),
14073                                       false/*isConstexprSpecified*/);
14074 
14075         if (FD->getQualifier())
14076           NewFD->setQualifierInfo(FD->getQualifierLoc());
14077 
14078         SmallVector<ParmVarDecl*, 16> Params;
14079         for (const auto &AI : FT->param_types()) {
14080           ParmVarDecl *Param =
14081             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14082           Param->setScopeInfo(0, Params.size());
14083           Params.push_back(Param);
14084         }
14085         NewFD->setParams(Params);
14086         DRE->setDecl(NewFD);
14087         VD = DRE->getDecl();
14088       }
14089     }
14090 
14091     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14092       if (MD->isInstance()) {
14093         ValueKind = VK_RValue;
14094         Type = S.Context.BoundMemberTy;
14095       }
14096 
14097     // Function references aren't l-values in C.
14098     if (!S.getLangOpts().CPlusPlus)
14099       ValueKind = VK_RValue;
14100 
14101   //  - variables
14102   } else if (isa<VarDecl>(VD)) {
14103     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14104       Type = RefTy->getPointeeType();
14105     } else if (Type->isFunctionType()) {
14106       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14107         << VD << E->getSourceRange();
14108       return ExprError();
14109     }
14110 
14111   //  - nothing else
14112   } else {
14113     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14114       << VD << E->getSourceRange();
14115     return ExprError();
14116   }
14117 
14118   // Modifying the declaration like this is friendly to IR-gen but
14119   // also really dangerous.
14120   VD->setType(DestType);
14121   E->setType(Type);
14122   E->setValueKind(ValueKind);
14123   return E;
14124 }
14125 
14126 /// Check a cast of an unknown-any type.  We intentionally only
14127 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)14128 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14129                                      Expr *CastExpr, CastKind &CastKind,
14130                                      ExprValueKind &VK, CXXCastPath &Path) {
14131   // Rewrite the casted expression from scratch.
14132   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14133   if (!result.isUsable()) return ExprError();
14134 
14135   CastExpr = result.get();
14136   VK = CastExpr->getValueKind();
14137   CastKind = CK_NoOp;
14138 
14139   return CastExpr;
14140 }
14141 
forceUnknownAnyToType(Expr * E,QualType ToType)14142 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14143   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14144 }
14145 
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)14146 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14147                                     Expr *arg, QualType &paramType) {
14148   // If the syntactic form of the argument is not an explicit cast of
14149   // any sort, just do default argument promotion.
14150   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14151   if (!castArg) {
14152     ExprResult result = DefaultArgumentPromotion(arg);
14153     if (result.isInvalid()) return ExprError();
14154     paramType = result.get()->getType();
14155     return result;
14156   }
14157 
14158   // Otherwise, use the type that was written in the explicit cast.
14159   assert(!arg->hasPlaceholderType());
14160   paramType = castArg->getTypeAsWritten();
14161 
14162   // Copy-initialize a parameter of that type.
14163   InitializedEntity entity =
14164     InitializedEntity::InitializeParameter(Context, paramType,
14165                                            /*consumed*/ false);
14166   return PerformCopyInitialization(entity, callLoc, arg);
14167 }
14168 
diagnoseUnknownAnyExpr(Sema & S,Expr * E)14169 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14170   Expr *orig = E;
14171   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14172   while (true) {
14173     E = E->IgnoreParenImpCasts();
14174     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14175       E = call->getCallee();
14176       diagID = diag::err_uncasted_call_of_unknown_any;
14177     } else {
14178       break;
14179     }
14180   }
14181 
14182   SourceLocation loc;
14183   NamedDecl *d;
14184   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14185     loc = ref->getLocation();
14186     d = ref->getDecl();
14187   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14188     loc = mem->getMemberLoc();
14189     d = mem->getMemberDecl();
14190   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14191     diagID = diag::err_uncasted_call_of_unknown_any;
14192     loc = msg->getSelectorStartLoc();
14193     d = msg->getMethodDecl();
14194     if (!d) {
14195       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14196         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14197         << orig->getSourceRange();
14198       return ExprError();
14199     }
14200   } else {
14201     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14202       << E->getSourceRange();
14203     return ExprError();
14204   }
14205 
14206   S.Diag(loc, diagID) << d << orig->getSourceRange();
14207 
14208   // Never recoverable.
14209   return ExprError();
14210 }
14211 
14212 /// Check for operands with placeholder types and complain if found.
14213 /// Returns true if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)14214 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14215   if (!getLangOpts().CPlusPlus) {
14216     // C cannot handle TypoExpr nodes on either side of a binop because it
14217     // doesn't handle dependent types properly, so make sure any TypoExprs have
14218     // been dealt with before checking the operands.
14219     ExprResult Result = CorrectDelayedTyposInExpr(E);
14220     if (!Result.isUsable()) return ExprError();
14221     E = Result.get();
14222   }
14223 
14224   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14225   if (!placeholderType) return E;
14226 
14227   switch (placeholderType->getKind()) {
14228 
14229   // Overloaded expressions.
14230   case BuiltinType::Overload: {
14231     // Try to resolve a single function template specialization.
14232     // This is obligatory.
14233     ExprResult result = E;
14234     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14235       return result;
14236 
14237     // If that failed, try to recover with a call.
14238     } else {
14239       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14240                            /*complain*/ true);
14241       return result;
14242     }
14243   }
14244 
14245   // Bound member functions.
14246   case BuiltinType::BoundMember: {
14247     ExprResult result = E;
14248     const Expr *BME = E->IgnoreParens();
14249     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14250     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14251     if (isa<CXXPseudoDestructorExpr>(BME)) {
14252       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14253     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14254       if (ME->getMemberNameInfo().getName().getNameKind() ==
14255           DeclarationName::CXXDestructorName)
14256         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14257     }
14258     tryToRecoverWithCall(result, PD,
14259                          /*complain*/ true);
14260     return result;
14261   }
14262 
14263   // ARC unbridged casts.
14264   case BuiltinType::ARCUnbridgedCast: {
14265     Expr *realCast = stripARCUnbridgedCast(E);
14266     diagnoseARCUnbridgedCast(realCast);
14267     return realCast;
14268   }
14269 
14270   // Expressions of unknown type.
14271   case BuiltinType::UnknownAny:
14272     return diagnoseUnknownAnyExpr(*this, E);
14273 
14274   // Pseudo-objects.
14275   case BuiltinType::PseudoObject:
14276     return checkPseudoObjectRValue(E);
14277 
14278   case BuiltinType::BuiltinFn: {
14279     // Accept __noop without parens by implicitly converting it to a call expr.
14280     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14281     if (DRE) {
14282       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14283       if (FD->getBuiltinID() == Builtin::BI__noop) {
14284         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14285                               CK_BuiltinFnToFnPtr).get();
14286         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14287                                       VK_RValue, SourceLocation());
14288       }
14289     }
14290 
14291     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14292     return ExprError();
14293   }
14294 
14295   // Everything else should be impossible.
14296 #define BUILTIN_TYPE(Id, SingletonId) \
14297   case BuiltinType::Id:
14298 #define PLACEHOLDER_TYPE(Id, SingletonId)
14299 #include "clang/AST/BuiltinTypes.def"
14300     break;
14301   }
14302 
14303   llvm_unreachable("invalid placeholder type!");
14304 }
14305 
CheckCaseExpression(Expr * E)14306 bool Sema::CheckCaseExpression(Expr *E) {
14307   if (E->isTypeDependent())
14308     return true;
14309   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14310     return E->getType()->isIntegralOrEnumerationType();
14311   return false;
14312 }
14313 
14314 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14315 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)14316 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14317   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14318          "Unknown Objective-C Boolean value!");
14319   QualType BoolT = Context.ObjCBuiltinBoolTy;
14320   if (!Context.getBOOLDecl()) {
14321     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14322                         Sema::LookupOrdinaryName);
14323     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14324       NamedDecl *ND = Result.getFoundDecl();
14325       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14326         Context.setBOOLDecl(TD);
14327     }
14328   }
14329   if (Context.getBOOLDecl())
14330     BoolT = Context.getBOOLType();
14331   return new (Context)
14332       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14333 }
14334