• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1  //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2  //
3  //                     The LLVM Compiler Infrastructure
4  //
5  // This file is distributed under the University of Illinois Open Source
6  // License. See LICENSE.TXT for details.
7  //
8  //===----------------------------------------------------------------------===//
9  //
10  //  This file implements semantic analysis for expressions.
11  //
12  //===----------------------------------------------------------------------===//
13  
14  #include "clang/Sema/SemaInternal.h"
15  #include "TreeTransform.h"
16  #include "clang/AST/ASTConsumer.h"
17  #include "clang/AST/ASTContext.h"
18  #include "clang/AST/ASTLambda.h"
19  #include "clang/AST/ASTMutationListener.h"
20  #include "clang/AST/CXXInheritance.h"
21  #include "clang/AST/DeclObjC.h"
22  #include "clang/AST/DeclTemplate.h"
23  #include "clang/AST/EvaluatedExprVisitor.h"
24  #include "clang/AST/Expr.h"
25  #include "clang/AST/ExprCXX.h"
26  #include "clang/AST/ExprObjC.h"
27  #include "clang/AST/ExprOpenMP.h"
28  #include "clang/AST/RecursiveASTVisitor.h"
29  #include "clang/AST/TypeLoc.h"
30  #include "clang/Basic/PartialDiagnostic.h"
31  #include "clang/Basic/SourceManager.h"
32  #include "clang/Basic/TargetInfo.h"
33  #include "clang/Lex/LiteralSupport.h"
34  #include "clang/Lex/Preprocessor.h"
35  #include "clang/Sema/AnalysisBasedWarnings.h"
36  #include "clang/Sema/DeclSpec.h"
37  #include "clang/Sema/DelayedDiagnostic.h"
38  #include "clang/Sema/Designator.h"
39  #include "clang/Sema/Initialization.h"
40  #include "clang/Sema/Lookup.h"
41  #include "clang/Sema/ParsedTemplate.h"
42  #include "clang/Sema/Scope.h"
43  #include "clang/Sema/ScopeInfo.h"
44  #include "clang/Sema/SemaFixItUtils.h"
45  #include "clang/Sema/Template.h"
46  #include "llvm/Support/ConvertUTF.h"
47  using namespace clang;
48  using namespace sema;
49  
50  /// \brief Determine whether the use of this declaration is valid, without
51  /// emitting diagnostics.
CanUseDecl(NamedDecl * D)52  bool Sema::CanUseDecl(NamedDecl *D) {
53    // See if this is an auto-typed variable whose initializer we are parsing.
54    if (ParsingInitForAutoVars.count(D))
55      return false;
56  
57    // See if this is a deleted function.
58    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59      if (FD->isDeleted())
60        return false;
61  
62      // If the function has a deduced return type, and we can't deduce it,
63      // then we can't use it either.
64      if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65          DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66        return false;
67    }
68  
69    // See if this function is unavailable.
70    if (D->getAvailability() == AR_Unavailable &&
71        cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72      return false;
73  
74    return true;
75  }
76  
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)77  static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78    // Warn if this is used but marked unused.
79    if (D->hasAttr<UnusedAttr>()) {
80      const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
81      if (DC && !DC->hasAttr<UnusedAttr>())
82        S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
83    }
84  }
85  
HasRedeclarationWithoutAvailabilityInCategory(const Decl * D)86  static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
87    const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
88    if (!OMD)
89      return false;
90    const ObjCInterfaceDecl *OID = OMD->getClassInterface();
91    if (!OID)
92      return false;
93  
94    for (const ObjCCategoryDecl *Cat : OID->visible_categories())
95      if (ObjCMethodDecl *CatMeth =
96              Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
97        if (!CatMeth->hasAttr<AvailabilityAttr>())
98          return true;
99    return false;
100  }
101  
102  static AvailabilityResult
DiagnoseAvailabilityOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)103  DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
104                             const ObjCInterfaceDecl *UnknownObjCClass,
105                             bool ObjCPropertyAccess) {
106    // See if this declaration is unavailable or deprecated.
107    std::string Message;
108    AvailabilityResult Result = D->getAvailability(&Message);
109  
110    // For typedefs, if the typedef declaration appears available look
111    // to the underlying type to see if it is more restrictive.
112    while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113      if (Result == AR_Available) {
114        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115          D = TT->getDecl();
116          Result = D->getAvailability(&Message);
117          continue;
118        }
119      }
120      break;
121    }
122  
123    // Forward class declarations get their attributes from their definition.
124    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125      if (IDecl->getDefinition()) {
126        D = IDecl->getDefinition();
127        Result = D->getAvailability(&Message);
128      }
129    }
130  
131    if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132      if (Result == AR_Available) {
133        const DeclContext *DC = ECD->getDeclContext();
134        if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135          Result = TheEnumDecl->getAvailability(&Message);
136      }
137  
138    const ObjCPropertyDecl *ObjCPDecl = nullptr;
139    if (Result == AR_Deprecated || Result == AR_Unavailable ||
140        AR_NotYetIntroduced) {
141      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142        if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
143          AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
144          if (PDeclResult == Result)
145            ObjCPDecl = PD;
146        }
147      }
148    }
149  
150    switch (Result) {
151      case AR_Available:
152        break;
153  
154      case AR_Deprecated:
155        if (S.getCurContextAvailability() != AR_Deprecated)
156          S.EmitAvailabilityWarning(Sema::AD_Deprecation,
157                                    D, Message, Loc, UnknownObjCClass, ObjCPDecl,
158                                    ObjCPropertyAccess);
159        break;
160  
161      case AR_NotYetIntroduced: {
162        // Don't do this for enums, they can't be redeclared.
163        if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
164          break;
165  
166        bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
167        // Objective-C method declarations in categories are not modelled as
168        // redeclarations, so manually look for a redeclaration in a category
169        // if necessary.
170        if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
171          Warn = false;
172        // In general, D will point to the most recent redeclaration. However,
173        // for `@class A;` decls, this isn't true -- manually go through the
174        // redecl chain in that case.
175        if (Warn && isa<ObjCInterfaceDecl>(D))
176          for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
177               Redecl = Redecl->getPreviousDecl())
178            if (!Redecl->hasAttr<AvailabilityAttr>() ||
179                Redecl->getAttr<AvailabilityAttr>()->isInherited())
180              Warn = false;
181  
182        if (Warn)
183          S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
184                                    UnknownObjCClass, ObjCPDecl,
185                                    ObjCPropertyAccess);
186        break;
187      }
188  
189      case AR_Unavailable:
190        if (S.getCurContextAvailability() != AR_Unavailable)
191          S.EmitAvailabilityWarning(Sema::AD_Unavailable,
192                                    D, Message, Loc, UnknownObjCClass, ObjCPDecl,
193                                    ObjCPropertyAccess);
194        break;
195  
196      }
197      return Result;
198  }
199  
200  /// \brief Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)201  void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
202    assert(Decl->isDeleted());
203  
204    CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
205  
206    if (Method && Method->isDeleted() && Method->isDefaulted()) {
207      // If the method was explicitly defaulted, point at that declaration.
208      if (!Method->isImplicit())
209        Diag(Decl->getLocation(), diag::note_implicitly_deleted);
210  
211      // Try to diagnose why this special member function was implicitly
212      // deleted. This might fail, if that reason no longer applies.
213      CXXSpecialMember CSM = getSpecialMember(Method);
214      if (CSM != CXXInvalid)
215        ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
216  
217      return;
218    }
219  
220    if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
221      if (CXXConstructorDecl *BaseCD =
222              const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
223        Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
224        if (BaseCD->isDeleted()) {
225          NoteDeletedFunction(BaseCD);
226        } else {
227          // FIXME: An explanation of why exactly it can't be inherited
228          // would be nice.
229          Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
230        }
231        return;
232      }
233    }
234  
235    Diag(Decl->getLocation(), diag::note_availability_specified_here)
236      << Decl << true;
237  }
238  
239  /// \brief Determine whether a FunctionDecl was ever declared with an
240  /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)241  static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
242    for (auto I : D->redecls()) {
243      if (I->getStorageClass() != SC_None)
244        return true;
245    }
246    return false;
247  }
248  
249  /// \brief Check whether we're in an extern inline function and referring to a
250  /// variable or function with internal linkage (C11 6.7.4p3).
251  ///
252  /// This is only a warning because we used to silently accept this code, but
253  /// in many cases it will not behave correctly. This is not enabled in C++ mode
254  /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
255  /// and so while there may still be user mistakes, most of the time we can't
256  /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)257  static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
258                                                        const NamedDecl *D,
259                                                        SourceLocation Loc) {
260    // This is disabled under C++; there are too many ways for this to fire in
261    // contexts where the warning is a false positive, or where it is technically
262    // correct but benign.
263    if (S.getLangOpts().CPlusPlus)
264      return;
265  
266    // Check if this is an inlined function or method.
267    FunctionDecl *Current = S.getCurFunctionDecl();
268    if (!Current)
269      return;
270    if (!Current->isInlined())
271      return;
272    if (!Current->isExternallyVisible())
273      return;
274  
275    // Check if the decl has internal linkage.
276    if (D->getFormalLinkage() != InternalLinkage)
277      return;
278  
279    // Downgrade from ExtWarn to Extension if
280    //  (1) the supposedly external inline function is in the main file,
281    //      and probably won't be included anywhere else.
282    //  (2) the thing we're referencing is a pure function.
283    //  (3) the thing we're referencing is another inline function.
284    // This last can give us false negatives, but it's better than warning on
285    // wrappers for simple C library functions.
286    const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
287    bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
288    if (!DowngradeWarning && UsedFn)
289      DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
290  
291    S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
292                                 : diag::ext_internal_in_extern_inline)
293      << /*IsVar=*/!UsedFn << D;
294  
295    S.MaybeSuggestAddingStaticToDecl(Current);
296  
297    S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
298        << D;
299  }
300  
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)301  void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
302    const FunctionDecl *First = Cur->getFirstDecl();
303  
304    // Suggest "static" on the function, if possible.
305    if (!hasAnyExplicitStorageClass(First)) {
306      SourceLocation DeclBegin = First->getSourceRange().getBegin();
307      Diag(DeclBegin, diag::note_convert_inline_to_static)
308        << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
309    }
310  }
311  
312  /// \brief Determine whether the use of this declaration is valid, and
313  /// emit any corresponding diagnostics.
314  ///
315  /// This routine diagnoses various problems with referencing
316  /// declarations that can occur when using a declaration. For example,
317  /// it might warn if a deprecated or unavailable declaration is being
318  /// used, or produce an error (and return true) if a C++0x deleted
319  /// function is being used.
320  ///
321  /// \returns true if there was an error (this declaration cannot be
322  /// referenced), false otherwise.
323  ///
DiagnoseUseOfDecl(NamedDecl * D,SourceLocation Loc,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess)324  bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
325                               const ObjCInterfaceDecl *UnknownObjCClass,
326                               bool ObjCPropertyAccess) {
327    if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
328      // If there were any diagnostics suppressed by template argument deduction,
329      // emit them now.
330      auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
331      if (Pos != SuppressedDiagnostics.end()) {
332        for (const PartialDiagnosticAt &Suppressed : Pos->second)
333          Diag(Suppressed.first, Suppressed.second);
334  
335        // Clear out the list of suppressed diagnostics, so that we don't emit
336        // them again for this specialization. However, we don't obsolete this
337        // entry from the table, because we want to avoid ever emitting these
338        // diagnostics again.
339        Pos->second.clear();
340      }
341  
342      // C++ [basic.start.main]p3:
343      //   The function 'main' shall not be used within a program.
344      if (cast<FunctionDecl>(D)->isMain())
345        Diag(Loc, diag::ext_main_used);
346    }
347  
348    // See if this is an auto-typed variable whose initializer we are parsing.
349    if (ParsingInitForAutoVars.count(D)) {
350      const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
351  
352      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
353        << D->getDeclName() << (unsigned)AT->getKeyword();
354      return true;
355    }
356  
357    // See if this is a deleted function.
358    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
359      if (FD->isDeleted()) {
360        Diag(Loc, diag::err_deleted_function_use);
361        NoteDeletedFunction(FD);
362        return true;
363      }
364  
365      // If the function has a deduced return type, and we can't deduce it,
366      // then we can't use it either.
367      if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
368          DeduceReturnType(FD, Loc))
369        return true;
370    }
371    DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
372                               ObjCPropertyAccess);
373  
374    DiagnoseUnusedOfDecl(*this, D, Loc);
375  
376    diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
377  
378    return false;
379  }
380  
381  /// \brief Retrieve the message suffix that should be added to a
382  /// diagnostic complaining about the given function being deleted or
383  /// unavailable.
getDeletedOrUnavailableSuffix(const FunctionDecl * FD)384  std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
385    std::string Message;
386    if (FD->getAvailability(&Message))
387      return ": " + Message;
388  
389    return std::string();
390  }
391  
392  /// DiagnoseSentinelCalls - This routine checks whether a call or
393  /// message-send is to a declaration with the sentinel attribute, and
394  /// if so, it checks that the requirements of the sentinel are
395  /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)396  void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
397                                   ArrayRef<Expr *> Args) {
398    const SentinelAttr *attr = D->getAttr<SentinelAttr>();
399    if (!attr)
400      return;
401  
402    // The number of formal parameters of the declaration.
403    unsigned numFormalParams;
404  
405    // The kind of declaration.  This is also an index into a %select in
406    // the diagnostic.
407    enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
408  
409    if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
410      numFormalParams = MD->param_size();
411      calleeType = CT_Method;
412    } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
413      numFormalParams = FD->param_size();
414      calleeType = CT_Function;
415    } else if (isa<VarDecl>(D)) {
416      QualType type = cast<ValueDecl>(D)->getType();
417      const FunctionType *fn = nullptr;
418      if (const PointerType *ptr = type->getAs<PointerType>()) {
419        fn = ptr->getPointeeType()->getAs<FunctionType>();
420        if (!fn) return;
421        calleeType = CT_Function;
422      } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
423        fn = ptr->getPointeeType()->castAs<FunctionType>();
424        calleeType = CT_Block;
425      } else {
426        return;
427      }
428  
429      if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
430        numFormalParams = proto->getNumParams();
431      } else {
432        numFormalParams = 0;
433      }
434    } else {
435      return;
436    }
437  
438    // "nullPos" is the number of formal parameters at the end which
439    // effectively count as part of the variadic arguments.  This is
440    // useful if you would prefer to not have *any* formal parameters,
441    // but the language forces you to have at least one.
442    unsigned nullPos = attr->getNullPos();
443    assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
444    numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
445  
446    // The number of arguments which should follow the sentinel.
447    unsigned numArgsAfterSentinel = attr->getSentinel();
448  
449    // If there aren't enough arguments for all the formal parameters,
450    // the sentinel, and the args after the sentinel, complain.
451    if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
452      Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
453      Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
454      return;
455    }
456  
457    // Otherwise, find the sentinel expression.
458    Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
459    if (!sentinelExpr) return;
460    if (sentinelExpr->isValueDependent()) return;
461    if (Context.isSentinelNullExpr(sentinelExpr)) return;
462  
463    // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
464    // or 'NULL' if those are actually defined in the context.  Only use
465    // 'nil' for ObjC methods, where it's much more likely that the
466    // variadic arguments form a list of object pointers.
467    SourceLocation MissingNilLoc
468      = getLocForEndOfToken(sentinelExpr->getLocEnd());
469    std::string NullValue;
470    if (calleeType == CT_Method && PP.isMacroDefined("nil"))
471      NullValue = "nil";
472    else if (getLangOpts().CPlusPlus11)
473      NullValue = "nullptr";
474    else if (PP.isMacroDefined("NULL"))
475      NullValue = "NULL";
476    else
477      NullValue = "(void*) 0";
478  
479    if (MissingNilLoc.isInvalid())
480      Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
481    else
482      Diag(MissingNilLoc, diag::warn_missing_sentinel)
483        << int(calleeType)
484        << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
485    Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
486  }
487  
getExprRange(Expr * E) const488  SourceRange Sema::getExprRange(Expr *E) const {
489    return E ? E->getSourceRange() : SourceRange();
490  }
491  
492  //===----------------------------------------------------------------------===//
493  //  Standard Promotions and Conversions
494  //===----------------------------------------------------------------------===//
495  
496  /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)497  ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
498    // Handle any placeholder expressions which made it here.
499    if (E->getType()->isPlaceholderType()) {
500      ExprResult result = CheckPlaceholderExpr(E);
501      if (result.isInvalid()) return ExprError();
502      E = result.get();
503    }
504  
505    QualType Ty = E->getType();
506    assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
507  
508    if (Ty->isFunctionType()) {
509      // If we are here, we are not calling a function but taking
510      // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
511      if (getLangOpts().OpenCL) {
512        if (Diagnose)
513          Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
514        return ExprError();
515      }
516  
517      if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
518        if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
519          if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
520            return ExprError();
521  
522      E = ImpCastExprToType(E, Context.getPointerType(Ty),
523                            CK_FunctionToPointerDecay).get();
524    } else if (Ty->isArrayType()) {
525      // In C90 mode, arrays only promote to pointers if the array expression is
526      // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
527      // type 'array of type' is converted to an expression that has type 'pointer
528      // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
529      // that has type 'array of type' ...".  The relevant change is "an lvalue"
530      // (C90) to "an expression" (C99).
531      //
532      // C++ 4.2p1:
533      // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
534      // T" can be converted to an rvalue of type "pointer to T".
535      //
536      if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
537        E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
538                              CK_ArrayToPointerDecay).get();
539    }
540    return E;
541  }
542  
CheckForNullPointerDereference(Sema & S,Expr * E)543  static void CheckForNullPointerDereference(Sema &S, Expr *E) {
544    // Check to see if we are dereferencing a null pointer.  If so,
545    // and if not volatile-qualified, this is undefined behavior that the
546    // optimizer will delete, so warn about it.  People sometimes try to use this
547    // to get a deterministic trap and are surprised by clang's behavior.  This
548    // only handles the pattern "*null", which is a very syntactic check.
549    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
550      if (UO->getOpcode() == UO_Deref &&
551          UO->getSubExpr()->IgnoreParenCasts()->
552            isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
553          !UO->getType().isVolatileQualified()) {
554      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
555                            S.PDiag(diag::warn_indirection_through_null)
556                              << UO->getSubExpr()->getSourceRange());
557      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558                          S.PDiag(diag::note_indirection_through_null));
559    }
560  }
561  
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)562  static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
563                                      SourceLocation AssignLoc,
564                                      const Expr* RHS) {
565    const ObjCIvarDecl *IV = OIRE->getDecl();
566    if (!IV)
567      return;
568  
569    DeclarationName MemberName = IV->getDeclName();
570    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
571    if (!Member || !Member->isStr("isa"))
572      return;
573  
574    const Expr *Base = OIRE->getBase();
575    QualType BaseType = Base->getType();
576    if (OIRE->isArrow())
577      BaseType = BaseType->getPointeeType();
578    if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
579      if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
580        ObjCInterfaceDecl *ClassDeclared = nullptr;
581        ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
582        if (!ClassDeclared->getSuperClass()
583            && (*ClassDeclared->ivar_begin()) == IV) {
584          if (RHS) {
585            NamedDecl *ObjectSetClass =
586              S.LookupSingleName(S.TUScope,
587                                 &S.Context.Idents.get("object_setClass"),
588                                 SourceLocation(), S.LookupOrdinaryName);
589            if (ObjectSetClass) {
590              SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
591              S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
592              FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
593              FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
594                                                       AssignLoc), ",") <<
595              FixItHint::CreateInsertion(RHSLocEnd, ")");
596            }
597            else
598              S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
599          } else {
600            NamedDecl *ObjectGetClass =
601              S.LookupSingleName(S.TUScope,
602                                 &S.Context.Idents.get("object_getClass"),
603                                 SourceLocation(), S.LookupOrdinaryName);
604            if (ObjectGetClass)
605              S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
606              FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
607              FixItHint::CreateReplacement(
608                                           SourceRange(OIRE->getOpLoc(),
609                                                       OIRE->getLocEnd()), ")");
610            else
611              S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
612          }
613          S.Diag(IV->getLocation(), diag::note_ivar_decl);
614        }
615      }
616  }
617  
DefaultLvalueConversion(Expr * E)618  ExprResult Sema::DefaultLvalueConversion(Expr *E) {
619    // Handle any placeholder expressions which made it here.
620    if (E->getType()->isPlaceholderType()) {
621      ExprResult result = CheckPlaceholderExpr(E);
622      if (result.isInvalid()) return ExprError();
623      E = result.get();
624    }
625  
626    // C++ [conv.lval]p1:
627    //   A glvalue of a non-function, non-array type T can be
628    //   converted to a prvalue.
629    if (!E->isGLValue()) return E;
630  
631    QualType T = E->getType();
632    assert(!T.isNull() && "r-value conversion on typeless expression?");
633  
634    // We don't want to throw lvalue-to-rvalue casts on top of
635    // expressions of certain types in C++.
636    if (getLangOpts().CPlusPlus &&
637        (E->getType() == Context.OverloadTy ||
638         T->isDependentType() ||
639         T->isRecordType()))
640      return E;
641  
642    // The C standard is actually really unclear on this point, and
643    // DR106 tells us what the result should be but not why.  It's
644    // generally best to say that void types just doesn't undergo
645    // lvalue-to-rvalue at all.  Note that expressions of unqualified
646    // 'void' type are never l-values, but qualified void can be.
647    if (T->isVoidType())
648      return E;
649  
650    // OpenCL usually rejects direct accesses to values of 'half' type.
651    if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
652        T->isHalfType()) {
653      Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
654        << 0 << T;
655      return ExprError();
656    }
657  
658    CheckForNullPointerDereference(*this, E);
659    if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
660      NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
661                                       &Context.Idents.get("object_getClass"),
662                                       SourceLocation(), LookupOrdinaryName);
663      if (ObjectGetClass)
664        Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
665          FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
666          FixItHint::CreateReplacement(
667                      SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
668      else
669        Diag(E->getExprLoc(), diag::warn_objc_isa_use);
670    }
671    else if (const ObjCIvarRefExpr *OIRE =
672              dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
673      DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
674  
675    // C++ [conv.lval]p1:
676    //   [...] If T is a non-class type, the type of the prvalue is the
677    //   cv-unqualified version of T. Otherwise, the type of the
678    //   rvalue is T.
679    //
680    // C99 6.3.2.1p2:
681    //   If the lvalue has qualified type, the value has the unqualified
682    //   version of the type of the lvalue; otherwise, the value has the
683    //   type of the lvalue.
684    if (T.hasQualifiers())
685      T = T.getUnqualifiedType();
686  
687    // Under the MS ABI, lock down the inheritance model now.
688    if (T->isMemberPointerType() &&
689        Context.getTargetInfo().getCXXABI().isMicrosoft())
690      (void)isCompleteType(E->getExprLoc(), T);
691  
692    UpdateMarkingForLValueToRValue(E);
693  
694    // Loading a __weak object implicitly retains the value, so we need a cleanup to
695    // balance that.
696    if (getLangOpts().ObjCAutoRefCount &&
697        E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
698      ExprNeedsCleanups = true;
699  
700    ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
701                                              nullptr, VK_RValue);
702  
703    // C11 6.3.2.1p2:
704    //   ... if the lvalue has atomic type, the value has the non-atomic version
705    //   of the type of the lvalue ...
706    if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
707      T = Atomic->getValueType().getUnqualifiedType();
708      Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
709                                     nullptr, VK_RValue);
710    }
711  
712    return Res;
713  }
714  
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)715  ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
716    ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
717    if (Res.isInvalid())
718      return ExprError();
719    Res = DefaultLvalueConversion(Res.get());
720    if (Res.isInvalid())
721      return ExprError();
722    return Res;
723  }
724  
725  /// CallExprUnaryConversions - a special case of an unary conversion
726  /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)727  ExprResult Sema::CallExprUnaryConversions(Expr *E) {
728    QualType Ty = E->getType();
729    ExprResult Res = E;
730    // Only do implicit cast for a function type, but not for a pointer
731    // to function type.
732    if (Ty->isFunctionType()) {
733      Res = ImpCastExprToType(E, Context.getPointerType(Ty),
734                              CK_FunctionToPointerDecay).get();
735      if (Res.isInvalid())
736        return ExprError();
737    }
738    Res = DefaultLvalueConversion(Res.get());
739    if (Res.isInvalid())
740      return ExprError();
741    return Res.get();
742  }
743  
744  /// UsualUnaryConversions - Performs various conversions that are common to most
745  /// operators (C99 6.3). The conversions of array and function types are
746  /// sometimes suppressed. For example, the array->pointer conversion doesn't
747  /// apply if the array is an argument to the sizeof or address (&) operators.
748  /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)749  ExprResult Sema::UsualUnaryConversions(Expr *E) {
750    // First, convert to an r-value.
751    ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
752    if (Res.isInvalid())
753      return ExprError();
754    E = Res.get();
755  
756    QualType Ty = E->getType();
757    assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
758  
759    // Half FP have to be promoted to float unless it is natively supported
760    if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
761      return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
762  
763    // Try to perform integral promotions if the object has a theoretically
764    // promotable type.
765    if (Ty->isIntegralOrUnscopedEnumerationType()) {
766      // C99 6.3.1.1p2:
767      //
768      //   The following may be used in an expression wherever an int or
769      //   unsigned int may be used:
770      //     - an object or expression with an integer type whose integer
771      //       conversion rank is less than or equal to the rank of int
772      //       and unsigned int.
773      //     - A bit-field of type _Bool, int, signed int, or unsigned int.
774      //
775      //   If an int can represent all values of the original type, the
776      //   value is converted to an int; otherwise, it is converted to an
777      //   unsigned int. These are called the integer promotions. All
778      //   other types are unchanged by the integer promotions.
779  
780      QualType PTy = Context.isPromotableBitField(E);
781      if (!PTy.isNull()) {
782        E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
783        return E;
784      }
785      if (Ty->isPromotableIntegerType()) {
786        QualType PT = Context.getPromotedIntegerType(Ty);
787        E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
788        return E;
789      }
790    }
791    return E;
792  }
793  
794  /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
795  /// do not have a prototype. Arguments that have type float or __fp16
796  /// are promoted to double. All other argument types are converted by
797  /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)798  ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
799    QualType Ty = E->getType();
800    assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
801  
802    ExprResult Res = UsualUnaryConversions(E);
803    if (Res.isInvalid())
804      return ExprError();
805    E = Res.get();
806  
807    // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
808    // double.
809    const BuiltinType *BTy = Ty->getAs<BuiltinType>();
810    if (BTy && (BTy->getKind() == BuiltinType::Half ||
811                BTy->getKind() == BuiltinType::Float))
812      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
813  
814    // C++ performs lvalue-to-rvalue conversion as a default argument
815    // promotion, even on class types, but note:
816    //   C++11 [conv.lval]p2:
817    //     When an lvalue-to-rvalue conversion occurs in an unevaluated
818    //     operand or a subexpression thereof the value contained in the
819    //     referenced object is not accessed. Otherwise, if the glvalue
820    //     has a class type, the conversion copy-initializes a temporary
821    //     of type T from the glvalue and the result of the conversion
822    //     is a prvalue for the temporary.
823    // FIXME: add some way to gate this entire thing for correctness in
824    // potentially potentially evaluated contexts.
825    if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
826      ExprResult Temp = PerformCopyInitialization(
827                         InitializedEntity::InitializeTemporary(E->getType()),
828                                                  E->getExprLoc(), E);
829      if (Temp.isInvalid())
830        return ExprError();
831      E = Temp.get();
832    }
833  
834    return E;
835  }
836  
837  /// Determine the degree of POD-ness for an expression.
838  /// Incomplete types are considered POD, since this check can be performed
839  /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)840  Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
841    if (Ty->isIncompleteType()) {
842      // C++11 [expr.call]p7:
843      //   After these conversions, if the argument does not have arithmetic,
844      //   enumeration, pointer, pointer to member, or class type, the program
845      //   is ill-formed.
846      //
847      // Since we've already performed array-to-pointer and function-to-pointer
848      // decay, the only such type in C++ is cv void. This also handles
849      // initializer lists as variadic arguments.
850      if (Ty->isVoidType())
851        return VAK_Invalid;
852  
853      if (Ty->isObjCObjectType())
854        return VAK_Invalid;
855      return VAK_Valid;
856    }
857  
858    if (Ty.isCXX98PODType(Context))
859      return VAK_Valid;
860  
861    // C++11 [expr.call]p7:
862    //   Passing a potentially-evaluated argument of class type (Clause 9)
863    //   having a non-trivial copy constructor, a non-trivial move constructor,
864    //   or a non-trivial destructor, with no corresponding parameter,
865    //   is conditionally-supported with implementation-defined semantics.
866    if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
867      if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
868        if (!Record->hasNonTrivialCopyConstructor() &&
869            !Record->hasNonTrivialMoveConstructor() &&
870            !Record->hasNonTrivialDestructor())
871          return VAK_ValidInCXX11;
872  
873    if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
874      return VAK_Valid;
875  
876    if (Ty->isObjCObjectType())
877      return VAK_Invalid;
878  
879    if (getLangOpts().MSVCCompat)
880      return VAK_MSVCUndefined;
881  
882    // FIXME: In C++11, these cases are conditionally-supported, meaning we're
883    // permitted to reject them. We should consider doing so.
884    return VAK_Undefined;
885  }
886  
checkVariadicArgument(const Expr * E,VariadicCallType CT)887  void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
888    // Don't allow one to pass an Objective-C interface to a vararg.
889    const QualType &Ty = E->getType();
890    VarArgKind VAK = isValidVarArgType(Ty);
891  
892    // Complain about passing non-POD types through varargs.
893    switch (VAK) {
894    case VAK_ValidInCXX11:
895      DiagRuntimeBehavior(
896          E->getLocStart(), nullptr,
897          PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
898            << Ty << CT);
899      // Fall through.
900    case VAK_Valid:
901      if (Ty->isRecordType()) {
902        // This is unlikely to be what the user intended. If the class has a
903        // 'c_str' member function, the user probably meant to call that.
904        DiagRuntimeBehavior(E->getLocStart(), nullptr,
905                            PDiag(diag::warn_pass_class_arg_to_vararg)
906                              << Ty << CT << hasCStrMethod(E) << ".c_str()");
907      }
908      break;
909  
910    case VAK_Undefined:
911    case VAK_MSVCUndefined:
912      DiagRuntimeBehavior(
913          E->getLocStart(), nullptr,
914          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
915            << getLangOpts().CPlusPlus11 << Ty << CT);
916      break;
917  
918    case VAK_Invalid:
919      if (Ty->isObjCObjectType())
920        DiagRuntimeBehavior(
921            E->getLocStart(), nullptr,
922            PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
923              << Ty << CT);
924      else
925        Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
926          << isa<InitListExpr>(E) << Ty << CT;
927      break;
928    }
929  }
930  
931  /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
932  /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)933  ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
934                                                    FunctionDecl *FDecl) {
935    if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
936      // Strip the unbridged-cast placeholder expression off, if applicable.
937      if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
938          (CT == VariadicMethod ||
939           (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
940        E = stripARCUnbridgedCast(E);
941  
942      // Otherwise, do normal placeholder checking.
943      } else {
944        ExprResult ExprRes = CheckPlaceholderExpr(E);
945        if (ExprRes.isInvalid())
946          return ExprError();
947        E = ExprRes.get();
948      }
949    }
950  
951    ExprResult ExprRes = DefaultArgumentPromotion(E);
952    if (ExprRes.isInvalid())
953      return ExprError();
954    E = ExprRes.get();
955  
956    // Diagnostics regarding non-POD argument types are
957    // emitted along with format string checking in Sema::CheckFunctionCall().
958    if (isValidVarArgType(E->getType()) == VAK_Undefined) {
959      // Turn this into a trap.
960      CXXScopeSpec SS;
961      SourceLocation TemplateKWLoc;
962      UnqualifiedId Name;
963      Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
964                         E->getLocStart());
965      ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
966                                            Name, true, false);
967      if (TrapFn.isInvalid())
968        return ExprError();
969  
970      ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
971                                      E->getLocStart(), None,
972                                      E->getLocEnd());
973      if (Call.isInvalid())
974        return ExprError();
975  
976      ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
977                                    Call.get(), E);
978      if (Comma.isInvalid())
979        return ExprError();
980      return Comma.get();
981    }
982  
983    if (!getLangOpts().CPlusPlus &&
984        RequireCompleteType(E->getExprLoc(), E->getType(),
985                            diag::err_call_incomplete_argument))
986      return ExprError();
987  
988    return E;
989  }
990  
991  /// \brief Converts an integer to complex float type.  Helper function of
992  /// UsualArithmeticConversions()
993  ///
994  /// \return false if the integer expression is an integer type and is
995  /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)996  static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
997                                                    ExprResult &ComplexExpr,
998                                                    QualType IntTy,
999                                                    QualType ComplexTy,
1000                                                    bool SkipCast) {
1001    if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1002    if (SkipCast) return false;
1003    if (IntTy->isIntegerType()) {
1004      QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1005      IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1006      IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1007                                    CK_FloatingRealToComplex);
1008    } else {
1009      assert(IntTy->isComplexIntegerType());
1010      IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1011                                    CK_IntegralComplexToFloatingComplex);
1012    }
1013    return false;
1014  }
1015  
1016  /// \brief Handle arithmetic conversion with complex types.  Helper function of
1017  /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1018  static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1019                                               ExprResult &RHS, QualType LHSType,
1020                                               QualType RHSType,
1021                                               bool IsCompAssign) {
1022    // if we have an integer operand, the result is the complex type.
1023    if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1024                                               /*skipCast*/false))
1025      return LHSType;
1026    if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1027                                               /*skipCast*/IsCompAssign))
1028      return RHSType;
1029  
1030    // This handles complex/complex, complex/float, or float/complex.
1031    // When both operands are complex, the shorter operand is converted to the
1032    // type of the longer, and that is the type of the result. This corresponds
1033    // to what is done when combining two real floating-point operands.
1034    // The fun begins when size promotion occur across type domains.
1035    // From H&S 6.3.4: When one operand is complex and the other is a real
1036    // floating-point type, the less precise type is converted, within it's
1037    // real or complex domain, to the precision of the other type. For example,
1038    // when combining a "long double" with a "double _Complex", the
1039    // "double _Complex" is promoted to "long double _Complex".
1040  
1041    // Compute the rank of the two types, regardless of whether they are complex.
1042    int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1043  
1044    auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1045    auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1046    QualType LHSElementType =
1047        LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1048    QualType RHSElementType =
1049        RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1050  
1051    QualType ResultType = S.Context.getComplexType(LHSElementType);
1052    if (Order < 0) {
1053      // Promote the precision of the LHS if not an assignment.
1054      ResultType = S.Context.getComplexType(RHSElementType);
1055      if (!IsCompAssign) {
1056        if (LHSComplexType)
1057          LHS =
1058              S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1059        else
1060          LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1061      }
1062    } else if (Order > 0) {
1063      // Promote the precision of the RHS.
1064      if (RHSComplexType)
1065        RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1066      else
1067        RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1068    }
1069    return ResultType;
1070  }
1071  
1072  /// \brief Hande arithmetic conversion from integer to float.  Helper function
1073  /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1074  static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1075                                             ExprResult &IntExpr,
1076                                             QualType FloatTy, QualType IntTy,
1077                                             bool ConvertFloat, bool ConvertInt) {
1078    if (IntTy->isIntegerType()) {
1079      if (ConvertInt)
1080        // Convert intExpr to the lhs floating point type.
1081        IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1082                                      CK_IntegralToFloating);
1083      return FloatTy;
1084    }
1085  
1086    // Convert both sides to the appropriate complex float.
1087    assert(IntTy->isComplexIntegerType());
1088    QualType result = S.Context.getComplexType(FloatTy);
1089  
1090    // _Complex int -> _Complex float
1091    if (ConvertInt)
1092      IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1093                                    CK_IntegralComplexToFloatingComplex);
1094  
1095    // float -> _Complex float
1096    if (ConvertFloat)
1097      FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1098                                      CK_FloatingRealToComplex);
1099  
1100    return result;
1101  }
1102  
1103  /// \brief Handle arithmethic conversion with floating point types.  Helper
1104  /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1105  static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1106                                        ExprResult &RHS, QualType LHSType,
1107                                        QualType RHSType, bool IsCompAssign) {
1108    bool LHSFloat = LHSType->isRealFloatingType();
1109    bool RHSFloat = RHSType->isRealFloatingType();
1110  
1111    // If we have two real floating types, convert the smaller operand
1112    // to the bigger result.
1113    if (LHSFloat && RHSFloat) {
1114      int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1115      if (order > 0) {
1116        RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1117        return LHSType;
1118      }
1119  
1120      assert(order < 0 && "illegal float comparison");
1121      if (!IsCompAssign)
1122        LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1123      return RHSType;
1124    }
1125  
1126    if (LHSFloat) {
1127      // Half FP has to be promoted to float unless it is natively supported
1128      if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1129        LHSType = S.Context.FloatTy;
1130  
1131      return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1132                                        /*convertFloat=*/!IsCompAssign,
1133                                        /*convertInt=*/ true);
1134    }
1135    assert(RHSFloat);
1136    return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1137                                      /*convertInt=*/ true,
1138                                      /*convertFloat=*/!IsCompAssign);
1139  }
1140  
1141  typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1142  
1143  namespace {
1144  /// These helper callbacks are placed in an anonymous namespace to
1145  /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1146  ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1147    return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1148  }
1149  
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1150  ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1151    return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1152                               CK_IntegralComplexCast);
1153  }
1154  }
1155  
1156  /// \brief Handle integer arithmetic conversions.  Helper function of
1157  /// UsualArithmeticConversions()
1158  template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1159  static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1160                                          ExprResult &RHS, QualType LHSType,
1161                                          QualType RHSType, bool IsCompAssign) {
1162    // The rules for this case are in C99 6.3.1.8
1163    int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1164    bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1165    bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1166    if (LHSSigned == RHSSigned) {
1167      // Same signedness; use the higher-ranked type
1168      if (order >= 0) {
1169        RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1170        return LHSType;
1171      } else if (!IsCompAssign)
1172        LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1173      return RHSType;
1174    } else if (order != (LHSSigned ? 1 : -1)) {
1175      // The unsigned type has greater than or equal rank to the
1176      // signed type, so use the unsigned type
1177      if (RHSSigned) {
1178        RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1179        return LHSType;
1180      } else if (!IsCompAssign)
1181        LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182      return RHSType;
1183    } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1184      // The two types are different widths; if we are here, that
1185      // means the signed type is larger than the unsigned type, so
1186      // use the signed type.
1187      if (LHSSigned) {
1188        RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1189        return LHSType;
1190      } else if (!IsCompAssign)
1191        LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1192      return RHSType;
1193    } else {
1194      // The signed type is higher-ranked than the unsigned type,
1195      // but isn't actually any bigger (like unsigned int and long
1196      // on most 32-bit systems).  Use the unsigned type corresponding
1197      // to the signed type.
1198      QualType result =
1199        S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1200      RHS = (*doRHSCast)(S, RHS.get(), result);
1201      if (!IsCompAssign)
1202        LHS = (*doLHSCast)(S, LHS.get(), result);
1203      return result;
1204    }
1205  }
1206  
1207  /// \brief Handle conversions with GCC complex int extension.  Helper function
1208  /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1209  static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1210                                             ExprResult &RHS, QualType LHSType,
1211                                             QualType RHSType,
1212                                             bool IsCompAssign) {
1213    const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1214    const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1215  
1216    if (LHSComplexInt && RHSComplexInt) {
1217      QualType LHSEltType = LHSComplexInt->getElementType();
1218      QualType RHSEltType = RHSComplexInt->getElementType();
1219      QualType ScalarType =
1220        handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1221          (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1222  
1223      return S.Context.getComplexType(ScalarType);
1224    }
1225  
1226    if (LHSComplexInt) {
1227      QualType LHSEltType = LHSComplexInt->getElementType();
1228      QualType ScalarType =
1229        handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1230          (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1231      QualType ComplexType = S.Context.getComplexType(ScalarType);
1232      RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1233                                CK_IntegralRealToComplex);
1234  
1235      return ComplexType;
1236    }
1237  
1238    assert(RHSComplexInt);
1239  
1240    QualType RHSEltType = RHSComplexInt->getElementType();
1241    QualType ScalarType =
1242      handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1243        (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1244    QualType ComplexType = S.Context.getComplexType(ScalarType);
1245  
1246    if (!IsCompAssign)
1247      LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1248                                CK_IntegralRealToComplex);
1249    return ComplexType;
1250  }
1251  
1252  /// UsualArithmeticConversions - Performs various conversions that are common to
1253  /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1254  /// routine returns the first non-arithmetic type found. The client is
1255  /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,bool IsCompAssign)1256  QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1257                                            bool IsCompAssign) {
1258    if (!IsCompAssign) {
1259      LHS = UsualUnaryConversions(LHS.get());
1260      if (LHS.isInvalid())
1261        return QualType();
1262    }
1263  
1264    RHS = UsualUnaryConversions(RHS.get());
1265    if (RHS.isInvalid())
1266      return QualType();
1267  
1268    // For conversion purposes, we ignore any qualifiers.
1269    // For example, "const float" and "float" are equivalent.
1270    QualType LHSType =
1271      Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1272    QualType RHSType =
1273      Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1274  
1275    // For conversion purposes, we ignore any atomic qualifier on the LHS.
1276    if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1277      LHSType = AtomicLHS->getValueType();
1278  
1279    // If both types are identical, no conversion is needed.
1280    if (LHSType == RHSType)
1281      return LHSType;
1282  
1283    // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1284    // The caller can deal with this (e.g. pointer + int).
1285    if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1286      return QualType();
1287  
1288    // Apply unary and bitfield promotions to the LHS's type.
1289    QualType LHSUnpromotedType = LHSType;
1290    if (LHSType->isPromotableIntegerType())
1291      LHSType = Context.getPromotedIntegerType(LHSType);
1292    QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1293    if (!LHSBitfieldPromoteTy.isNull())
1294      LHSType = LHSBitfieldPromoteTy;
1295    if (LHSType != LHSUnpromotedType && !IsCompAssign)
1296      LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1297  
1298    // If both types are identical, no conversion is needed.
1299    if (LHSType == RHSType)
1300      return LHSType;
1301  
1302    // At this point, we have two different arithmetic types.
1303  
1304    // Handle complex types first (C99 6.3.1.8p1).
1305    if (LHSType->isComplexType() || RHSType->isComplexType())
1306      return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1307                                          IsCompAssign);
1308  
1309    // Now handle "real" floating types (i.e. float, double, long double).
1310    if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1311      return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1312                                   IsCompAssign);
1313  
1314    // Handle GCC complex int extension.
1315    if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1316      return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1317                                        IsCompAssign);
1318  
1319    // Finally, we have two differing integer types.
1320    return handleIntegerConversion<doIntegralCast, doIntegralCast>
1321             (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1322  }
1323  
1324  
1325  //===----------------------------------------------------------------------===//
1326  //  Semantic Analysis for various Expression Types
1327  //===----------------------------------------------------------------------===//
1328  
1329  
1330  ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1331  Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1332                                  SourceLocation DefaultLoc,
1333                                  SourceLocation RParenLoc,
1334                                  Expr *ControllingExpr,
1335                                  ArrayRef<ParsedType> ArgTypes,
1336                                  ArrayRef<Expr *> ArgExprs) {
1337    unsigned NumAssocs = ArgTypes.size();
1338    assert(NumAssocs == ArgExprs.size());
1339  
1340    TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1341    for (unsigned i = 0; i < NumAssocs; ++i) {
1342      if (ArgTypes[i])
1343        (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1344      else
1345        Types[i] = nullptr;
1346    }
1347  
1348    ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1349                                               ControllingExpr,
1350                                               llvm::makeArrayRef(Types, NumAssocs),
1351                                               ArgExprs);
1352    delete [] Types;
1353    return ER;
1354  }
1355  
1356  ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1357  Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1358                                   SourceLocation DefaultLoc,
1359                                   SourceLocation RParenLoc,
1360                                   Expr *ControllingExpr,
1361                                   ArrayRef<TypeSourceInfo *> Types,
1362                                   ArrayRef<Expr *> Exprs) {
1363    unsigned NumAssocs = Types.size();
1364    assert(NumAssocs == Exprs.size());
1365  
1366    // Decay and strip qualifiers for the controlling expression type, and handle
1367    // placeholder type replacement. See committee discussion from WG14 DR423.
1368    ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1369    if (R.isInvalid())
1370      return ExprError();
1371    ControllingExpr = R.get();
1372  
1373    // The controlling expression is an unevaluated operand, so side effects are
1374    // likely unintended.
1375    if (ActiveTemplateInstantiations.empty() &&
1376        ControllingExpr->HasSideEffects(Context, false))
1377      Diag(ControllingExpr->getExprLoc(),
1378           diag::warn_side_effects_unevaluated_context);
1379  
1380    bool TypeErrorFound = false,
1381         IsResultDependent = ControllingExpr->isTypeDependent(),
1382         ContainsUnexpandedParameterPack
1383           = ControllingExpr->containsUnexpandedParameterPack();
1384  
1385    for (unsigned i = 0; i < NumAssocs; ++i) {
1386      if (Exprs[i]->containsUnexpandedParameterPack())
1387        ContainsUnexpandedParameterPack = true;
1388  
1389      if (Types[i]) {
1390        if (Types[i]->getType()->containsUnexpandedParameterPack())
1391          ContainsUnexpandedParameterPack = true;
1392  
1393        if (Types[i]->getType()->isDependentType()) {
1394          IsResultDependent = true;
1395        } else {
1396          // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1397          // complete object type other than a variably modified type."
1398          unsigned D = 0;
1399          if (Types[i]->getType()->isIncompleteType())
1400            D = diag::err_assoc_type_incomplete;
1401          else if (!Types[i]->getType()->isObjectType())
1402            D = diag::err_assoc_type_nonobject;
1403          else if (Types[i]->getType()->isVariablyModifiedType())
1404            D = diag::err_assoc_type_variably_modified;
1405  
1406          if (D != 0) {
1407            Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1408              << Types[i]->getTypeLoc().getSourceRange()
1409              << Types[i]->getType();
1410            TypeErrorFound = true;
1411          }
1412  
1413          // C11 6.5.1.1p2 "No two generic associations in the same generic
1414          // selection shall specify compatible types."
1415          for (unsigned j = i+1; j < NumAssocs; ++j)
1416            if (Types[j] && !Types[j]->getType()->isDependentType() &&
1417                Context.typesAreCompatible(Types[i]->getType(),
1418                                           Types[j]->getType())) {
1419              Diag(Types[j]->getTypeLoc().getBeginLoc(),
1420                   diag::err_assoc_compatible_types)
1421                << Types[j]->getTypeLoc().getSourceRange()
1422                << Types[j]->getType()
1423                << Types[i]->getType();
1424              Diag(Types[i]->getTypeLoc().getBeginLoc(),
1425                   diag::note_compat_assoc)
1426                << Types[i]->getTypeLoc().getSourceRange()
1427                << Types[i]->getType();
1428              TypeErrorFound = true;
1429            }
1430        }
1431      }
1432    }
1433    if (TypeErrorFound)
1434      return ExprError();
1435  
1436    // If we determined that the generic selection is result-dependent, don't
1437    // try to compute the result expression.
1438    if (IsResultDependent)
1439      return new (Context) GenericSelectionExpr(
1440          Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1441          ContainsUnexpandedParameterPack);
1442  
1443    SmallVector<unsigned, 1> CompatIndices;
1444    unsigned DefaultIndex = -1U;
1445    for (unsigned i = 0; i < NumAssocs; ++i) {
1446      if (!Types[i])
1447        DefaultIndex = i;
1448      else if (Context.typesAreCompatible(ControllingExpr->getType(),
1449                                          Types[i]->getType()))
1450        CompatIndices.push_back(i);
1451    }
1452  
1453    // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1454    // type compatible with at most one of the types named in its generic
1455    // association list."
1456    if (CompatIndices.size() > 1) {
1457      // We strip parens here because the controlling expression is typically
1458      // parenthesized in macro definitions.
1459      ControllingExpr = ControllingExpr->IgnoreParens();
1460      Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1461        << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1462        << (unsigned) CompatIndices.size();
1463      for (unsigned I : CompatIndices) {
1464        Diag(Types[I]->getTypeLoc().getBeginLoc(),
1465             diag::note_compat_assoc)
1466          << Types[I]->getTypeLoc().getSourceRange()
1467          << Types[I]->getType();
1468      }
1469      return ExprError();
1470    }
1471  
1472    // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1473    // its controlling expression shall have type compatible with exactly one of
1474    // the types named in its generic association list."
1475    if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1476      // We strip parens here because the controlling expression is typically
1477      // parenthesized in macro definitions.
1478      ControllingExpr = ControllingExpr->IgnoreParens();
1479      Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1480        << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1481      return ExprError();
1482    }
1483  
1484    // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1485    // type name that is compatible with the type of the controlling expression,
1486    // then the result expression of the generic selection is the expression
1487    // in that generic association. Otherwise, the result expression of the
1488    // generic selection is the expression in the default generic association."
1489    unsigned ResultIndex =
1490      CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1491  
1492    return new (Context) GenericSelectionExpr(
1493        Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1494        ContainsUnexpandedParameterPack, ResultIndex);
1495  }
1496  
1497  /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1498  /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1499  static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1500                                       unsigned Offset) {
1501    return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1502                                          S.getLangOpts());
1503  }
1504  
1505  /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1506  /// 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)1507  static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1508                                                   IdentifierInfo *UDSuffix,
1509                                                   SourceLocation UDSuffixLoc,
1510                                                   ArrayRef<Expr*> Args,
1511                                                   SourceLocation LitEndLoc) {
1512    assert(Args.size() <= 2 && "too many arguments for literal operator");
1513  
1514    QualType ArgTy[2];
1515    for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1516      ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1517      if (ArgTy[ArgIdx]->isArrayType())
1518        ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1519    }
1520  
1521    DeclarationName OpName =
1522      S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1523    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1524    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1525  
1526    LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1527    if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1528                                /*AllowRaw*/false, /*AllowTemplate*/false,
1529                                /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1530      return ExprError();
1531  
1532    return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1533  }
1534  
1535  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1536  /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1537  /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1538  /// multiple tokens.  However, the common case is that StringToks points to one
1539  /// string.
1540  ///
1541  ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1542  Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1543    assert(!StringToks.empty() && "Must have at least one string!");
1544  
1545    StringLiteralParser Literal(StringToks, PP);
1546    if (Literal.hadError)
1547      return ExprError();
1548  
1549    SmallVector<SourceLocation, 4> StringTokLocs;
1550    for (const Token &Tok : StringToks)
1551      StringTokLocs.push_back(Tok.getLocation());
1552  
1553    QualType CharTy = Context.CharTy;
1554    StringLiteral::StringKind Kind = StringLiteral::Ascii;
1555    if (Literal.isWide()) {
1556      CharTy = Context.getWideCharType();
1557      Kind = StringLiteral::Wide;
1558    } else if (Literal.isUTF8()) {
1559      Kind = StringLiteral::UTF8;
1560    } else if (Literal.isUTF16()) {
1561      CharTy = Context.Char16Ty;
1562      Kind = StringLiteral::UTF16;
1563    } else if (Literal.isUTF32()) {
1564      CharTy = Context.Char32Ty;
1565      Kind = StringLiteral::UTF32;
1566    } else if (Literal.isPascal()) {
1567      CharTy = Context.UnsignedCharTy;
1568    }
1569  
1570    QualType CharTyConst = CharTy;
1571    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1572    if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1573      CharTyConst.addConst();
1574  
1575    // Get an array type for the string, according to C99 6.4.5.  This includes
1576    // the nul terminator character as well as the string length for pascal
1577    // strings.
1578    QualType StrTy = Context.getConstantArrayType(CharTyConst,
1579                                   llvm::APInt(32, Literal.GetNumStringChars()+1),
1580                                   ArrayType::Normal, 0);
1581  
1582    // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1583    if (getLangOpts().OpenCL) {
1584      StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1585    }
1586  
1587    // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1588    StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1589                                               Kind, Literal.Pascal, StrTy,
1590                                               &StringTokLocs[0],
1591                                               StringTokLocs.size());
1592    if (Literal.getUDSuffix().empty())
1593      return Lit;
1594  
1595    // We're building a user-defined literal.
1596    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1597    SourceLocation UDSuffixLoc =
1598      getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1599                     Literal.getUDSuffixOffset());
1600  
1601    // Make sure we're allowed user-defined literals here.
1602    if (!UDLScope)
1603      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1604  
1605    // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1606    //   operator "" X (str, len)
1607    QualType SizeType = Context.getSizeType();
1608  
1609    DeclarationName OpName =
1610      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1611    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1612    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1613  
1614    QualType ArgTy[] = {
1615      Context.getArrayDecayedType(StrTy), SizeType
1616    };
1617  
1618    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1619    switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1620                                  /*AllowRaw*/false, /*AllowTemplate*/false,
1621                                  /*AllowStringTemplate*/true)) {
1622  
1623    case LOLR_Cooked: {
1624      llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1625      IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1626                                                      StringTokLocs[0]);
1627      Expr *Args[] = { Lit, LenArg };
1628  
1629      return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1630    }
1631  
1632    case LOLR_StringTemplate: {
1633      TemplateArgumentListInfo ExplicitArgs;
1634  
1635      unsigned CharBits = Context.getIntWidth(CharTy);
1636      bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1637      llvm::APSInt Value(CharBits, CharIsUnsigned);
1638  
1639      TemplateArgument TypeArg(CharTy);
1640      TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1641      ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1642  
1643      for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1644        Value = Lit->getCodeUnit(I);
1645        TemplateArgument Arg(Context, Value, CharTy);
1646        TemplateArgumentLocInfo ArgInfo;
1647        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1648      }
1649      return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1650                                      &ExplicitArgs);
1651    }
1652    case LOLR_Raw:
1653    case LOLR_Template:
1654      llvm_unreachable("unexpected literal operator lookup result");
1655    case LOLR_Error:
1656      return ExprError();
1657    }
1658    llvm_unreachable("unexpected literal operator lookup result");
1659  }
1660  
1661  ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1662  Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1663                         SourceLocation Loc,
1664                         const CXXScopeSpec *SS) {
1665    DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1666    return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1667  }
1668  
1669  /// BuildDeclRefExpr - Build an expression that references a
1670  /// declaration that does not require a closure capture.
1671  ExprResult
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)1672  Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1673                         const DeclarationNameInfo &NameInfo,
1674                         const CXXScopeSpec *SS, NamedDecl *FoundD,
1675                         const TemplateArgumentListInfo *TemplateArgs) {
1676    if (getLangOpts().CUDA)
1677      if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1678        if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1679          if (CheckCUDATarget(Caller, Callee)) {
1680            Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1681              << IdentifyCUDATarget(Callee) << D->getIdentifier()
1682              << IdentifyCUDATarget(Caller);
1683            Diag(D->getLocation(), diag::note_previous_decl)
1684              << D->getIdentifier();
1685            return ExprError();
1686          }
1687        }
1688  
1689    bool RefersToCapturedVariable =
1690        isa<VarDecl>(D) &&
1691        NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1692  
1693    DeclRefExpr *E;
1694    if (isa<VarTemplateSpecializationDecl>(D)) {
1695      VarTemplateSpecializationDecl *VarSpec =
1696          cast<VarTemplateSpecializationDecl>(D);
1697  
1698      E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1699                                          : NestedNameSpecifierLoc(),
1700                              VarSpec->getTemplateKeywordLoc(), D,
1701                              RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1702                              FoundD, TemplateArgs);
1703    } else {
1704      assert(!TemplateArgs && "No template arguments for non-variable"
1705                              " template specialization references");
1706      E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1707                                          : NestedNameSpecifierLoc(),
1708                              SourceLocation(), D, RefersToCapturedVariable,
1709                              NameInfo, Ty, VK, FoundD);
1710    }
1711  
1712    MarkDeclRefReferenced(E);
1713  
1714    if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1715        Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1716        !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1717        recordUseOfEvaluatedWeak(E);
1718  
1719    // Just in case we're building an illegal pointer-to-member.
1720    FieldDecl *FD = dyn_cast<FieldDecl>(D);
1721    if (FD && FD->isBitField())
1722      E->setObjectKind(OK_BitField);
1723  
1724    return E;
1725  }
1726  
1727  /// Decomposes the given name into a DeclarationNameInfo, its location, and
1728  /// possibly a list of template arguments.
1729  ///
1730  /// If this produces template arguments, it is permitted to call
1731  /// DecomposeTemplateName.
1732  ///
1733  /// This actually loses a lot of source location information for
1734  /// non-standard name kinds; we should consider preserving that in
1735  /// some way.
1736  void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)1737  Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1738                               TemplateArgumentListInfo &Buffer,
1739                               DeclarationNameInfo &NameInfo,
1740                               const TemplateArgumentListInfo *&TemplateArgs) {
1741    if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1742      Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1743      Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1744  
1745      ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1746                                         Id.TemplateId->NumArgs);
1747      translateTemplateArguments(TemplateArgsPtr, Buffer);
1748  
1749      TemplateName TName = Id.TemplateId->Template.get();
1750      SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1751      NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1752      TemplateArgs = &Buffer;
1753    } else {
1754      NameInfo = GetNameFromUnqualifiedId(Id);
1755      TemplateArgs = nullptr;
1756    }
1757  }
1758  
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)1759  static void emitEmptyLookupTypoDiagnostic(
1760      const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1761      DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1762      unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1763    DeclContext *Ctx =
1764        SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1765    if (!TC) {
1766      // Emit a special diagnostic for failed member lookups.
1767      // FIXME: computing the declaration context might fail here (?)
1768      if (Ctx)
1769        SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1770                                                   << SS.getRange();
1771      else
1772        SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1773      return;
1774    }
1775  
1776    std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1777    bool DroppedSpecifier =
1778        TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1779    unsigned NoteID =
1780        (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1781            ? diag::note_implicit_param_decl
1782            : diag::note_previous_decl;
1783    if (!Ctx)
1784      SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1785                           SemaRef.PDiag(NoteID));
1786    else
1787      SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1788                                   << Typo << Ctx << DroppedSpecifier
1789                                   << SS.getRange(),
1790                           SemaRef.PDiag(NoteID));
1791  }
1792  
1793  /// Diagnose an empty lookup.
1794  ///
1795  /// \return false if new lookup candidates were found
1796  bool
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,std::unique_ptr<CorrectionCandidateCallback> CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)1797  Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1798                            std::unique_ptr<CorrectionCandidateCallback> CCC,
1799                            TemplateArgumentListInfo *ExplicitTemplateArgs,
1800                            ArrayRef<Expr *> Args, TypoExpr **Out) {
1801    DeclarationName Name = R.getLookupName();
1802  
1803    unsigned diagnostic = diag::err_undeclared_var_use;
1804    unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1805    if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1806        Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1807        Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1808      diagnostic = diag::err_undeclared_use;
1809      diagnostic_suggest = diag::err_undeclared_use_suggest;
1810    }
1811  
1812    // If the original lookup was an unqualified lookup, fake an
1813    // unqualified lookup.  This is useful when (for example) the
1814    // original lookup would not have found something because it was a
1815    // dependent name.
1816    DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1817    while (DC) {
1818      if (isa<CXXRecordDecl>(DC)) {
1819        LookupQualifiedName(R, DC);
1820  
1821        if (!R.empty()) {
1822          // Don't give errors about ambiguities in this lookup.
1823          R.suppressDiagnostics();
1824  
1825          // During a default argument instantiation the CurContext points
1826          // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1827          // function parameter list, hence add an explicit check.
1828          bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1829                                ActiveTemplateInstantiations.back().Kind ==
1830              ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1831          CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1832          bool isInstance = CurMethod &&
1833                            CurMethod->isInstance() &&
1834                            DC == CurMethod->getParent() && !isDefaultArgument;
1835  
1836          // Give a code modification hint to insert 'this->'.
1837          // TODO: fixit for inserting 'Base<T>::' in the other cases.
1838          // Actually quite difficult!
1839          if (getLangOpts().MSVCCompat)
1840            diagnostic = diag::ext_found_via_dependent_bases_lookup;
1841          if (isInstance) {
1842            Diag(R.getNameLoc(), diagnostic) << Name
1843              << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1844            CheckCXXThisCapture(R.getNameLoc());
1845          } else {
1846            Diag(R.getNameLoc(), diagnostic) << Name;
1847          }
1848  
1849          // Do we really want to note all of these?
1850          for (NamedDecl *D : R)
1851            Diag(D->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 (NamedDecl *CD : Corrected) {
1913            if (FunctionTemplateDecl *FTD =
1914                     dyn_cast<FunctionTemplateDecl>(CD))
1915              AddTemplateOverloadCandidate(
1916                  FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1917                  Args, OCS);
1918            else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1919              if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1920                AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1921                                     Args, OCS);
1922          }
1923          switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1924          case OR_Success:
1925            ND = Best->Function;
1926            Corrected.setCorrectionDecl(ND);
1927            break;
1928          default:
1929            // FIXME: Arbitrarily pick the first declaration for the note.
1930            Corrected.setCorrectionDecl(ND);
1931            break;
1932          }
1933        }
1934        R.addDecl(ND);
1935        if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1936          CXXRecordDecl *Record = nullptr;
1937          if (Corrected.getCorrectionSpecifier()) {
1938            const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1939            Record = Ty->getAsCXXRecordDecl();
1940          }
1941          if (!Record)
1942            Record = cast<CXXRecordDecl>(
1943                ND->getDeclContext()->getRedeclContext());
1944          R.setNamingClass(Record);
1945        }
1946  
1947        AcceptableWithRecovery =
1948            isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1949        // FIXME: If we ended up with a typo for a type name or
1950        // Objective-C class name, we're in trouble because the parser
1951        // is in the wrong place to recover. Suggest the typo
1952        // correction, but don't make it a fix-it since we're not going
1953        // to recover well anyway.
1954        AcceptableWithoutRecovery =
1955            isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1956      } else {
1957        // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1958        // because we aren't able to recover.
1959        AcceptableWithoutRecovery = true;
1960      }
1961  
1962      if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1963        unsigned NoteID = (Corrected.getCorrectionDecl() &&
1964                           isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1965                              ? diag::note_implicit_param_decl
1966                              : diag::note_previous_decl;
1967        if (SS.isEmpty())
1968          diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1969                       PDiag(NoteID), AcceptableWithRecovery);
1970        else
1971          diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1972                                    << Name << computeDeclContext(SS, false)
1973                                    << DroppedSpecifier << SS.getRange(),
1974                       PDiag(NoteID), AcceptableWithRecovery);
1975  
1976        // Tell the callee whether to try to recover.
1977        return !AcceptableWithRecovery;
1978      }
1979    }
1980    R.clear();
1981  
1982    // Emit a special diagnostic for failed member lookups.
1983    // FIXME: computing the declaration context might fail here (?)
1984    if (!SS.isEmpty()) {
1985      Diag(R.getNameLoc(), diag::err_no_member)
1986        << Name << computeDeclContext(SS, false)
1987        << SS.getRange();
1988      return true;
1989    }
1990  
1991    // Give up, we can't recover.
1992    Diag(R.getNameLoc(), diagnostic) << Name;
1993    return true;
1994  }
1995  
1996  /// In Microsoft mode, if we are inside a template class whose parent class has
1997  /// dependent base classes, and we can't resolve an unqualified identifier, then
1998  /// assume the identifier is a member of a dependent base class.  We can only
1999  /// recover successfully in static methods, instance methods, and other contexts
2000  /// where 'this' is available.  This doesn't precisely match MSVC's
2001  /// instantiation model, but it's close enough.
2002  static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2003  recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2004                                 DeclarationNameInfo &NameInfo,
2005                                 SourceLocation TemplateKWLoc,
2006                                 const TemplateArgumentListInfo *TemplateArgs) {
2007    // Only try to recover from lookup into dependent bases in static methods or
2008    // contexts where 'this' is available.
2009    QualType ThisType = S.getCurrentThisType();
2010    const CXXRecordDecl *RD = nullptr;
2011    if (!ThisType.isNull())
2012      RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2013    else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2014      RD = MD->getParent();
2015    if (!RD || !RD->hasAnyDependentBases())
2016      return nullptr;
2017  
2018    // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2019    // is available, suggest inserting 'this->' as a fixit.
2020    SourceLocation Loc = NameInfo.getLoc();
2021    auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2022    DB << NameInfo.getName() << RD;
2023  
2024    if (!ThisType.isNull()) {
2025      DB << FixItHint::CreateInsertion(Loc, "this->");
2026      return CXXDependentScopeMemberExpr::Create(
2027          Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2028          /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2029          /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2030    }
2031  
2032    // Synthesize a fake NNS that points to the derived class.  This will
2033    // perform name lookup during template instantiation.
2034    CXXScopeSpec SS;
2035    auto *NNS =
2036        NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2037    SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2038    return DependentScopeDeclRefExpr::Create(
2039        Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2040        TemplateArgs);
2041  }
2042  
2043  ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,std::unique_ptr<CorrectionCandidateCallback> CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2044  Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2045                          SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2046                          bool HasTrailingLParen, bool IsAddressOfOperand,
2047                          std::unique_ptr<CorrectionCandidateCallback> CCC,
2048                          bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2049    assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2050           "cannot be direct & operand and have a trailing lparen");
2051    if (SS.isInvalid())
2052      return ExprError();
2053  
2054    TemplateArgumentListInfo TemplateArgsBuffer;
2055  
2056    // Decompose the UnqualifiedId into the following data.
2057    DeclarationNameInfo NameInfo;
2058    const TemplateArgumentListInfo *TemplateArgs;
2059    DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2060  
2061    DeclarationName Name = NameInfo.getName();
2062    IdentifierInfo *II = Name.getAsIdentifierInfo();
2063    SourceLocation NameLoc = NameInfo.getLoc();
2064  
2065    // C++ [temp.dep.expr]p3:
2066    //   An id-expression is type-dependent if it contains:
2067    //     -- an identifier that was declared with a dependent type,
2068    //        (note: handled after lookup)
2069    //     -- a template-id that is dependent,
2070    //        (note: handled in BuildTemplateIdExpr)
2071    //     -- a conversion-function-id that specifies a dependent type,
2072    //     -- a nested-name-specifier that contains a class-name that
2073    //        names a dependent type.
2074    // Determine whether this is a member of an unknown specialization;
2075    // we need to handle these differently.
2076    bool DependentID = false;
2077    if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2078        Name.getCXXNameType()->isDependentType()) {
2079      DependentID = true;
2080    } else if (SS.isSet()) {
2081      if (DeclContext *DC = computeDeclContext(SS, false)) {
2082        if (RequireCompleteDeclContext(SS, DC))
2083          return ExprError();
2084      } else {
2085        DependentID = true;
2086      }
2087    }
2088  
2089    if (DependentID)
2090      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2091                                        IsAddressOfOperand, TemplateArgs);
2092  
2093    // Perform the required lookup.
2094    LookupResult R(*this, NameInfo,
2095                   (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2096                    ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2097    if (TemplateArgs) {
2098      // Lookup the template name again to correctly establish the context in
2099      // which it was found. This is really unfortunate as we already did the
2100      // lookup to determine that it was a template name in the first place. If
2101      // this becomes a performance hit, we can work harder to preserve those
2102      // results until we get here but it's likely not worth it.
2103      bool MemberOfUnknownSpecialization;
2104      LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2105                         MemberOfUnknownSpecialization);
2106  
2107      if (MemberOfUnknownSpecialization ||
2108          (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2109        return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2110                                          IsAddressOfOperand, TemplateArgs);
2111    } else {
2112      bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2113      LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2114  
2115      // If the result might be in a dependent base class, this is a dependent
2116      // id-expression.
2117      if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2118        return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2119                                          IsAddressOfOperand, TemplateArgs);
2120  
2121      // If this reference is in an Objective-C method, then we need to do
2122      // some special Objective-C lookup, too.
2123      if (IvarLookupFollowUp) {
2124        ExprResult E(LookupInObjCMethod(R, S, II, true));
2125        if (E.isInvalid())
2126          return ExprError();
2127  
2128        if (Expr *Ex = E.getAs<Expr>())
2129          return Ex;
2130      }
2131    }
2132  
2133    if (R.isAmbiguous())
2134      return ExprError();
2135  
2136    // This could be an implicitly declared function reference (legal in C90,
2137    // extension in C99, forbidden in C++).
2138    if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2139      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2140      if (D) R.addDecl(D);
2141    }
2142  
2143    // Determine whether this name might be a candidate for
2144    // argument-dependent lookup.
2145    bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2146  
2147    if (R.empty() && !ADL) {
2148      if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2149        if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2150                                                     TemplateKWLoc, TemplateArgs))
2151          return E;
2152      }
2153  
2154      // Don't diagnose an empty lookup for inline assembly.
2155      if (IsInlineAsmIdentifier)
2156        return ExprError();
2157  
2158      // If this name wasn't predeclared and if this is not a function
2159      // call, diagnose the problem.
2160      TypoExpr *TE = nullptr;
2161      auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2162          II, SS.isValid() ? SS.getScopeRep() : nullptr);
2163      DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2164      assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2165             "Typo correction callback misconfigured");
2166      if (CCC) {
2167        // Make sure the callback knows what the typo being diagnosed is.
2168        CCC->setTypoName(II);
2169        if (SS.isValid())
2170          CCC->setTypoNNS(SS.getScopeRep());
2171      }
2172      if (DiagnoseEmptyLookup(S, SS, R,
2173                              CCC ? std::move(CCC) : std::move(DefaultValidator),
2174                              nullptr, None, &TE)) {
2175        if (TE && KeywordReplacement) {
2176          auto &State = getTypoExprState(TE);
2177          auto BestTC = State.Consumer->getNextCorrection();
2178          if (BestTC.isKeyword()) {
2179            auto *II = BestTC.getCorrectionAsIdentifierInfo();
2180            if (State.DiagHandler)
2181              State.DiagHandler(BestTC);
2182            KeywordReplacement->startToken();
2183            KeywordReplacement->setKind(II->getTokenID());
2184            KeywordReplacement->setIdentifierInfo(II);
2185            KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2186            // Clean up the state associated with the TypoExpr, since it has
2187            // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2188            clearDelayedTypo(TE);
2189            // Signal that a correction to a keyword was performed by returning a
2190            // valid-but-null ExprResult.
2191            return (Expr*)nullptr;
2192          }
2193          State.Consumer->resetCorrectionStream();
2194        }
2195        return TE ? TE : ExprError();
2196      }
2197  
2198      assert(!R.empty() &&
2199             "DiagnoseEmptyLookup returned false but added no results");
2200  
2201      // If we found an Objective-C instance variable, let
2202      // LookupInObjCMethod build the appropriate expression to
2203      // reference the ivar.
2204      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2205        R.clear();
2206        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2207        // In a hopelessly buggy code, Objective-C instance variable
2208        // lookup fails and no expression will be built to reference it.
2209        if (!E.isInvalid() && !E.get())
2210          return ExprError();
2211        return E;
2212      }
2213    }
2214  
2215    // This is guaranteed from this point on.
2216    assert(!R.empty() || ADL);
2217  
2218    // Check whether this might be a C++ implicit instance member access.
2219    // C++ [class.mfct.non-static]p3:
2220    //   When an id-expression that is not part of a class member access
2221    //   syntax and not used to form a pointer to member is used in the
2222    //   body of a non-static member function of class X, if name lookup
2223    //   resolves the name in the id-expression to a non-static non-type
2224    //   member of some class C, the id-expression is transformed into a
2225    //   class member access expression using (*this) as the
2226    //   postfix-expression to the left of the . operator.
2227    //
2228    // But we don't actually need to do this for '&' operands if R
2229    // resolved to a function or overloaded function set, because the
2230    // expression is ill-formed if it actually works out to be a
2231    // non-static member function:
2232    //
2233    // C++ [expr.ref]p4:
2234    //   Otherwise, if E1.E2 refers to a non-static member function. . .
2235    //   [t]he expression can be used only as the left-hand operand of a
2236    //   member function call.
2237    //
2238    // There are other safeguards against such uses, but it's important
2239    // to get this right here so that we don't end up making a
2240    // spuriously dependent expression if we're inside a dependent
2241    // instance method.
2242    if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2243      bool MightBeImplicitMember;
2244      if (!IsAddressOfOperand)
2245        MightBeImplicitMember = true;
2246      else if (!SS.isEmpty())
2247        MightBeImplicitMember = false;
2248      else if (R.isOverloadedResult())
2249        MightBeImplicitMember = false;
2250      else if (R.isUnresolvableResult())
2251        MightBeImplicitMember = true;
2252      else
2253        MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2254                                isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2255                                isa<MSPropertyDecl>(R.getFoundDecl());
2256  
2257      if (MightBeImplicitMember)
2258        return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2259                                               R, TemplateArgs, S);
2260    }
2261  
2262    if (TemplateArgs || TemplateKWLoc.isValid()) {
2263  
2264      // In C++1y, if this is a variable template id, then check it
2265      // in BuildTemplateIdExpr().
2266      // The single lookup result must be a variable template declaration.
2267      if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2268          Id.TemplateId->Kind == TNK_Var_template) {
2269        assert(R.getAsSingle<VarTemplateDecl>() &&
2270               "There should only be one declaration found.");
2271      }
2272  
2273      return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2274    }
2275  
2276    return BuildDeclarationNameExpr(SS, R, ADL);
2277  }
2278  
2279  /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2280  /// declaration name, generally during template instantiation.
2281  /// There's a large number of things which don't need to be done along
2282  /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2283  ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2284      CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2285      bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2286    DeclContext *DC = computeDeclContext(SS, false);
2287    if (!DC)
2288      return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2289                                       NameInfo, /*TemplateArgs=*/nullptr);
2290  
2291    if (RequireCompleteDeclContext(SS, DC))
2292      return ExprError();
2293  
2294    LookupResult R(*this, NameInfo, LookupOrdinaryName);
2295    LookupQualifiedName(R, DC);
2296  
2297    if (R.isAmbiguous())
2298      return ExprError();
2299  
2300    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2301      return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2302                                       NameInfo, /*TemplateArgs=*/nullptr);
2303  
2304    if (R.empty()) {
2305      Diag(NameInfo.getLoc(), diag::err_no_member)
2306        << NameInfo.getName() << DC << SS.getRange();
2307      return ExprError();
2308    }
2309  
2310    if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2311      // Diagnose a missing typename if this resolved unambiguously to a type in
2312      // a dependent context.  If we can recover with a type, downgrade this to
2313      // a warning in Microsoft compatibility mode.
2314      unsigned DiagID = diag::err_typename_missing;
2315      if (RecoveryTSI && getLangOpts().MSVCCompat)
2316        DiagID = diag::ext_typename_missing;
2317      SourceLocation Loc = SS.getBeginLoc();
2318      auto D = Diag(Loc, DiagID);
2319      D << SS.getScopeRep() << NameInfo.getName().getAsString()
2320        << SourceRange(Loc, NameInfo.getEndLoc());
2321  
2322      // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2323      // context.
2324      if (!RecoveryTSI)
2325        return ExprError();
2326  
2327      // Only issue the fixit if we're prepared to recover.
2328      D << FixItHint::CreateInsertion(Loc, "typename ");
2329  
2330      // Recover by pretending this was an elaborated type.
2331      QualType Ty = Context.getTypeDeclType(TD);
2332      TypeLocBuilder TLB;
2333      TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2334  
2335      QualType ET = getElaboratedType(ETK_None, SS, Ty);
2336      ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2337      QTL.setElaboratedKeywordLoc(SourceLocation());
2338      QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2339  
2340      *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2341  
2342      return ExprEmpty();
2343    }
2344  
2345    // Defend against this resolving to an implicit member access. We usually
2346    // won't get here if this might be a legitimate a class member (we end up in
2347    // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2348    // a pointer-to-member or in an unevaluated context in C++11.
2349    if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2350      return BuildPossibleImplicitMemberExpr(SS,
2351                                             /*TemplateKWLoc=*/SourceLocation(),
2352                                             R, /*TemplateArgs=*/nullptr, S);
2353  
2354    return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2355  }
2356  
2357  /// LookupInObjCMethod - The parser has read a name in, and Sema has
2358  /// detected that we're currently inside an ObjC method.  Perform some
2359  /// additional lookup.
2360  ///
2361  /// Ideally, most of this would be done by lookup, but there's
2362  /// actually quite a lot of extra work involved.
2363  ///
2364  /// Returns a null sentinel to indicate trivial success.
2365  ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2366  Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2367                           IdentifierInfo *II, bool AllowBuiltinCreation) {
2368    SourceLocation Loc = Lookup.getNameLoc();
2369    ObjCMethodDecl *CurMethod = getCurMethodDecl();
2370  
2371    // Check for error condition which is already reported.
2372    if (!CurMethod)
2373      return ExprError();
2374  
2375    // There are two cases to handle here.  1) scoped lookup could have failed,
2376    // in which case we should look for an ivar.  2) scoped lookup could have
2377    // found a decl, but that decl is outside the current instance method (i.e.
2378    // a global variable).  In these two cases, we do a lookup for an ivar with
2379    // this name, if the lookup sucedes, we replace it our current decl.
2380  
2381    // If we're in a class method, we don't normally want to look for
2382    // ivars.  But if we don't find anything else, and there's an
2383    // ivar, that's an error.
2384    bool IsClassMethod = CurMethod->isClassMethod();
2385  
2386    bool LookForIvars;
2387    if (Lookup.empty())
2388      LookForIvars = true;
2389    else if (IsClassMethod)
2390      LookForIvars = false;
2391    else
2392      LookForIvars = (Lookup.isSingleResult() &&
2393                      Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2394    ObjCInterfaceDecl *IFace = nullptr;
2395    if (LookForIvars) {
2396      IFace = CurMethod->getClassInterface();
2397      ObjCInterfaceDecl *ClassDeclared;
2398      ObjCIvarDecl *IV = nullptr;
2399      if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2400        // Diagnose using an ivar in a class method.
2401        if (IsClassMethod)
2402          return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2403                           << IV->getDeclName());
2404  
2405        // If we're referencing an invalid decl, just return this as a silent
2406        // error node.  The error diagnostic was already emitted on the decl.
2407        if (IV->isInvalidDecl())
2408          return ExprError();
2409  
2410        // Check if referencing a field with __attribute__((deprecated)).
2411        if (DiagnoseUseOfDecl(IV, Loc))
2412          return ExprError();
2413  
2414        // Diagnose the use of an ivar outside of the declaring class.
2415        if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2416            !declaresSameEntity(ClassDeclared, IFace) &&
2417            !getLangOpts().DebuggerSupport)
2418          Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2419  
2420        // FIXME: This should use a new expr for a direct reference, don't
2421        // turn this into Self->ivar, just return a BareIVarExpr or something.
2422        IdentifierInfo &II = Context.Idents.get("self");
2423        UnqualifiedId SelfName;
2424        SelfName.setIdentifier(&II, SourceLocation());
2425        SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2426        CXXScopeSpec SelfScopeSpec;
2427        SourceLocation TemplateKWLoc;
2428        ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2429                                                SelfName, false, false);
2430        if (SelfExpr.isInvalid())
2431          return ExprError();
2432  
2433        SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2434        if (SelfExpr.isInvalid())
2435          return ExprError();
2436  
2437        MarkAnyDeclReferenced(Loc, IV, true);
2438  
2439        ObjCMethodFamily MF = CurMethod->getMethodFamily();
2440        if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2441            !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2442          Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2443  
2444        ObjCIvarRefExpr *Result = new (Context)
2445            ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2446                            IV->getLocation(), SelfExpr.get(), true, true);
2447  
2448        if (getLangOpts().ObjCAutoRefCount) {
2449          if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2450            if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2451              recordUseOfEvaluatedWeak(Result);
2452          }
2453          if (CurContext->isClosure())
2454            Diag(Loc, diag::warn_implicitly_retains_self)
2455              << FixItHint::CreateInsertion(Loc, "self->");
2456        }
2457  
2458        return Result;
2459      }
2460    } else if (CurMethod->isInstanceMethod()) {
2461      // We should warn if a local variable hides an ivar.
2462      if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2463        ObjCInterfaceDecl *ClassDeclared;
2464        if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2465          if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2466              declaresSameEntity(IFace, ClassDeclared))
2467            Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2468        }
2469      }
2470    } else if (Lookup.isSingleResult() &&
2471               Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2472      // If accessing a stand-alone ivar in a class method, this is an error.
2473      if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2474        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2475                         << IV->getDeclName());
2476    }
2477  
2478    if (Lookup.empty() && II && AllowBuiltinCreation) {
2479      // FIXME. Consolidate this with similar code in LookupName.
2480      if (unsigned BuiltinID = II->getBuiltinID()) {
2481        if (!(getLangOpts().CPlusPlus &&
2482              Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2483          NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2484                                             S, Lookup.isForRedeclaration(),
2485                                             Lookup.getNameLoc());
2486          if (D) Lookup.addDecl(D);
2487        }
2488      }
2489    }
2490    // Sentinel value saying that we didn't do anything special.
2491    return ExprResult((Expr *)nullptr);
2492  }
2493  
2494  /// \brief Cast a base object to a member's actual type.
2495  ///
2496  /// Logically this happens in three phases:
2497  ///
2498  /// * First we cast from the base type to the naming class.
2499  ///   The naming class is the class into which we were looking
2500  ///   when we found the member;  it's the qualifier type if a
2501  ///   qualifier was provided, and otherwise it's the base type.
2502  ///
2503  /// * Next we cast from the naming class to the declaring class.
2504  ///   If the member we found was brought into a class's scope by
2505  ///   a using declaration, this is that class;  otherwise it's
2506  ///   the class declaring the member.
2507  ///
2508  /// * Finally we cast from the declaring class to the "true"
2509  ///   declaring class of the member.  This conversion does not
2510  ///   obey access control.
2511  ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2512  Sema::PerformObjectMemberConversion(Expr *From,
2513                                      NestedNameSpecifier *Qualifier,
2514                                      NamedDecl *FoundDecl,
2515                                      NamedDecl *Member) {
2516    CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2517    if (!RD)
2518      return From;
2519  
2520    QualType DestRecordType;
2521    QualType DestType;
2522    QualType FromRecordType;
2523    QualType FromType = From->getType();
2524    bool PointerConversions = false;
2525    if (isa<FieldDecl>(Member)) {
2526      DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2527  
2528      if (FromType->getAs<PointerType>()) {
2529        DestType = Context.getPointerType(DestRecordType);
2530        FromRecordType = FromType->getPointeeType();
2531        PointerConversions = true;
2532      } else {
2533        DestType = DestRecordType;
2534        FromRecordType = FromType;
2535      }
2536    } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2537      if (Method->isStatic())
2538        return From;
2539  
2540      DestType = Method->getThisType(Context);
2541      DestRecordType = DestType->getPointeeType();
2542  
2543      if (FromType->getAs<PointerType>()) {
2544        FromRecordType = FromType->getPointeeType();
2545        PointerConversions = true;
2546      } else {
2547        FromRecordType = FromType;
2548        DestType = DestRecordType;
2549      }
2550    } else {
2551      // No conversion necessary.
2552      return From;
2553    }
2554  
2555    if (DestType->isDependentType() || FromType->isDependentType())
2556      return From;
2557  
2558    // If the unqualified types are the same, no conversion is necessary.
2559    if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2560      return From;
2561  
2562    SourceRange FromRange = From->getSourceRange();
2563    SourceLocation FromLoc = FromRange.getBegin();
2564  
2565    ExprValueKind VK = From->getValueKind();
2566  
2567    // C++ [class.member.lookup]p8:
2568    //   [...] Ambiguities can often be resolved by qualifying a name with its
2569    //   class name.
2570    //
2571    // If the member was a qualified name and the qualified referred to a
2572    // specific base subobject type, we'll cast to that intermediate type
2573    // first and then to the object in which the member is declared. That allows
2574    // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2575    //
2576    //   class Base { public: int x; };
2577    //   class Derived1 : public Base { };
2578    //   class Derived2 : public Base { };
2579    //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2580    //
2581    //   void VeryDerived::f() {
2582    //     x = 17; // error: ambiguous base subobjects
2583    //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2584    //   }
2585    if (Qualifier && Qualifier->getAsType()) {
2586      QualType QType = QualType(Qualifier->getAsType(), 0);
2587      assert(QType->isRecordType() && "lookup done with non-record type");
2588  
2589      QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2590  
2591      // In C++98, the qualifier type doesn't actually have to be a base
2592      // type of the object type, in which case we just ignore it.
2593      // Otherwise build the appropriate casts.
2594      if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2595        CXXCastPath BasePath;
2596        if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2597                                         FromLoc, FromRange, &BasePath))
2598          return ExprError();
2599  
2600        if (PointerConversions)
2601          QType = Context.getPointerType(QType);
2602        From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2603                                 VK, &BasePath).get();
2604  
2605        FromType = QType;
2606        FromRecordType = QRecordType;
2607  
2608        // If the qualifier type was the same as the destination type,
2609        // we're done.
2610        if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2611          return From;
2612      }
2613    }
2614  
2615    bool IgnoreAccess = false;
2616  
2617    // If we actually found the member through a using declaration, cast
2618    // down to the using declaration's type.
2619    //
2620    // Pointer equality is fine here because only one declaration of a
2621    // class ever has member declarations.
2622    if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2623      assert(isa<UsingShadowDecl>(FoundDecl));
2624      QualType URecordType = Context.getTypeDeclType(
2625                             cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2626  
2627      // We only need to do this if the naming-class to declaring-class
2628      // conversion is non-trivial.
2629      if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2630        assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2631        CXXCastPath BasePath;
2632        if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2633                                         FromLoc, FromRange, &BasePath))
2634          return ExprError();
2635  
2636        QualType UType = URecordType;
2637        if (PointerConversions)
2638          UType = Context.getPointerType(UType);
2639        From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2640                                 VK, &BasePath).get();
2641        FromType = UType;
2642        FromRecordType = URecordType;
2643      }
2644  
2645      // We don't do access control for the conversion from the
2646      // declaring class to the true declaring class.
2647      IgnoreAccess = true;
2648    }
2649  
2650    CXXCastPath BasePath;
2651    if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2652                                     FromLoc, FromRange, &BasePath,
2653                                     IgnoreAccess))
2654      return ExprError();
2655  
2656    return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2657                             VK, &BasePath);
2658  }
2659  
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)2660  bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2661                                        const LookupResult &R,
2662                                        bool HasTrailingLParen) {
2663    // Only when used directly as the postfix-expression of a call.
2664    if (!HasTrailingLParen)
2665      return false;
2666  
2667    // Never if a scope specifier was provided.
2668    if (SS.isSet())
2669      return false;
2670  
2671    // Only in C++ or ObjC++.
2672    if (!getLangOpts().CPlusPlus)
2673      return false;
2674  
2675    // Turn off ADL when we find certain kinds of declarations during
2676    // normal lookup:
2677    for (NamedDecl *D : R) {
2678      // C++0x [basic.lookup.argdep]p3:
2679      //     -- a declaration of a class member
2680      // Since using decls preserve this property, we check this on the
2681      // original decl.
2682      if (D->isCXXClassMember())
2683        return false;
2684  
2685      // C++0x [basic.lookup.argdep]p3:
2686      //     -- a block-scope function declaration that is not a
2687      //        using-declaration
2688      // NOTE: we also trigger this for function templates (in fact, we
2689      // don't check the decl type at all, since all other decl types
2690      // turn off ADL anyway).
2691      if (isa<UsingShadowDecl>(D))
2692        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2693      else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2694        return false;
2695  
2696      // C++0x [basic.lookup.argdep]p3:
2697      //     -- a declaration that is neither a function or a function
2698      //        template
2699      // And also for builtin functions.
2700      if (isa<FunctionDecl>(D)) {
2701        FunctionDecl *FDecl = cast<FunctionDecl>(D);
2702  
2703        // But also builtin functions.
2704        if (FDecl->getBuiltinID() && FDecl->isImplicit())
2705          return false;
2706      } else if (!isa<FunctionTemplateDecl>(D))
2707        return false;
2708    }
2709  
2710    return true;
2711  }
2712  
2713  
2714  /// Diagnoses obvious problems with the use of the given declaration
2715  /// as an expression.  This is only actually called for lookups that
2716  /// were not overloaded, and it doesn't promise that the declaration
2717  /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)2718  static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2719    if (isa<TypedefNameDecl>(D)) {
2720      S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2721      return true;
2722    }
2723  
2724    if (isa<ObjCInterfaceDecl>(D)) {
2725      S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2726      return true;
2727    }
2728  
2729    if (isa<NamespaceDecl>(D)) {
2730      S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2731      return true;
2732    }
2733  
2734    return false;
2735  }
2736  
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)2737  ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2738                                            LookupResult &R, bool NeedsADL,
2739                                            bool AcceptInvalidDecl) {
2740    // If this is a single, fully-resolved result and we don't need ADL,
2741    // just build an ordinary singleton decl ref.
2742    if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2743      return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2744                                      R.getRepresentativeDecl(), nullptr,
2745                                      AcceptInvalidDecl);
2746  
2747    // We only need to check the declaration if there's exactly one
2748    // result, because in the overloaded case the results can only be
2749    // functions and function templates.
2750    if (R.isSingleResult() &&
2751        CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2752      return ExprError();
2753  
2754    // Otherwise, just build an unresolved lookup expression.  Suppress
2755    // any lookup-related diagnostics; we'll hash these out later, when
2756    // we've picked a target.
2757    R.suppressDiagnostics();
2758  
2759    UnresolvedLookupExpr *ULE
2760      = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2761                                     SS.getWithLocInContext(Context),
2762                                     R.getLookupNameInfo(),
2763                                     NeedsADL, R.isOverloadedResult(),
2764                                     R.begin(), R.end());
2765  
2766    return ULE;
2767  }
2768  
2769  /// \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)2770  ExprResult Sema::BuildDeclarationNameExpr(
2771      const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2772      NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2773      bool AcceptInvalidDecl) {
2774    assert(D && "Cannot refer to a NULL declaration");
2775    assert(!isa<FunctionTemplateDecl>(D) &&
2776           "Cannot refer unambiguously to a function template");
2777  
2778    SourceLocation Loc = NameInfo.getLoc();
2779    if (CheckDeclInExpr(*this, Loc, D))
2780      return ExprError();
2781  
2782    if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2783      // Specifically diagnose references to class templates that are missing
2784      // a template argument list.
2785      Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2786                                             << Template << SS.getRange();
2787      Diag(Template->getLocation(), diag::note_template_decl_here);
2788      return ExprError();
2789    }
2790  
2791    // Make sure that we're referring to a value.
2792    ValueDecl *VD = dyn_cast<ValueDecl>(D);
2793    if (!VD) {
2794      Diag(Loc, diag::err_ref_non_value)
2795        << D << SS.getRange();
2796      Diag(D->getLocation(), diag::note_declared_at);
2797      return ExprError();
2798    }
2799  
2800    // Check whether this declaration can be used. Note that we suppress
2801    // this check when we're going to perform argument-dependent lookup
2802    // on this function name, because this might not be the function
2803    // that overload resolution actually selects.
2804    if (DiagnoseUseOfDecl(VD, Loc))
2805      return ExprError();
2806  
2807    // Only create DeclRefExpr's for valid Decl's.
2808    if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2809      return ExprError();
2810  
2811    // Handle members of anonymous structs and unions.  If we got here,
2812    // and the reference is to a class member indirect field, then this
2813    // must be the subject of a pointer-to-member expression.
2814    if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2815      if (!indirectField->isCXXClassMember())
2816        return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2817                                                        indirectField);
2818  
2819    {
2820      QualType type = VD->getType();
2821      ExprValueKind valueKind = VK_RValue;
2822  
2823      switch (D->getKind()) {
2824      // Ignore all the non-ValueDecl kinds.
2825  #define ABSTRACT_DECL(kind)
2826  #define VALUE(type, base)
2827  #define DECL(type, base) \
2828      case Decl::type:
2829  #include "clang/AST/DeclNodes.inc"
2830        llvm_unreachable("invalid value decl kind");
2831  
2832      // These shouldn't make it here.
2833      case Decl::ObjCAtDefsField:
2834      case Decl::ObjCIvar:
2835        llvm_unreachable("forming non-member reference to ivar?");
2836  
2837      // Enum constants are always r-values and never references.
2838      // Unresolved using declarations are dependent.
2839      case Decl::EnumConstant:
2840      case Decl::UnresolvedUsingValue:
2841        valueKind = VK_RValue;
2842        break;
2843  
2844      // Fields and indirect fields that got here must be for
2845      // pointer-to-member expressions; we just call them l-values for
2846      // internal consistency, because this subexpression doesn't really
2847      // exist in the high-level semantics.
2848      case Decl::Field:
2849      case Decl::IndirectField:
2850        assert(getLangOpts().CPlusPlus &&
2851               "building reference to field in C?");
2852  
2853        // These can't have reference type in well-formed programs, but
2854        // for internal consistency we do this anyway.
2855        type = type.getNonReferenceType();
2856        valueKind = VK_LValue;
2857        break;
2858  
2859      // Non-type template parameters are either l-values or r-values
2860      // depending on the type.
2861      case Decl::NonTypeTemplateParm: {
2862        if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2863          type = reftype->getPointeeType();
2864          valueKind = VK_LValue; // even if the parameter is an r-value reference
2865          break;
2866        }
2867  
2868        // For non-references, we need to strip qualifiers just in case
2869        // the template parameter was declared as 'const int' or whatever.
2870        valueKind = VK_RValue;
2871        type = type.getUnqualifiedType();
2872        break;
2873      }
2874  
2875      case Decl::Var:
2876      case Decl::VarTemplateSpecialization:
2877      case Decl::VarTemplatePartialSpecialization:
2878        // In C, "extern void blah;" is valid and is an r-value.
2879        if (!getLangOpts().CPlusPlus &&
2880            !type.hasQualifiers() &&
2881            type->isVoidType()) {
2882          valueKind = VK_RValue;
2883          break;
2884        }
2885        // fallthrough
2886  
2887      case Decl::ImplicitParam:
2888      case Decl::ParmVar: {
2889        // These are always l-values.
2890        valueKind = VK_LValue;
2891        type = type.getNonReferenceType();
2892  
2893        // FIXME: Does the addition of const really only apply in
2894        // potentially-evaluated contexts? Since the variable isn't actually
2895        // captured in an unevaluated context, it seems that the answer is no.
2896        if (!isUnevaluatedContext()) {
2897          QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2898          if (!CapturedType.isNull())
2899            type = CapturedType;
2900        }
2901  
2902        break;
2903      }
2904  
2905      case Decl::Function: {
2906        if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2907          if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2908            type = Context.BuiltinFnTy;
2909            valueKind = VK_RValue;
2910            break;
2911          }
2912        }
2913  
2914        const FunctionType *fty = type->castAs<FunctionType>();
2915  
2916        // If we're referring to a function with an __unknown_anytype
2917        // result type, make the entire expression __unknown_anytype.
2918        if (fty->getReturnType() == Context.UnknownAnyTy) {
2919          type = Context.UnknownAnyTy;
2920          valueKind = VK_RValue;
2921          break;
2922        }
2923  
2924        // Functions are l-values in C++.
2925        if (getLangOpts().CPlusPlus) {
2926          valueKind = VK_LValue;
2927          break;
2928        }
2929  
2930        // C99 DR 316 says that, if a function type comes from a
2931        // function definition (without a prototype), that type is only
2932        // used for checking compatibility. Therefore, when referencing
2933        // the function, we pretend that we don't have the full function
2934        // type.
2935        if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2936            isa<FunctionProtoType>(fty))
2937          type = Context.getFunctionNoProtoType(fty->getReturnType(),
2938                                                fty->getExtInfo());
2939  
2940        // Functions are r-values in C.
2941        valueKind = VK_RValue;
2942        break;
2943      }
2944  
2945      case Decl::MSProperty:
2946        valueKind = VK_LValue;
2947        break;
2948  
2949      case Decl::CXXMethod:
2950        // If we're referring to a method with an __unknown_anytype
2951        // result type, make the entire expression __unknown_anytype.
2952        // This should only be possible with a type written directly.
2953        if (const FunctionProtoType *proto
2954              = dyn_cast<FunctionProtoType>(VD->getType()))
2955          if (proto->getReturnType() == Context.UnknownAnyTy) {
2956            type = Context.UnknownAnyTy;
2957            valueKind = VK_RValue;
2958            break;
2959          }
2960  
2961        // C++ methods are l-values if static, r-values if non-static.
2962        if (cast<CXXMethodDecl>(VD)->isStatic()) {
2963          valueKind = VK_LValue;
2964          break;
2965        }
2966        // fallthrough
2967  
2968      case Decl::CXXConversion:
2969      case Decl::CXXDestructor:
2970      case Decl::CXXConstructor:
2971        valueKind = VK_RValue;
2972        break;
2973      }
2974  
2975      return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2976                              TemplateArgs);
2977    }
2978  }
2979  
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)2980  static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2981                                      SmallString<32> &Target) {
2982    Target.resize(CharByteWidth * (Source.size() + 1));
2983    char *ResultPtr = &Target[0];
2984    const UTF8 *ErrorPtr;
2985    bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2986    (void)success;
2987    assert(success);
2988    Target.resize(ResultPtr - &Target[0]);
2989  }
2990  
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentType IT)2991  ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2992                                       PredefinedExpr::IdentType IT) {
2993    // Pick the current block, lambda, captured statement or function.
2994    Decl *currentDecl = nullptr;
2995    if (const BlockScopeInfo *BSI = getCurBlock())
2996      currentDecl = BSI->TheDecl;
2997    else if (const LambdaScopeInfo *LSI = getCurLambda())
2998      currentDecl = LSI->CallOperator;
2999    else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3000      currentDecl = CSI->TheCapturedDecl;
3001    else
3002      currentDecl = getCurFunctionOrMethodDecl();
3003  
3004    if (!currentDecl) {
3005      Diag(Loc, diag::ext_predef_outside_function);
3006      currentDecl = Context.getTranslationUnitDecl();
3007    }
3008  
3009    QualType ResTy;
3010    StringLiteral *SL = nullptr;
3011    if (cast<DeclContext>(currentDecl)->isDependentContext())
3012      ResTy = Context.DependentTy;
3013    else {
3014      // Pre-defined identifiers are of type char[x], where x is the length of
3015      // the string.
3016      auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3017      unsigned Length = Str.length();
3018  
3019      llvm::APInt LengthI(32, Length + 1);
3020      if (IT == PredefinedExpr::LFunction) {
3021        ResTy = Context.WideCharTy.withConst();
3022        SmallString<32> RawChars;
3023        ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3024                                Str, RawChars);
3025        ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3026                                             /*IndexTypeQuals*/ 0);
3027        SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3028                                   /*Pascal*/ false, ResTy, Loc);
3029      } else {
3030        ResTy = Context.CharTy.withConst();
3031        ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3032                                             /*IndexTypeQuals*/ 0);
3033        SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3034                                   /*Pascal*/ false, ResTy, Loc);
3035      }
3036    }
3037  
3038    return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3039  }
3040  
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3041  ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3042    PredefinedExpr::IdentType IT;
3043  
3044    switch (Kind) {
3045    default: llvm_unreachable("Unknown simple primary expr!");
3046    case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3047    case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3048    case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3049    case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3050    case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3051    case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3052    }
3053  
3054    return BuildPredefinedExpr(Loc, IT);
3055  }
3056  
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3057  ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3058    SmallString<16> CharBuffer;
3059    bool Invalid = false;
3060    StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3061    if (Invalid)
3062      return ExprError();
3063  
3064    CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3065                              PP, Tok.getKind());
3066    if (Literal.hadError())
3067      return ExprError();
3068  
3069    QualType Ty;
3070    if (Literal.isWide())
3071      Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3072    else if (Literal.isUTF16())
3073      Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3074    else if (Literal.isUTF32())
3075      Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3076    else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3077      Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3078    else
3079      Ty = Context.CharTy;  // 'x' -> char in C++
3080  
3081    CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3082    if (Literal.isWide())
3083      Kind = CharacterLiteral::Wide;
3084    else if (Literal.isUTF16())
3085      Kind = CharacterLiteral::UTF16;
3086    else if (Literal.isUTF32())
3087      Kind = CharacterLiteral::UTF32;
3088  
3089    Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3090                                               Tok.getLocation());
3091  
3092    if (Literal.getUDSuffix().empty())
3093      return Lit;
3094  
3095    // We're building a user-defined literal.
3096    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3097    SourceLocation UDSuffixLoc =
3098      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3099  
3100    // Make sure we're allowed user-defined literals here.
3101    if (!UDLScope)
3102      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3103  
3104    // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3105    //   operator "" X (ch)
3106    return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3107                                          Lit, Tok.getLocation());
3108  }
3109  
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3110  ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3111    unsigned IntSize = Context.getTargetInfo().getIntWidth();
3112    return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3113                                  Context.IntTy, Loc);
3114  }
3115  
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3116  static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3117                                    QualType Ty, SourceLocation Loc) {
3118    const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3119  
3120    using llvm::APFloat;
3121    APFloat Val(Format);
3122  
3123    APFloat::opStatus result = Literal.GetFloatValue(Val);
3124  
3125    // Overflow is always an error, but underflow is only an error if
3126    // we underflowed to zero (APFloat reports denormals as underflow).
3127    if ((result & APFloat::opOverflow) ||
3128        ((result & APFloat::opUnderflow) && Val.isZero())) {
3129      unsigned diagnostic;
3130      SmallString<20> buffer;
3131      if (result & APFloat::opOverflow) {
3132        diagnostic = diag::warn_float_overflow;
3133        APFloat::getLargest(Format).toString(buffer);
3134      } else {
3135        diagnostic = diag::warn_float_underflow;
3136        APFloat::getSmallest(Format).toString(buffer);
3137      }
3138  
3139      S.Diag(Loc, diagnostic)
3140        << Ty
3141        << StringRef(buffer.data(), buffer.size());
3142    }
3143  
3144    bool isExact = (result == APFloat::opOK);
3145    return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3146  }
3147  
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3148  bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3149    assert(E && "Invalid expression");
3150  
3151    if (E->isValueDependent())
3152      return false;
3153  
3154    QualType QT = E->getType();
3155    if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3156      Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3157      return true;
3158    }
3159  
3160    llvm::APSInt ValueAPS;
3161    ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3162  
3163    if (R.isInvalid())
3164      return true;
3165  
3166    bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3167    if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3168      Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3169          << ValueAPS.toString(10) << ValueIsPositive;
3170      return true;
3171    }
3172  
3173    return false;
3174  }
3175  
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3176  ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3177    // Fast path for a single digit (which is quite common).  A single digit
3178    // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3179    if (Tok.getLength() == 1) {
3180      const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3181      return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3182    }
3183  
3184    SmallString<128> SpellingBuffer;
3185    // NumericLiteralParser wants to overread by one character.  Add padding to
3186    // the buffer in case the token is copied to the buffer.  If getSpelling()
3187    // returns a StringRef to the memory buffer, it should have a null char at
3188    // the EOF, so it is also safe.
3189    SpellingBuffer.resize(Tok.getLength() + 1);
3190  
3191    // Get the spelling of the token, which eliminates trigraphs, etc.
3192    bool Invalid = false;
3193    StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3194    if (Invalid)
3195      return ExprError();
3196  
3197    NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3198    if (Literal.hadError)
3199      return ExprError();
3200  
3201    if (Literal.hasUDSuffix()) {
3202      // We're building a user-defined literal.
3203      IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3204      SourceLocation UDSuffixLoc =
3205        getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3206  
3207      // Make sure we're allowed user-defined literals here.
3208      if (!UDLScope)
3209        return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3210  
3211      QualType CookedTy;
3212      if (Literal.isFloatingLiteral()) {
3213        // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3214        // long double, the literal is treated as a call of the form
3215        //   operator "" X (f L)
3216        CookedTy = Context.LongDoubleTy;
3217      } else {
3218        // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3219        // unsigned long long, the literal is treated as a call of the form
3220        //   operator "" X (n ULL)
3221        CookedTy = Context.UnsignedLongLongTy;
3222      }
3223  
3224      DeclarationName OpName =
3225        Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3226      DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3227      OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3228  
3229      SourceLocation TokLoc = Tok.getLocation();
3230  
3231      // Perform literal operator lookup to determine if we're building a raw
3232      // literal or a cooked one.
3233      LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3234      switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3235                                    /*AllowRaw*/true, /*AllowTemplate*/true,
3236                                    /*AllowStringTemplate*/false)) {
3237      case LOLR_Error:
3238        return ExprError();
3239  
3240      case LOLR_Cooked: {
3241        Expr *Lit;
3242        if (Literal.isFloatingLiteral()) {
3243          Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3244        } else {
3245          llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3246          if (Literal.GetIntegerValue(ResultVal))
3247            Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3248                << /* Unsigned */ 1;
3249          Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3250                                       Tok.getLocation());
3251        }
3252        return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3253      }
3254  
3255      case LOLR_Raw: {
3256        // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3257        // literal is treated as a call of the form
3258        //   operator "" X ("n")
3259        unsigned Length = Literal.getUDSuffixOffset();
3260        QualType StrTy = Context.getConstantArrayType(
3261            Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3262            ArrayType::Normal, 0);
3263        Expr *Lit = StringLiteral::Create(
3264            Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3265            /*Pascal*/false, StrTy, &TokLoc, 1);
3266        return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3267      }
3268  
3269      case LOLR_Template: {
3270        // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3271        // template), L is treated as a call fo the form
3272        //   operator "" X <'c1', 'c2', ... 'ck'>()
3273        // where n is the source character sequence c1 c2 ... ck.
3274        TemplateArgumentListInfo ExplicitArgs;
3275        unsigned CharBits = Context.getIntWidth(Context.CharTy);
3276        bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3277        llvm::APSInt Value(CharBits, CharIsUnsigned);
3278        for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3279          Value = TokSpelling[I];
3280          TemplateArgument Arg(Context, Value, Context.CharTy);
3281          TemplateArgumentLocInfo ArgInfo;
3282          ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3283        }
3284        return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3285                                        &ExplicitArgs);
3286      }
3287      case LOLR_StringTemplate:
3288        llvm_unreachable("unexpected literal operator lookup result");
3289      }
3290    }
3291  
3292    Expr *Res;
3293  
3294    if (Literal.isFloatingLiteral()) {
3295      QualType Ty;
3296      if (Literal.isFloat)
3297        Ty = Context.FloatTy;
3298      else if (!Literal.isLong)
3299        Ty = Context.DoubleTy;
3300      else
3301        Ty = Context.LongDoubleTy;
3302  
3303      Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3304  
3305      if (Ty == Context.DoubleTy) {
3306        if (getLangOpts().SinglePrecisionConstants) {
3307          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3308        } else if (getLangOpts().OpenCL &&
3309                   !((getLangOpts().OpenCLVersion >= 120) ||
3310                     getOpenCLOptions().cl_khr_fp64)) {
3311          Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3312          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3313        }
3314      }
3315    } else if (!Literal.isIntegerLiteral()) {
3316      return ExprError();
3317    } else {
3318      QualType Ty;
3319  
3320      // 'long long' is a C99 or C++11 feature.
3321      if (!getLangOpts().C99 && Literal.isLongLong) {
3322        if (getLangOpts().CPlusPlus)
3323          Diag(Tok.getLocation(),
3324               getLangOpts().CPlusPlus11 ?
3325               diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3326        else
3327          Diag(Tok.getLocation(), diag::ext_c99_longlong);
3328      }
3329  
3330      // Get the value in the widest-possible width.
3331      unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3332      llvm::APInt ResultVal(MaxWidth, 0);
3333  
3334      if (Literal.GetIntegerValue(ResultVal)) {
3335        // If this value didn't fit into uintmax_t, error and force to ull.
3336        Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3337            << /* Unsigned */ 1;
3338        Ty = Context.UnsignedLongLongTy;
3339        assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3340               "long long is not intmax_t?");
3341      } else {
3342        // If this value fits into a ULL, try to figure out what else it fits into
3343        // according to the rules of C99 6.4.4.1p5.
3344  
3345        // Octal, Hexadecimal, and integers with a U suffix are allowed to
3346        // be an unsigned int.
3347        bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3348  
3349        // Check from smallest to largest, picking the smallest type we can.
3350        unsigned Width = 0;
3351  
3352        // Microsoft specific integer suffixes are explicitly sized.
3353        if (Literal.MicrosoftInteger) {
3354          if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3355            Width = 8;
3356            Ty = Context.CharTy;
3357          } else {
3358            Width = Literal.MicrosoftInteger;
3359            Ty = Context.getIntTypeForBitwidth(Width,
3360                                               /*Signed=*/!Literal.isUnsigned);
3361          }
3362        }
3363  
3364        if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3365          // Are int/unsigned possibilities?
3366          unsigned IntSize = Context.getTargetInfo().getIntWidth();
3367  
3368          // Does it fit in a unsigned int?
3369          if (ResultVal.isIntN(IntSize)) {
3370            // Does it fit in a signed int?
3371            if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3372              Ty = Context.IntTy;
3373            else if (AllowUnsigned)
3374              Ty = Context.UnsignedIntTy;
3375            Width = IntSize;
3376          }
3377        }
3378  
3379        // Are long/unsigned long possibilities?
3380        if (Ty.isNull() && !Literal.isLongLong) {
3381          unsigned LongSize = Context.getTargetInfo().getLongWidth();
3382  
3383          // Does it fit in a unsigned long?
3384          if (ResultVal.isIntN(LongSize)) {
3385            // Does it fit in a signed long?
3386            if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3387              Ty = Context.LongTy;
3388            else if (AllowUnsigned)
3389              Ty = Context.UnsignedLongTy;
3390            // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3391            // is compatible.
3392            else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3393              const unsigned LongLongSize =
3394                  Context.getTargetInfo().getLongLongWidth();
3395              Diag(Tok.getLocation(),
3396                   getLangOpts().CPlusPlus
3397                       ? Literal.isLong
3398                             ? diag::warn_old_implicitly_unsigned_long_cxx
3399                             : /*C++98 UB*/ diag::
3400                                   ext_old_implicitly_unsigned_long_cxx
3401                       : diag::warn_old_implicitly_unsigned_long)
3402                  << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3403                                              : /*will be ill-formed*/ 1);
3404              Ty = Context.UnsignedLongTy;
3405            }
3406            Width = LongSize;
3407          }
3408        }
3409  
3410        // Check long long if needed.
3411        if (Ty.isNull()) {
3412          unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3413  
3414          // Does it fit in a unsigned long long?
3415          if (ResultVal.isIntN(LongLongSize)) {
3416            // Does it fit in a signed long long?
3417            // To be compatible with MSVC, hex integer literals ending with the
3418            // LL or i64 suffix are always signed in Microsoft mode.
3419            if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3420                (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3421              Ty = Context.LongLongTy;
3422            else if (AllowUnsigned)
3423              Ty = Context.UnsignedLongLongTy;
3424            Width = LongLongSize;
3425          }
3426        }
3427  
3428        // If we still couldn't decide a type, we probably have something that
3429        // does not fit in a signed long long, but has no U suffix.
3430        if (Ty.isNull()) {
3431          Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3432          Ty = Context.UnsignedLongLongTy;
3433          Width = Context.getTargetInfo().getLongLongWidth();
3434        }
3435  
3436        if (ResultVal.getBitWidth() != Width)
3437          ResultVal = ResultVal.trunc(Width);
3438      }
3439      Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3440    }
3441  
3442    // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3443    if (Literal.isImaginary)
3444      Res = new (Context) ImaginaryLiteral(Res,
3445                                          Context.getComplexType(Res->getType()));
3446  
3447    return Res;
3448  }
3449  
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3450  ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3451    assert(E && "ActOnParenExpr() missing expr");
3452    return new (Context) ParenExpr(L, R, E);
3453  }
3454  
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3455  static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3456                                           SourceLocation Loc,
3457                                           SourceRange ArgRange) {
3458    // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3459    // scalar or vector data type argument..."
3460    // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3461    // type (C99 6.2.5p18) or void.
3462    if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3463      S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3464        << T << ArgRange;
3465      return true;
3466    }
3467  
3468    assert((T->isVoidType() || !T->isIncompleteType()) &&
3469           "Scalar types should always be complete");
3470    return false;
3471  }
3472  
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3473  static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3474                                             SourceLocation Loc,
3475                                             SourceRange ArgRange,
3476                                             UnaryExprOrTypeTrait TraitKind) {
3477    // Invalid types must be hard errors for SFINAE in C++.
3478    if (S.LangOpts.CPlusPlus)
3479      return true;
3480  
3481    // C99 6.5.3.4p1:
3482    if (T->isFunctionType() &&
3483        (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3484      // sizeof(function)/alignof(function) is allowed as an extension.
3485      S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3486        << TraitKind << ArgRange;
3487      return false;
3488    }
3489  
3490    // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3491    // this is an error (OpenCL v1.1 s6.3.k)
3492    if (T->isVoidType()) {
3493      unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3494                                          : diag::ext_sizeof_alignof_void_type;
3495      S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3496      return false;
3497    }
3498  
3499    return true;
3500  }
3501  
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)3502  static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3503                                               SourceLocation Loc,
3504                                               SourceRange ArgRange,
3505                                               UnaryExprOrTypeTrait TraitKind) {
3506    // Reject sizeof(interface) and sizeof(interface<proto>) if the
3507    // runtime doesn't allow it.
3508    if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3509      S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3510        << T << (TraitKind == UETT_SizeOf)
3511        << ArgRange;
3512      return true;
3513    }
3514  
3515    return false;
3516  }
3517  
3518  /// \brief Check whether E is a pointer from a decayed array type (the decayed
3519  /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)3520  static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3521                                       Expr *E) {
3522    // Don't warn if the operation changed the type.
3523    if (T != E->getType())
3524      return;
3525  
3526    // Now look for array decays.
3527    ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3528    if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3529      return;
3530  
3531    S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3532                                               << ICE->getType()
3533                                               << ICE->getSubExpr()->getType();
3534  }
3535  
3536  /// \brief Check the constraints on expression operands to unary type expression
3537  /// and type traits.
3538  ///
3539  /// Completes any types necessary and validates the constraints on the operand
3540  /// expression. The logic mostly mirrors the type-based overload, but may modify
3541  /// the expression as it completes the type for that expression through template
3542  /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)3543  bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3544                                              UnaryExprOrTypeTrait ExprKind) {
3545    QualType ExprTy = E->getType();
3546    assert(!ExprTy->isReferenceType());
3547  
3548    if (ExprKind == UETT_VecStep)
3549      return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3550                                          E->getSourceRange());
3551  
3552    // Whitelist some types as extensions
3553    if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3554                                        E->getSourceRange(), ExprKind))
3555      return false;
3556  
3557    // 'alignof' applied to an expression only requires the base element type of
3558    // the expression to be complete. 'sizeof' requires the expression's type to
3559    // be complete (and will attempt to complete it if it's an array of unknown
3560    // bound).
3561    if (ExprKind == UETT_AlignOf) {
3562      if (RequireCompleteType(E->getExprLoc(),
3563                              Context.getBaseElementType(E->getType()),
3564                              diag::err_sizeof_alignof_incomplete_type, ExprKind,
3565                              E->getSourceRange()))
3566        return true;
3567    } else {
3568      if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3569                                  ExprKind, E->getSourceRange()))
3570        return true;
3571    }
3572  
3573    // Completing the expression's type may have changed it.
3574    ExprTy = E->getType();
3575    assert(!ExprTy->isReferenceType());
3576  
3577    if (ExprTy->isFunctionType()) {
3578      Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3579        << ExprKind << E->getSourceRange();
3580      return true;
3581    }
3582  
3583    // The operand for sizeof and alignof is in an unevaluated expression context,
3584    // so side effects could result in unintended consequences.
3585    if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3586        ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3587      Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3588  
3589    if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3590                                         E->getSourceRange(), ExprKind))
3591      return true;
3592  
3593    if (ExprKind == UETT_SizeOf) {
3594      if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3595        if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3596          QualType OType = PVD->getOriginalType();
3597          QualType Type = PVD->getType();
3598          if (Type->isPointerType() && OType->isArrayType()) {
3599            Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3600              << Type << OType;
3601            Diag(PVD->getLocation(), diag::note_declared_at);
3602          }
3603        }
3604      }
3605  
3606      // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3607      // decays into a pointer and returns an unintended result. This is most
3608      // likely a typo for "sizeof(array) op x".
3609      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3610        warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3611                                 BO->getLHS());
3612        warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3613                                 BO->getRHS());
3614      }
3615    }
3616  
3617    return false;
3618  }
3619  
3620  /// \brief Check the constraints on operands to unary expression and type
3621  /// traits.
3622  ///
3623  /// This will complete any types necessary, and validate the various constraints
3624  /// on those operands.
3625  ///
3626  /// The UsualUnaryConversions() function is *not* called by this routine.
3627  /// C99 6.3.2.1p[2-4] all state:
3628  ///   Except when it is the operand of the sizeof operator ...
3629  ///
3630  /// C++ [expr.sizeof]p4
3631  ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3632  ///   standard conversions are not applied to the operand of sizeof.
3633  ///
3634  /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)3635  bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3636                                              SourceLocation OpLoc,
3637                                              SourceRange ExprRange,
3638                                              UnaryExprOrTypeTrait ExprKind) {
3639    if (ExprType->isDependentType())
3640      return false;
3641  
3642    // C++ [expr.sizeof]p2:
3643    //     When applied to a reference or a reference type, the result
3644    //     is the size of the referenced type.
3645    // C++11 [expr.alignof]p3:
3646    //     When alignof is applied to a reference type, the result
3647    //     shall be the alignment of the referenced type.
3648    if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3649      ExprType = Ref->getPointeeType();
3650  
3651    // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3652    //   When alignof or _Alignof is applied to an array type, the result
3653    //   is the alignment of the element type.
3654    if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3655      ExprType = Context.getBaseElementType(ExprType);
3656  
3657    if (ExprKind == UETT_VecStep)
3658      return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3659  
3660    // Whitelist some types as extensions
3661    if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3662                                        ExprKind))
3663      return false;
3664  
3665    if (RequireCompleteType(OpLoc, ExprType,
3666                            diag::err_sizeof_alignof_incomplete_type,
3667                            ExprKind, ExprRange))
3668      return true;
3669  
3670    if (ExprType->isFunctionType()) {
3671      Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3672        << ExprKind << ExprRange;
3673      return true;
3674    }
3675  
3676    if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3677                                         ExprKind))
3678      return true;
3679  
3680    return false;
3681  }
3682  
CheckAlignOfExpr(Sema & S,Expr * E)3683  static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3684    E = E->IgnoreParens();
3685  
3686    // Cannot know anything else if the expression is dependent.
3687    if (E->isTypeDependent())
3688      return false;
3689  
3690    if (E->getObjectKind() == OK_BitField) {
3691      S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3692         << 1 << E->getSourceRange();
3693      return true;
3694    }
3695  
3696    ValueDecl *D = nullptr;
3697    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3698      D = DRE->getDecl();
3699    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3700      D = ME->getMemberDecl();
3701    }
3702  
3703    // If it's a field, require the containing struct to have a
3704    // complete definition so that we can compute the layout.
3705    //
3706    // This can happen in C++11 onwards, either by naming the member
3707    // in a way that is not transformed into a member access expression
3708    // (in an unevaluated operand, for instance), or by naming the member
3709    // in a trailing-return-type.
3710    //
3711    // For the record, since __alignof__ on expressions is a GCC
3712    // extension, GCC seems to permit this but always gives the
3713    // nonsensical answer 0.
3714    //
3715    // We don't really need the layout here --- we could instead just
3716    // directly check for all the appropriate alignment-lowing
3717    // attributes --- but that would require duplicating a lot of
3718    // logic that just isn't worth duplicating for such a marginal
3719    // use-case.
3720    if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3721      // Fast path this check, since we at least know the record has a
3722      // definition if we can find a member of it.
3723      if (!FD->getParent()->isCompleteDefinition()) {
3724        S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3725          << E->getSourceRange();
3726        return true;
3727      }
3728  
3729      // Otherwise, if it's a field, and the field doesn't have
3730      // reference type, then it must have a complete type (or be a
3731      // flexible array member, which we explicitly want to
3732      // white-list anyway), which makes the following checks trivial.
3733      if (!FD->getType()->isReferenceType())
3734        return false;
3735    }
3736  
3737    return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3738  }
3739  
CheckVecStepExpr(Expr * E)3740  bool Sema::CheckVecStepExpr(Expr *E) {
3741    E = E->IgnoreParens();
3742  
3743    // Cannot know anything else if the expression is dependent.
3744    if (E->isTypeDependent())
3745      return false;
3746  
3747    return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3748  }
3749  
3750  /// \brief Build a sizeof or alignof expression given a type operand.
3751  ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)3752  Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3753                                       SourceLocation OpLoc,
3754                                       UnaryExprOrTypeTrait ExprKind,
3755                                       SourceRange R) {
3756    if (!TInfo)
3757      return ExprError();
3758  
3759    QualType T = TInfo->getType();
3760  
3761    if (!T->isDependentType() &&
3762        CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3763      return ExprError();
3764  
3765    // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3766    return new (Context) UnaryExprOrTypeTraitExpr(
3767        ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3768  }
3769  
3770  /// \brief Build a sizeof or alignof expression given an expression
3771  /// operand.
3772  ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)3773  Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3774                                       UnaryExprOrTypeTrait ExprKind) {
3775    ExprResult PE = CheckPlaceholderExpr(E);
3776    if (PE.isInvalid())
3777      return ExprError();
3778  
3779    E = PE.get();
3780  
3781    // Verify that the operand is valid.
3782    bool isInvalid = false;
3783    if (E->isTypeDependent()) {
3784      // Delay type-checking for type-dependent expressions.
3785    } else if (ExprKind == UETT_AlignOf) {
3786      isInvalid = CheckAlignOfExpr(*this, E);
3787    } else if (ExprKind == UETT_VecStep) {
3788      isInvalid = CheckVecStepExpr(E);
3789    } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3790        Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3791        isInvalid = true;
3792    } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3793      Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3794      isInvalid = true;
3795    } else {
3796      isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3797    }
3798  
3799    if (isInvalid)
3800      return ExprError();
3801  
3802    if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3803      PE = TransformToPotentiallyEvaluated(E);
3804      if (PE.isInvalid()) return ExprError();
3805      E = PE.get();
3806    }
3807  
3808    // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3809    return new (Context) UnaryExprOrTypeTraitExpr(
3810        ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3811  }
3812  
3813  /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3814  /// expr and the same for @c alignof and @c __alignof
3815  /// Note that the ArgRange is invalid if isType is false.
3816  ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)3817  Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3818                                      UnaryExprOrTypeTrait ExprKind, bool IsType,
3819                                      void *TyOrEx, SourceRange ArgRange) {
3820    // If error parsing type, ignore.
3821    if (!TyOrEx) return ExprError();
3822  
3823    if (IsType) {
3824      TypeSourceInfo *TInfo;
3825      (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3826      return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3827    }
3828  
3829    Expr *ArgEx = (Expr *)TyOrEx;
3830    ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3831    return Result;
3832  }
3833  
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)3834  static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3835                                       bool IsReal) {
3836    if (V.get()->isTypeDependent())
3837      return S.Context.DependentTy;
3838  
3839    // _Real and _Imag are only l-values for normal l-values.
3840    if (V.get()->getObjectKind() != OK_Ordinary) {
3841      V = S.DefaultLvalueConversion(V.get());
3842      if (V.isInvalid())
3843        return QualType();
3844    }
3845  
3846    // These operators return the element type of a complex type.
3847    if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3848      return CT->getElementType();
3849  
3850    // Otherwise they pass through real integer and floating point types here.
3851    if (V.get()->getType()->isArithmeticType())
3852      return V.get()->getType();
3853  
3854    // Test for placeholders.
3855    ExprResult PR = S.CheckPlaceholderExpr(V.get());
3856    if (PR.isInvalid()) return QualType();
3857    if (PR.get() != V.get()) {
3858      V = PR;
3859      return CheckRealImagOperand(S, V, Loc, IsReal);
3860    }
3861  
3862    // Reject anything else.
3863    S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3864      << (IsReal ? "__real" : "__imag");
3865    return QualType();
3866  }
3867  
3868  
3869  
3870  ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)3871  Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3872                            tok::TokenKind Kind, Expr *Input) {
3873    UnaryOperatorKind Opc;
3874    switch (Kind) {
3875    default: llvm_unreachable("Unknown unary op!");
3876    case tok::plusplus:   Opc = UO_PostInc; break;
3877    case tok::minusminus: Opc = UO_PostDec; break;
3878    }
3879  
3880    // Since this might is a postfix expression, get rid of ParenListExprs.
3881    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3882    if (Result.isInvalid()) return ExprError();
3883    Input = Result.get();
3884  
3885    return BuildUnaryOp(S, OpLoc, Opc, Input);
3886  }
3887  
3888  /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3889  ///
3890  /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)3891  static bool checkArithmeticOnObjCPointer(Sema &S,
3892                                           SourceLocation opLoc,
3893                                           Expr *op) {
3894    assert(op->getType()->isObjCObjectPointerType());
3895    if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3896        !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3897      return false;
3898  
3899    S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3900      << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3901      << op->getSourceRange();
3902    return true;
3903  }
3904  
isMSPropertySubscriptExpr(Sema & S,Expr * Base)3905  static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
3906    auto *BaseNoParens = Base->IgnoreParens();
3907    if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
3908      return MSProp->getPropertyDecl()->getType()->isArrayType();
3909    return isa<MSPropertySubscriptExpr>(BaseNoParens);
3910  }
3911  
3912  ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)3913  Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3914                                Expr *idx, SourceLocation rbLoc) {
3915    if (base && !base->getType().isNull() &&
3916        base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
3917      return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
3918                                      /*Length=*/nullptr, rbLoc);
3919  
3920    // Since this might be a postfix expression, get rid of ParenListExprs.
3921    if (isa<ParenListExpr>(base)) {
3922      ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3923      if (result.isInvalid()) return ExprError();
3924      base = result.get();
3925    }
3926  
3927    // Handle any non-overload placeholder types in the base and index
3928    // expressions.  We can't handle overloads here because the other
3929    // operand might be an overloadable type, in which case the overload
3930    // resolution for the operator overload should get the first crack
3931    // at the overload.
3932    bool IsMSPropertySubscript = false;
3933    if (base->getType()->isNonOverloadPlaceholderType()) {
3934      IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
3935      if (!IsMSPropertySubscript) {
3936        ExprResult result = CheckPlaceholderExpr(base);
3937        if (result.isInvalid())
3938          return ExprError();
3939        base = result.get();
3940      }
3941    }
3942    if (idx->getType()->isNonOverloadPlaceholderType()) {
3943      ExprResult result = CheckPlaceholderExpr(idx);
3944      if (result.isInvalid()) return ExprError();
3945      idx = result.get();
3946    }
3947  
3948    // Build an unanalyzed expression if either operand is type-dependent.
3949    if (getLangOpts().CPlusPlus &&
3950        (base->isTypeDependent() || idx->isTypeDependent())) {
3951      return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3952                                              VK_LValue, OK_Ordinary, rbLoc);
3953    }
3954  
3955    // MSDN, property (C++)
3956    // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
3957    // This attribute can also be used in the declaration of an empty array in a
3958    // class or structure definition. For example:
3959    // __declspec(property(get=GetX, put=PutX)) int x[];
3960    // The above statement indicates that x[] can be used with one or more array
3961    // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
3962    // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
3963    if (IsMSPropertySubscript) {
3964      // Build MS property subscript expression if base is MS property reference
3965      // or MS property subscript.
3966      return new (Context) MSPropertySubscriptExpr(
3967          base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
3968    }
3969  
3970    // Use C++ overloaded-operator rules if either operand has record
3971    // type.  The spec says to do this if either type is *overloadable*,
3972    // but enum types can't declare subscript operators or conversion
3973    // operators, so there's nothing interesting for overload resolution
3974    // to do if there aren't any record types involved.
3975    //
3976    // ObjC pointers have their own subscripting logic that is not tied
3977    // to overload resolution and so should not take this path.
3978    if (getLangOpts().CPlusPlus &&
3979        (base->getType()->isRecordType() ||
3980         (!base->getType()->isObjCObjectPointerType() &&
3981          idx->getType()->isRecordType()))) {
3982      return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3983    }
3984  
3985    return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3986  }
3987  
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLoc,Expr * Length,SourceLocation RBLoc)3988  ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3989                                            Expr *LowerBound,
3990                                            SourceLocation ColonLoc, Expr *Length,
3991                                            SourceLocation RBLoc) {
3992    if (Base->getType()->isPlaceholderType() &&
3993        !Base->getType()->isSpecificPlaceholderType(
3994            BuiltinType::OMPArraySection)) {
3995      ExprResult Result = CheckPlaceholderExpr(Base);
3996      if (Result.isInvalid())
3997        return ExprError();
3998      Base = Result.get();
3999    }
4000    if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4001      ExprResult Result = CheckPlaceholderExpr(LowerBound);
4002      if (Result.isInvalid())
4003        return ExprError();
4004      LowerBound = Result.get();
4005    }
4006    if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4007      ExprResult Result = CheckPlaceholderExpr(Length);
4008      if (Result.isInvalid())
4009        return ExprError();
4010      Length = Result.get();
4011    }
4012  
4013    // Build an unanalyzed expression if either operand is type-dependent.
4014    if (Base->isTypeDependent() ||
4015        (LowerBound &&
4016         (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4017        (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4018      return new (Context)
4019          OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4020                              VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4021    }
4022  
4023    // Perform default conversions.
4024    QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4025    QualType ResultTy;
4026    if (OriginalTy->isAnyPointerType()) {
4027      ResultTy = OriginalTy->getPointeeType();
4028    } else if (OriginalTy->isArrayType()) {
4029      ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4030    } else {
4031      return ExprError(
4032          Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4033          << Base->getSourceRange());
4034    }
4035    // C99 6.5.2.1p1
4036    if (LowerBound) {
4037      auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4038                                                        LowerBound);
4039      if (Res.isInvalid())
4040        return ExprError(Diag(LowerBound->getExprLoc(),
4041                              diag::err_omp_typecheck_section_not_integer)
4042                         << 0 << LowerBound->getSourceRange());
4043      LowerBound = Res.get();
4044  
4045      if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4046          LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4047        Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4048            << 0 << LowerBound->getSourceRange();
4049    }
4050    if (Length) {
4051      auto Res =
4052          PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4053      if (Res.isInvalid())
4054        return ExprError(Diag(Length->getExprLoc(),
4055                              diag::err_omp_typecheck_section_not_integer)
4056                         << 1 << Length->getSourceRange());
4057      Length = Res.get();
4058  
4059      if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4060          Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4061        Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4062            << 1 << Length->getSourceRange();
4063    }
4064  
4065    // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4066    // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4067    // type. Note that functions are not objects, and that (in C99 parlance)
4068    // incomplete types are not object types.
4069    if (ResultTy->isFunctionType()) {
4070      Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4071          << ResultTy << Base->getSourceRange();
4072      return ExprError();
4073    }
4074  
4075    if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4076                            diag::err_omp_section_incomplete_type, Base))
4077      return ExprError();
4078  
4079    if (LowerBound) {
4080      llvm::APSInt LowerBoundValue;
4081      if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4082        // OpenMP 4.0, [2.4 Array Sections]
4083        // The lower-bound and length must evaluate to non-negative integers.
4084        if (LowerBoundValue.isNegative()) {
4085          Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4086              << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4087              << LowerBound->getSourceRange();
4088          return ExprError();
4089        }
4090      }
4091    }
4092  
4093    if (Length) {
4094      llvm::APSInt LengthValue;
4095      if (Length->EvaluateAsInt(LengthValue, Context)) {
4096        // OpenMP 4.0, [2.4 Array Sections]
4097        // The lower-bound and length must evaluate to non-negative integers.
4098        if (LengthValue.isNegative()) {
4099          Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4100              << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4101              << Length->getSourceRange();
4102          return ExprError();
4103        }
4104      }
4105    } else if (ColonLoc.isValid() &&
4106               (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4107                                        !OriginalTy->isVariableArrayType()))) {
4108      // OpenMP 4.0, [2.4 Array Sections]
4109      // When the size of the array dimension is not known, the length must be
4110      // specified explicitly.
4111      Diag(ColonLoc, diag::err_omp_section_length_undefined)
4112          << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4113      return ExprError();
4114    }
4115  
4116    return new (Context)
4117        OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4118                            VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4119  }
4120  
4121  ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)4122  Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4123                                        Expr *Idx, SourceLocation RLoc) {
4124    Expr *LHSExp = Base;
4125    Expr *RHSExp = Idx;
4126  
4127    // Perform default conversions.
4128    if (!LHSExp->getType()->getAs<VectorType>()) {
4129      ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4130      if (Result.isInvalid())
4131        return ExprError();
4132      LHSExp = Result.get();
4133    }
4134    ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4135    if (Result.isInvalid())
4136      return ExprError();
4137    RHSExp = Result.get();
4138  
4139    QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4140    ExprValueKind VK = VK_LValue;
4141    ExprObjectKind OK = OK_Ordinary;
4142  
4143    // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4144    // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4145    // in the subscript position. As a result, we need to derive the array base
4146    // and index from the expression types.
4147    Expr *BaseExpr, *IndexExpr;
4148    QualType ResultType;
4149    if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4150      BaseExpr = LHSExp;
4151      IndexExpr = RHSExp;
4152      ResultType = Context.DependentTy;
4153    } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4154      BaseExpr = LHSExp;
4155      IndexExpr = RHSExp;
4156      ResultType = PTy->getPointeeType();
4157    } else if (const ObjCObjectPointerType *PTy =
4158                 LHSTy->getAs<ObjCObjectPointerType>()) {
4159      BaseExpr = LHSExp;
4160      IndexExpr = RHSExp;
4161  
4162      // Use custom logic if this should be the pseudo-object subscript
4163      // expression.
4164      if (!LangOpts.isSubscriptPointerArithmetic())
4165        return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4166                                            nullptr);
4167  
4168      ResultType = PTy->getPointeeType();
4169    } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4170       // Handle the uncommon case of "123[Ptr]".
4171      BaseExpr = RHSExp;
4172      IndexExpr = LHSExp;
4173      ResultType = PTy->getPointeeType();
4174    } else if (const ObjCObjectPointerType *PTy =
4175                 RHSTy->getAs<ObjCObjectPointerType>()) {
4176       // Handle the uncommon case of "123[Ptr]".
4177      BaseExpr = RHSExp;
4178      IndexExpr = LHSExp;
4179      ResultType = PTy->getPointeeType();
4180      if (!LangOpts.isSubscriptPointerArithmetic()) {
4181        Diag(LLoc, diag::err_subscript_nonfragile_interface)
4182          << ResultType << BaseExpr->getSourceRange();
4183        return ExprError();
4184      }
4185    } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4186      BaseExpr = LHSExp;    // vectors: V[123]
4187      IndexExpr = RHSExp;
4188      VK = LHSExp->getValueKind();
4189      if (VK != VK_RValue)
4190        OK = OK_VectorComponent;
4191  
4192      // FIXME: need to deal with const...
4193      ResultType = VTy->getElementType();
4194    } else if (LHSTy->isArrayType()) {
4195      // If we see an array that wasn't promoted by
4196      // DefaultFunctionArrayLvalueConversion, it must be an array that
4197      // wasn't promoted because of the C90 rule that doesn't
4198      // allow promoting non-lvalue arrays.  Warn, then
4199      // force the promotion here.
4200      Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4201          LHSExp->getSourceRange();
4202      LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4203                                 CK_ArrayToPointerDecay).get();
4204      LHSTy = LHSExp->getType();
4205  
4206      BaseExpr = LHSExp;
4207      IndexExpr = RHSExp;
4208      ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4209    } else if (RHSTy->isArrayType()) {
4210      // Same as previous, except for 123[f().a] case
4211      Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4212          RHSExp->getSourceRange();
4213      RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4214                                 CK_ArrayToPointerDecay).get();
4215      RHSTy = RHSExp->getType();
4216  
4217      BaseExpr = RHSExp;
4218      IndexExpr = LHSExp;
4219      ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4220    } else {
4221      return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4222         << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4223    }
4224    // C99 6.5.2.1p1
4225    if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4226      return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4227                       << IndexExpr->getSourceRange());
4228  
4229    if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4230         IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4231           && !IndexExpr->isTypeDependent())
4232      Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4233  
4234    // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4235    // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4236    // type. Note that Functions are not objects, and that (in C99 parlance)
4237    // incomplete types are not object types.
4238    if (ResultType->isFunctionType()) {
4239      Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4240        << ResultType << BaseExpr->getSourceRange();
4241      return ExprError();
4242    }
4243  
4244    if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4245      // GNU extension: subscripting on pointer to void
4246      Diag(LLoc, diag::ext_gnu_subscript_void_type)
4247        << BaseExpr->getSourceRange();
4248  
4249      // C forbids expressions of unqualified void type from being l-values.
4250      // See IsCForbiddenLValueType.
4251      if (!ResultType.hasQualifiers()) VK = VK_RValue;
4252    } else if (!ResultType->isDependentType() &&
4253        RequireCompleteType(LLoc, ResultType,
4254                            diag::err_subscript_incomplete_type, BaseExpr))
4255      return ExprError();
4256  
4257    assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4258           !ResultType.isCForbiddenLValueType());
4259  
4260    return new (Context)
4261        ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4262  }
4263  
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)4264  ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4265                                          FunctionDecl *FD,
4266                                          ParmVarDecl *Param) {
4267    if (Param->hasUnparsedDefaultArg()) {
4268      Diag(CallLoc,
4269           diag::err_use_of_default_argument_to_function_declared_later) <<
4270        FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4271      Diag(UnparsedDefaultArgLocs[Param],
4272           diag::note_default_argument_declared_here);
4273      return ExprError();
4274    }
4275  
4276    if (Param->hasUninstantiatedDefaultArg()) {
4277      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4278  
4279      EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4280                                                   Param);
4281  
4282      // Instantiate the expression.
4283      MultiLevelTemplateArgumentList MutiLevelArgList
4284        = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4285  
4286      InstantiatingTemplate Inst(*this, CallLoc, Param,
4287                                 MutiLevelArgList.getInnermost());
4288      if (Inst.isInvalid())
4289        return ExprError();
4290  
4291      ExprResult Result;
4292      {
4293        // C++ [dcl.fct.default]p5:
4294        //   The names in the [default argument] expression are bound, and
4295        //   the semantic constraints are checked, at the point where the
4296        //   default argument expression appears.
4297        ContextRAII SavedContext(*this, FD);
4298        LocalInstantiationScope Local(*this);
4299        Result = SubstExpr(UninstExpr, MutiLevelArgList);
4300      }
4301      if (Result.isInvalid())
4302        return ExprError();
4303  
4304      // Check the expression as an initializer for the parameter.
4305      InitializedEntity Entity
4306        = InitializedEntity::InitializeParameter(Context, Param);
4307      InitializationKind Kind
4308        = InitializationKind::CreateCopy(Param->getLocation(),
4309               /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4310      Expr *ResultE = Result.getAs<Expr>();
4311  
4312      InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4313      Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4314      if (Result.isInvalid())
4315        return ExprError();
4316  
4317      Expr *Arg = Result.getAs<Expr>();
4318      CheckCompletedExpr(Arg, Param->getOuterLocStart());
4319      // Build the default argument expression.
4320      return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4321    }
4322  
4323    // If the default expression creates temporaries, we need to
4324    // push them to the current stack of expression temporaries so they'll
4325    // be properly destroyed.
4326    // FIXME: We should really be rebuilding the default argument with new
4327    // bound temporaries; see the comment in PR5810.
4328    // We don't need to do that with block decls, though, because
4329    // blocks in default argument expression can never capture anything.
4330    if (isa<ExprWithCleanups>(Param->getInit())) {
4331      // Set the "needs cleanups" bit regardless of whether there are
4332      // any explicit objects.
4333      ExprNeedsCleanups = true;
4334  
4335      // Append all the objects to the cleanup list.  Right now, this
4336      // should always be a no-op, because blocks in default argument
4337      // expressions should never be able to capture anything.
4338      assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4339             "default argument expression has capturing blocks?");
4340    }
4341  
4342    // We already type-checked the argument, so we know it works.
4343    // Just mark all of the declarations in this potentially-evaluated expression
4344    // as being "referenced".
4345    MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4346                                     /*SkipLocalVariables=*/true);
4347    return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4348  }
4349  
4350  
4351  Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)4352  Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4353                            Expr *Fn) {
4354    if (Proto && Proto->isVariadic()) {
4355      if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4356        return VariadicConstructor;
4357      else if (Fn && Fn->getType()->isBlockPointerType())
4358        return VariadicBlock;
4359      else if (FDecl) {
4360        if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4361          if (Method->isInstance())
4362            return VariadicMethod;
4363      } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4364        return VariadicMethod;
4365      return VariadicFunction;
4366    }
4367    return VariadicDoesNotApply;
4368  }
4369  
4370  namespace {
4371  class FunctionCallCCC : public FunctionCallFilterCCC {
4372  public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)4373    FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4374                    unsigned NumArgs, MemberExpr *ME)
4375        : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4376          FunctionName(FuncName) {}
4377  
ValidateCandidate(const TypoCorrection & candidate)4378    bool ValidateCandidate(const TypoCorrection &candidate) override {
4379      if (!candidate.getCorrectionSpecifier() ||
4380          candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4381        return false;
4382      }
4383  
4384      return FunctionCallFilterCCC::ValidateCandidate(candidate);
4385    }
4386  
4387  private:
4388    const IdentifierInfo *const FunctionName;
4389  };
4390  }
4391  
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)4392  static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4393                                                 FunctionDecl *FDecl,
4394                                                 ArrayRef<Expr *> Args) {
4395    MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4396    DeclarationName FuncName = FDecl->getDeclName();
4397    SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4398  
4399    if (TypoCorrection Corrected = S.CorrectTypo(
4400            DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4401            S.getScopeForContext(S.CurContext), nullptr,
4402            llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4403                                               Args.size(), ME),
4404            Sema::CTK_ErrorRecovery)) {
4405      if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4406        if (Corrected.isOverloaded()) {
4407          OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4408          OverloadCandidateSet::iterator Best;
4409          for (NamedDecl *CD : Corrected) {
4410            if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4411              S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4412                                     OCS);
4413          }
4414          switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4415          case OR_Success:
4416            ND = Best->Function;
4417            Corrected.setCorrectionDecl(ND);
4418            break;
4419          default:
4420            break;
4421          }
4422        }
4423        if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4424          return Corrected;
4425        }
4426      }
4427    }
4428    return TypoCorrection();
4429  }
4430  
4431  /// ConvertArgumentsForCall - Converts the arguments specified in
4432  /// Args/NumArgs to the parameter types of the function FDecl with
4433  /// function prototype Proto. Call is the call expression itself, and
4434  /// Fn is the function expression. For a C++ member function, this
4435  /// routine does not attempt to convert the object argument. Returns
4436  /// true if the call is ill-formed.
4437  bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)4438  Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4439                                FunctionDecl *FDecl,
4440                                const FunctionProtoType *Proto,
4441                                ArrayRef<Expr *> Args,
4442                                SourceLocation RParenLoc,
4443                                bool IsExecConfig) {
4444    // Bail out early if calling a builtin with custom typechecking.
4445    if (FDecl)
4446      if (unsigned ID = FDecl->getBuiltinID())
4447        if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4448          return false;
4449  
4450    // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4451    // assignment, to the types of the corresponding parameter, ...
4452    unsigned NumParams = Proto->getNumParams();
4453    bool Invalid = false;
4454    unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4455    unsigned FnKind = Fn->getType()->isBlockPointerType()
4456                         ? 1 /* block */
4457                         : (IsExecConfig ? 3 /* kernel function (exec config) */
4458                                         : 0 /* function */);
4459  
4460    // If too few arguments are available (and we don't have default
4461    // arguments for the remaining parameters), don't make the call.
4462    if (Args.size() < NumParams) {
4463      if (Args.size() < MinArgs) {
4464        TypoCorrection TC;
4465        if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4466          unsigned diag_id =
4467              MinArgs == NumParams && !Proto->isVariadic()
4468                  ? diag::err_typecheck_call_too_few_args_suggest
4469                  : diag::err_typecheck_call_too_few_args_at_least_suggest;
4470          diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4471                                          << static_cast<unsigned>(Args.size())
4472                                          << TC.getCorrectionRange());
4473        } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4474          Diag(RParenLoc,
4475               MinArgs == NumParams && !Proto->isVariadic()
4476                   ? diag::err_typecheck_call_too_few_args_one
4477                   : diag::err_typecheck_call_too_few_args_at_least_one)
4478              << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4479        else
4480          Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4481                              ? diag::err_typecheck_call_too_few_args
4482                              : diag::err_typecheck_call_too_few_args_at_least)
4483              << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4484              << Fn->getSourceRange();
4485  
4486        // Emit the location of the prototype.
4487        if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4488          Diag(FDecl->getLocStart(), diag::note_callee_decl)
4489            << FDecl;
4490  
4491        return true;
4492      }
4493      Call->setNumArgs(Context, NumParams);
4494    }
4495  
4496    // If too many are passed and not variadic, error on the extras and drop
4497    // them.
4498    if (Args.size() > NumParams) {
4499      if (!Proto->isVariadic()) {
4500        TypoCorrection TC;
4501        if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4502          unsigned diag_id =
4503              MinArgs == NumParams && !Proto->isVariadic()
4504                  ? diag::err_typecheck_call_too_many_args_suggest
4505                  : diag::err_typecheck_call_too_many_args_at_most_suggest;
4506          diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4507                                          << static_cast<unsigned>(Args.size())
4508                                          << TC.getCorrectionRange());
4509        } else if (NumParams == 1 && FDecl &&
4510                   FDecl->getParamDecl(0)->getDeclName())
4511          Diag(Args[NumParams]->getLocStart(),
4512               MinArgs == NumParams
4513                   ? diag::err_typecheck_call_too_many_args_one
4514                   : diag::err_typecheck_call_too_many_args_at_most_one)
4515              << FnKind << FDecl->getParamDecl(0)
4516              << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4517              << SourceRange(Args[NumParams]->getLocStart(),
4518                             Args.back()->getLocEnd());
4519        else
4520          Diag(Args[NumParams]->getLocStart(),
4521               MinArgs == NumParams
4522                   ? diag::err_typecheck_call_too_many_args
4523                   : diag::err_typecheck_call_too_many_args_at_most)
4524              << FnKind << NumParams << static_cast<unsigned>(Args.size())
4525              << Fn->getSourceRange()
4526              << SourceRange(Args[NumParams]->getLocStart(),
4527                             Args.back()->getLocEnd());
4528  
4529        // Emit the location of the prototype.
4530        if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4531          Diag(FDecl->getLocStart(), diag::note_callee_decl)
4532            << FDecl;
4533  
4534        // This deletes the extra arguments.
4535        Call->setNumArgs(Context, NumParams);
4536        return true;
4537      }
4538    }
4539    SmallVector<Expr *, 8> AllArgs;
4540    VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4541  
4542    Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4543                                     Proto, 0, Args, AllArgs, CallType);
4544    if (Invalid)
4545      return true;
4546    unsigned TotalNumArgs = AllArgs.size();
4547    for (unsigned i = 0; i < TotalNumArgs; ++i)
4548      Call->setArg(i, AllArgs[i]);
4549  
4550    return false;
4551  }
4552  
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)4553  bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4554                                    const FunctionProtoType *Proto,
4555                                    unsigned FirstParam, ArrayRef<Expr *> Args,
4556                                    SmallVectorImpl<Expr *> &AllArgs,
4557                                    VariadicCallType CallType, bool AllowExplicit,
4558                                    bool IsListInitialization) {
4559    unsigned NumParams = Proto->getNumParams();
4560    bool Invalid = false;
4561    size_t ArgIx = 0;
4562    // Continue to check argument types (even if we have too few/many args).
4563    for (unsigned i = FirstParam; i < NumParams; i++) {
4564      QualType ProtoArgType = Proto->getParamType(i);
4565  
4566      Expr *Arg;
4567      ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4568      if (ArgIx < Args.size()) {
4569        Arg = Args[ArgIx++];
4570  
4571        if (RequireCompleteType(Arg->getLocStart(),
4572                                ProtoArgType,
4573                                diag::err_call_incomplete_argument, Arg))
4574          return true;
4575  
4576        // Strip the unbridged-cast placeholder expression off, if applicable.
4577        bool CFAudited = false;
4578        if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4579            FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4580            (!Param || !Param->hasAttr<CFConsumedAttr>()))
4581          Arg = stripARCUnbridgedCast(Arg);
4582        else if (getLangOpts().ObjCAutoRefCount &&
4583                 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4584                 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4585          CFAudited = true;
4586  
4587        InitializedEntity Entity =
4588            Param ? InitializedEntity::InitializeParameter(Context, Param,
4589                                                           ProtoArgType)
4590                  : InitializedEntity::InitializeParameter(
4591                        Context, ProtoArgType, Proto->isParamConsumed(i));
4592  
4593        // Remember that parameter belongs to a CF audited API.
4594        if (CFAudited)
4595          Entity.setParameterCFAudited();
4596  
4597        ExprResult ArgE = PerformCopyInitialization(
4598            Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4599        if (ArgE.isInvalid())
4600          return true;
4601  
4602        Arg = ArgE.getAs<Expr>();
4603      } else {
4604        assert(Param && "can't use default arguments without a known callee");
4605  
4606        ExprResult ArgExpr =
4607          BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4608        if (ArgExpr.isInvalid())
4609          return true;
4610  
4611        Arg = ArgExpr.getAs<Expr>();
4612      }
4613  
4614      // Check for array bounds violations for each argument to the call. This
4615      // check only triggers warnings when the argument isn't a more complex Expr
4616      // with its own checking, such as a BinaryOperator.
4617      CheckArrayAccess(Arg);
4618  
4619      // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4620      CheckStaticArrayArgument(CallLoc, Param, Arg);
4621  
4622      AllArgs.push_back(Arg);
4623    }
4624  
4625    // If this is a variadic call, handle args passed through "...".
4626    if (CallType != VariadicDoesNotApply) {
4627      // Assume that extern "C" functions with variadic arguments that
4628      // return __unknown_anytype aren't *really* variadic.
4629      if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4630          FDecl->isExternC()) {
4631        for (Expr *A : Args.slice(ArgIx)) {
4632          QualType paramType; // ignored
4633          ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4634          Invalid |= arg.isInvalid();
4635          AllArgs.push_back(arg.get());
4636        }
4637  
4638      // Otherwise do argument promotion, (C99 6.5.2.2p7).
4639      } else {
4640        for (Expr *A : Args.slice(ArgIx)) {
4641          ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4642          Invalid |= Arg.isInvalid();
4643          AllArgs.push_back(Arg.get());
4644        }
4645      }
4646  
4647      // Check for array bounds violations.
4648      for (Expr *A : Args.slice(ArgIx))
4649        CheckArrayAccess(A);
4650    }
4651    return Invalid;
4652  }
4653  
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)4654  static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4655    TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4656    if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4657      TL = DTL.getOriginalLoc();
4658    if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4659      S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4660        << ATL.getLocalSourceRange();
4661  }
4662  
4663  /// CheckStaticArrayArgument - If the given argument corresponds to a static
4664  /// array parameter, check that it is non-null, and that if it is formed by
4665  /// array-to-pointer decay, the underlying array is sufficiently large.
4666  ///
4667  /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4668  /// array type derivation, then for each call to the function, the value of the
4669  /// corresponding actual argument shall provide access to the first element of
4670  /// an array with at least as many elements as specified by the size expression.
4671  void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)4672  Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4673                                 ParmVarDecl *Param,
4674                                 const Expr *ArgExpr) {
4675    // Static array parameters are not supported in C++.
4676    if (!Param || getLangOpts().CPlusPlus)
4677      return;
4678  
4679    QualType OrigTy = Param->getOriginalType();
4680  
4681    const ArrayType *AT = Context.getAsArrayType(OrigTy);
4682    if (!AT || AT->getSizeModifier() != ArrayType::Static)
4683      return;
4684  
4685    if (ArgExpr->isNullPointerConstant(Context,
4686                                       Expr::NPC_NeverValueDependent)) {
4687      Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4688      DiagnoseCalleeStaticArrayParam(*this, Param);
4689      return;
4690    }
4691  
4692    const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4693    if (!CAT)
4694      return;
4695  
4696    const ConstantArrayType *ArgCAT =
4697      Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4698    if (!ArgCAT)
4699      return;
4700  
4701    if (ArgCAT->getSize().ult(CAT->getSize())) {
4702      Diag(CallLoc, diag::warn_static_array_too_small)
4703        << ArgExpr->getSourceRange()
4704        << (unsigned) ArgCAT->getSize().getZExtValue()
4705        << (unsigned) CAT->getSize().getZExtValue();
4706      DiagnoseCalleeStaticArrayParam(*this, Param);
4707    }
4708  }
4709  
4710  /// Given a function expression of unknown-any type, try to rebuild it
4711  /// to have a function type.
4712  static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4713  
4714  /// Is the given type a placeholder that we need to lower out
4715  /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)4716  static bool isPlaceholderToRemoveAsArg(QualType type) {
4717    // Placeholders are never sugared.
4718    const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4719    if (!placeholder) return false;
4720  
4721    switch (placeholder->getKind()) {
4722    // Ignore all the non-placeholder types.
4723  #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4724  #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4725  #include "clang/AST/BuiltinTypes.def"
4726      return false;
4727  
4728    // We cannot lower out overload sets; they might validly be resolved
4729    // by the call machinery.
4730    case BuiltinType::Overload:
4731      return false;
4732  
4733    // Unbridged casts in ARC can be handled in some call positions and
4734    // should be left in place.
4735    case BuiltinType::ARCUnbridgedCast:
4736      return false;
4737  
4738    // Pseudo-objects should be converted as soon as possible.
4739    case BuiltinType::PseudoObject:
4740      return true;
4741  
4742    // The debugger mode could theoretically but currently does not try
4743    // to resolve unknown-typed arguments based on known parameter types.
4744    case BuiltinType::UnknownAny:
4745      return true;
4746  
4747    // These are always invalid as call arguments and should be reported.
4748    case BuiltinType::BoundMember:
4749    case BuiltinType::BuiltinFn:
4750    case BuiltinType::OMPArraySection:
4751      return true;
4752  
4753    }
4754    llvm_unreachable("bad builtin type kind");
4755  }
4756  
4757  /// Check an argument list for placeholders that we won't try to
4758  /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)4759  static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4760    // Apply this processing to all the arguments at once instead of
4761    // dying at the first failure.
4762    bool hasInvalid = false;
4763    for (size_t i = 0, e = args.size(); i != e; i++) {
4764      if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4765        ExprResult result = S.CheckPlaceholderExpr(args[i]);
4766        if (result.isInvalid()) hasInvalid = true;
4767        else args[i] = result.get();
4768      } else if (hasInvalid) {
4769        (void)S.CorrectDelayedTyposInExpr(args[i]);
4770      }
4771    }
4772    return hasInvalid;
4773  }
4774  
4775  /// If a builtin function has a pointer argument with no explicit address
4776  /// space, than it should be able to accept a pointer to any address
4777  /// space as input.  In order to do this, we need to replace the
4778  /// standard builtin declaration with one that uses the same address space
4779  /// as the call.
4780  ///
4781  /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4782  ///                  it does not contain any pointer arguments without
4783  ///                  an address space qualifer.  Otherwise the rewritten
4784  ///                  FunctionDecl is returned.
4785  /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,const FunctionDecl * FDecl,MultiExprArg ArgExprs)4786  static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4787                                                  const FunctionDecl *FDecl,
4788                                                  MultiExprArg ArgExprs) {
4789  
4790    QualType DeclType = FDecl->getType();
4791    const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4792  
4793    if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4794        !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4795      return nullptr;
4796  
4797    bool NeedsNewDecl = false;
4798    unsigned i = 0;
4799    SmallVector<QualType, 8> OverloadParams;
4800  
4801    for (QualType ParamType : FT->param_types()) {
4802  
4803      // Convert array arguments to pointer to simplify type lookup.
4804      Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4805      QualType ArgType = Arg->getType();
4806      if (!ParamType->isPointerType() ||
4807          ParamType.getQualifiers().hasAddressSpace() ||
4808          !ArgType->isPointerType() ||
4809          !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4810        OverloadParams.push_back(ParamType);
4811        continue;
4812      }
4813  
4814      NeedsNewDecl = true;
4815      unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4816  
4817      QualType PointeeType = ParamType->getPointeeType();
4818      PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4819      OverloadParams.push_back(Context.getPointerType(PointeeType));
4820    }
4821  
4822    if (!NeedsNewDecl)
4823      return nullptr;
4824  
4825    FunctionProtoType::ExtProtoInfo EPI;
4826    QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4827                                                  OverloadParams, EPI);
4828    DeclContext *Parent = Context.getTranslationUnitDecl();
4829    FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4830                                                      FDecl->getLocation(),
4831                                                      FDecl->getLocation(),
4832                                                      FDecl->getIdentifier(),
4833                                                      OverloadTy,
4834                                                      /*TInfo=*/nullptr,
4835                                                      SC_Extern, false,
4836                                                      /*hasPrototype=*/true);
4837    SmallVector<ParmVarDecl*, 16> Params;
4838    FT = cast<FunctionProtoType>(OverloadTy);
4839    for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4840      QualType ParamType = FT->getParamType(i);
4841      ParmVarDecl *Parm =
4842          ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4843                                  SourceLocation(), nullptr, ParamType,
4844                                  /*TInfo=*/nullptr, SC_None, nullptr);
4845      Parm->setScopeInfo(0, i);
4846      Params.push_back(Parm);
4847    }
4848    OverloadDecl->setParams(Params);
4849    return OverloadDecl;
4850  }
4851  
4852  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4853  /// This provides the location of the left/right parens and a list of comma
4854  /// locations.
4855  ExprResult
ActOnCallExpr(Scope * S,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)4856  Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4857                      MultiExprArg ArgExprs, SourceLocation RParenLoc,
4858                      Expr *ExecConfig, bool IsExecConfig) {
4859    // Since this might be a postfix expression, get rid of ParenListExprs.
4860    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4861    if (Result.isInvalid()) return ExprError();
4862    Fn = Result.get();
4863  
4864    if (checkArgsForPlaceholders(*this, ArgExprs))
4865      return ExprError();
4866  
4867    if (getLangOpts().CPlusPlus) {
4868      // If this is a pseudo-destructor expression, build the call immediately.
4869      if (isa<CXXPseudoDestructorExpr>(Fn)) {
4870        if (!ArgExprs.empty()) {
4871          // Pseudo-destructor calls should not have any arguments.
4872          Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4873            << FixItHint::CreateRemoval(
4874                                      SourceRange(ArgExprs.front()->getLocStart(),
4875                                                  ArgExprs.back()->getLocEnd()));
4876        }
4877  
4878        return new (Context)
4879            CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4880      }
4881      if (Fn->getType() == Context.PseudoObjectTy) {
4882        ExprResult result = CheckPlaceholderExpr(Fn);
4883        if (result.isInvalid()) return ExprError();
4884        Fn = result.get();
4885      }
4886  
4887      // Determine whether this is a dependent call inside a C++ template,
4888      // in which case we won't do any semantic analysis now.
4889      // FIXME: Will need to cache the results of name lookup (including ADL) in
4890      // Fn.
4891      bool Dependent = false;
4892      if (Fn->isTypeDependent())
4893        Dependent = true;
4894      else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4895        Dependent = true;
4896  
4897      if (Dependent) {
4898        if (ExecConfig) {
4899          return new (Context) CUDAKernelCallExpr(
4900              Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4901              Context.DependentTy, VK_RValue, RParenLoc);
4902        } else {
4903          return new (Context) CallExpr(
4904              Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4905        }
4906      }
4907  
4908      // Determine whether this is a call to an object (C++ [over.call.object]).
4909      if (Fn->getType()->isRecordType())
4910        return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4911                                            RParenLoc);
4912  
4913      if (Fn->getType() == Context.UnknownAnyTy) {
4914        ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4915        if (result.isInvalid()) return ExprError();
4916        Fn = result.get();
4917      }
4918  
4919      if (Fn->getType() == Context.BoundMemberTy) {
4920        return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4921      }
4922    }
4923  
4924    // Check for overloaded calls.  This can happen even in C due to extensions.
4925    if (Fn->getType() == Context.OverloadTy) {
4926      OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4927  
4928      // We aren't supposed to apply this logic for if there's an '&' involved.
4929      if (!find.HasFormOfMemberPointer) {
4930        OverloadExpr *ovl = find.Expression;
4931        if (isa<UnresolvedLookupExpr>(ovl)) {
4932          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4933          return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4934                                         RParenLoc, ExecConfig);
4935        } else {
4936          return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4937                                           RParenLoc);
4938        }
4939      }
4940    }
4941  
4942    // If we're directly calling a function, get the appropriate declaration.
4943    if (Fn->getType() == Context.UnknownAnyTy) {
4944      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4945      if (result.isInvalid()) return ExprError();
4946      Fn = result.get();
4947    }
4948  
4949    Expr *NakedFn = Fn->IgnoreParens();
4950  
4951    NamedDecl *NDecl = nullptr;
4952    if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4953      if (UnOp->getOpcode() == UO_AddrOf)
4954        NakedFn = UnOp->getSubExpr()->IgnoreParens();
4955  
4956    if (isa<DeclRefExpr>(NakedFn)) {
4957      NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4958  
4959      FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4960      if (FDecl && FDecl->getBuiltinID()) {
4961        // Rewrite the function decl for this builtin by replacing paramaters
4962        // with no explicit address space with the address space of the arguments
4963        // in ArgExprs.
4964        if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4965          NDecl = FDecl;
4966          Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4967                             SourceLocation(), FDecl, false,
4968                             SourceLocation(), FDecl->getType(),
4969                             Fn->getValueKind(), FDecl);
4970        }
4971      }
4972    } else if (isa<MemberExpr>(NakedFn))
4973      NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4974  
4975    if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4976      if (FD->hasAttr<EnableIfAttr>()) {
4977        if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4978          Diag(Fn->getLocStart(),
4979               isa<CXXMethodDecl>(FD) ?
4980                   diag::err_ovl_no_viable_member_function_in_call :
4981                   diag::err_ovl_no_viable_function_in_call)
4982            << FD << FD->getSourceRange();
4983          Diag(FD->getLocation(),
4984               diag::note_ovl_candidate_disabled_by_enable_if_attr)
4985              << Attr->getCond()->getSourceRange() << Attr->getMessage();
4986        }
4987      }
4988    }
4989  
4990    return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4991                                 ExecConfig, IsExecConfig);
4992  }
4993  
4994  /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4995  ///
4996  /// __builtin_astype( value, dst type )
4997  ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)4998  ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4999                                   SourceLocation BuiltinLoc,
5000                                   SourceLocation RParenLoc) {
5001    ExprValueKind VK = VK_RValue;
5002    ExprObjectKind OK = OK_Ordinary;
5003    QualType DstTy = GetTypeFromParser(ParsedDestTy);
5004    QualType SrcTy = E->getType();
5005    if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5006      return ExprError(Diag(BuiltinLoc,
5007                            diag::err_invalid_astype_of_different_size)
5008                       << DstTy
5009                       << SrcTy
5010                       << E->getSourceRange());
5011    return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5012  }
5013  
5014  /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5015  /// provided arguments.
5016  ///
5017  /// __builtin_convertvector( value, dst type )
5018  ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)5019  ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5020                                          SourceLocation BuiltinLoc,
5021                                          SourceLocation RParenLoc) {
5022    TypeSourceInfo *TInfo;
5023    GetTypeFromParser(ParsedDestTy, &TInfo);
5024    return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5025  }
5026  
5027  /// BuildResolvedCallExpr - Build a call to a resolved expression,
5028  /// i.e. an expression not of \p OverloadTy.  The expression should
5029  /// unary-convert to an expression of function-pointer or
5030  /// block-pointer type.
5031  ///
5032  /// \param NDecl the declaration being called, if available
5033  ExprResult
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig)5034  Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5035                              SourceLocation LParenLoc,
5036                              ArrayRef<Expr *> Args,
5037                              SourceLocation RParenLoc,
5038                              Expr *Config, bool IsExecConfig) {
5039    FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5040    unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5041  
5042    // Promote the function operand.
5043    // We special-case function promotion here because we only allow promoting
5044    // builtin functions to function pointers in the callee of a call.
5045    ExprResult Result;
5046    if (BuiltinID &&
5047        Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5048      Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5049                                 CK_BuiltinFnToFnPtr).get();
5050    } else {
5051      Result = CallExprUnaryConversions(Fn);
5052    }
5053    if (Result.isInvalid())
5054      return ExprError();
5055    Fn = Result.get();
5056  
5057    // Make the call expr early, before semantic checks.  This guarantees cleanup
5058    // of arguments and function on error.
5059    CallExpr *TheCall;
5060    if (Config)
5061      TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5062                                                 cast<CallExpr>(Config), Args,
5063                                                 Context.BoolTy, VK_RValue,
5064                                                 RParenLoc);
5065    else
5066      TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5067                                       VK_RValue, RParenLoc);
5068  
5069    if (!getLangOpts().CPlusPlus) {
5070      // C cannot always handle TypoExpr nodes in builtin calls and direct
5071      // function calls as their argument checking don't necessarily handle
5072      // dependent types properly, so make sure any TypoExprs have been
5073      // dealt with.
5074      ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5075      if (!Result.isUsable()) return ExprError();
5076      TheCall = dyn_cast<CallExpr>(Result.get());
5077      if (!TheCall) return Result;
5078      Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5079    }
5080  
5081    // Bail out early if calling a builtin with custom typechecking.
5082    if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5083      return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5084  
5085   retry:
5086    const FunctionType *FuncT;
5087    if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5088      // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5089      // have type pointer to function".
5090      FuncT = PT->getPointeeType()->getAs<FunctionType>();
5091      if (!FuncT)
5092        return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5093                           << Fn->getType() << Fn->getSourceRange());
5094    } else if (const BlockPointerType *BPT =
5095                 Fn->getType()->getAs<BlockPointerType>()) {
5096      FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5097    } else {
5098      // Handle calls to expressions of unknown-any type.
5099      if (Fn->getType() == Context.UnknownAnyTy) {
5100        ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5101        if (rewrite.isInvalid()) return ExprError();
5102        Fn = rewrite.get();
5103        TheCall->setCallee(Fn);
5104        goto retry;
5105      }
5106  
5107      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5108        << Fn->getType() << Fn->getSourceRange());
5109    }
5110  
5111    if (getLangOpts().CUDA) {
5112      if (Config) {
5113        // CUDA: Kernel calls must be to global functions
5114        if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5115          return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5116              << FDecl->getName() << Fn->getSourceRange());
5117  
5118        // CUDA: Kernel function must have 'void' return type
5119        if (!FuncT->getReturnType()->isVoidType())
5120          return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5121              << Fn->getType() << Fn->getSourceRange());
5122      } else {
5123        // CUDA: Calls to global functions must be configured
5124        if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5125          return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5126              << FDecl->getName() << Fn->getSourceRange());
5127      }
5128    }
5129  
5130    // Check for a valid return type
5131    if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5132                            FDecl))
5133      return ExprError();
5134  
5135    // We know the result type of the call, set it.
5136    TheCall->setType(FuncT->getCallResultType(Context));
5137    TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5138  
5139    const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5140    if (Proto) {
5141      if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5142                                  IsExecConfig))
5143        return ExprError();
5144    } else {
5145      assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5146  
5147      if (FDecl) {
5148        // Check if we have too few/too many template arguments, based
5149        // on our knowledge of the function definition.
5150        const FunctionDecl *Def = nullptr;
5151        if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5152          Proto = Def->getType()->getAs<FunctionProtoType>();
5153         if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5154            Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5155            << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5156        }
5157  
5158        // If the function we're calling isn't a function prototype, but we have
5159        // a function prototype from a prior declaratiom, use that prototype.
5160        if (!FDecl->hasPrototype())
5161          Proto = FDecl->getType()->getAs<FunctionProtoType>();
5162      }
5163  
5164      // Promote the arguments (C99 6.5.2.2p6).
5165      for (unsigned i = 0, e = Args.size(); i != e; i++) {
5166        Expr *Arg = Args[i];
5167  
5168        if (Proto && i < Proto->getNumParams()) {
5169          InitializedEntity Entity = InitializedEntity::InitializeParameter(
5170              Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5171          ExprResult ArgE =
5172              PerformCopyInitialization(Entity, SourceLocation(), Arg);
5173          if (ArgE.isInvalid())
5174            return true;
5175  
5176          Arg = ArgE.getAs<Expr>();
5177  
5178        } else {
5179          ExprResult ArgE = DefaultArgumentPromotion(Arg);
5180  
5181          if (ArgE.isInvalid())
5182            return true;
5183  
5184          Arg = ArgE.getAs<Expr>();
5185        }
5186  
5187        if (RequireCompleteType(Arg->getLocStart(),
5188                                Arg->getType(),
5189                                diag::err_call_incomplete_argument, Arg))
5190          return ExprError();
5191  
5192        TheCall->setArg(i, Arg);
5193      }
5194    }
5195  
5196    if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5197      if (!Method->isStatic())
5198        return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5199          << Fn->getSourceRange());
5200  
5201    // Check for sentinels
5202    if (NDecl)
5203      DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5204  
5205    // Do special checking on direct calls to functions.
5206    if (FDecl) {
5207      if (CheckFunctionCall(FDecl, TheCall, Proto))
5208        return ExprError();
5209  
5210      if (BuiltinID)
5211        return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5212    } else if (NDecl) {
5213      if (CheckPointerCall(NDecl, TheCall, Proto))
5214        return ExprError();
5215    } else {
5216      if (CheckOtherCall(TheCall, Proto))
5217        return ExprError();
5218    }
5219  
5220    return MaybeBindToTemporary(TheCall);
5221  }
5222  
5223  ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)5224  Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5225                             SourceLocation RParenLoc, Expr *InitExpr) {
5226    assert(Ty && "ActOnCompoundLiteral(): missing type");
5227    assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5228  
5229    TypeSourceInfo *TInfo;
5230    QualType literalType = GetTypeFromParser(Ty, &TInfo);
5231    if (!TInfo)
5232      TInfo = Context.getTrivialTypeSourceInfo(literalType);
5233  
5234    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5235  }
5236  
5237  ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)5238  Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5239                                 SourceLocation RParenLoc, Expr *LiteralExpr) {
5240    QualType literalType = TInfo->getType();
5241  
5242    if (literalType->isArrayType()) {
5243      if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5244            diag::err_illegal_decl_array_incomplete_type,
5245            SourceRange(LParenLoc,
5246                        LiteralExpr->getSourceRange().getEnd())))
5247        return ExprError();
5248      if (literalType->isVariableArrayType())
5249        return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5250          << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5251    } else if (!literalType->isDependentType() &&
5252               RequireCompleteType(LParenLoc, literalType,
5253                 diag::err_typecheck_decl_incomplete_type,
5254                 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5255      return ExprError();
5256  
5257    InitializedEntity Entity
5258      = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5259    InitializationKind Kind
5260      = InitializationKind::CreateCStyleCast(LParenLoc,
5261                                             SourceRange(LParenLoc, RParenLoc),
5262                                             /*InitList=*/true);
5263    InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5264    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5265                                        &literalType);
5266    if (Result.isInvalid())
5267      return ExprError();
5268    LiteralExpr = Result.get();
5269  
5270    bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5271    if (isFileScope &&
5272        !LiteralExpr->isTypeDependent() &&
5273        !LiteralExpr->isValueDependent() &&
5274        !literalType->isDependentType()) { // 6.5.2.5p3
5275      if (CheckForConstantInitializer(LiteralExpr, literalType))
5276        return ExprError();
5277    }
5278  
5279    // In C, compound literals are l-values for some reason.
5280    ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5281  
5282    return MaybeBindToTemporary(
5283             new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5284                                               VK, LiteralExpr, isFileScope));
5285  }
5286  
5287  ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)5288  Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5289                      SourceLocation RBraceLoc) {
5290    // Immediately handle non-overload placeholders.  Overloads can be
5291    // resolved contextually, but everything else here can't.
5292    for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5293      if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5294        ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5295  
5296        // Ignore failures; dropping the entire initializer list because
5297        // of one failure would be terrible for indexing/etc.
5298        if (result.isInvalid()) continue;
5299  
5300        InitArgList[I] = result.get();
5301      }
5302    }
5303  
5304    // Semantic analysis for initializers is done by ActOnDeclarator() and
5305    // CheckInitializer() - it requires knowledge of the object being intialized.
5306  
5307    InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5308                                                 RBraceLoc);
5309    E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5310    return E;
5311  }
5312  
5313  /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)5314  void Sema::maybeExtendBlockObject(ExprResult &E) {
5315    assert(E.get()->getType()->isBlockPointerType());
5316    assert(E.get()->isRValue());
5317  
5318    // Only do this in an r-value context.
5319    if (!getLangOpts().ObjCAutoRefCount) return;
5320  
5321    E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5322                                 CK_ARCExtendBlockObject, E.get(),
5323                                 /*base path*/ nullptr, VK_RValue);
5324    ExprNeedsCleanups = true;
5325  }
5326  
5327  /// Prepare a conversion of the given expression to an ObjC object
5328  /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)5329  CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5330    QualType type = E.get()->getType();
5331    if (type->isObjCObjectPointerType()) {
5332      return CK_BitCast;
5333    } else if (type->isBlockPointerType()) {
5334      maybeExtendBlockObject(E);
5335      return CK_BlockPointerToObjCPointerCast;
5336    } else {
5337      assert(type->isPointerType());
5338      return CK_CPointerToObjCPointerCast;
5339    }
5340  }
5341  
5342  /// Prepares for a scalar cast, performing all the necessary stages
5343  /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)5344  CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5345    // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5346    // Also, callers should have filtered out the invalid cases with
5347    // pointers.  Everything else should be possible.
5348  
5349    QualType SrcTy = Src.get()->getType();
5350    if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5351      return CK_NoOp;
5352  
5353    switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5354    case Type::STK_MemberPointer:
5355      llvm_unreachable("member pointer type in C");
5356  
5357    case Type::STK_CPointer:
5358    case Type::STK_BlockPointer:
5359    case Type::STK_ObjCObjectPointer:
5360      switch (DestTy->getScalarTypeKind()) {
5361      case Type::STK_CPointer: {
5362        unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5363        unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5364        if (SrcAS != DestAS)
5365          return CK_AddressSpaceConversion;
5366        return CK_BitCast;
5367      }
5368      case Type::STK_BlockPointer:
5369        return (SrcKind == Type::STK_BlockPointer
5370                  ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5371      case Type::STK_ObjCObjectPointer:
5372        if (SrcKind == Type::STK_ObjCObjectPointer)
5373          return CK_BitCast;
5374        if (SrcKind == Type::STK_CPointer)
5375          return CK_CPointerToObjCPointerCast;
5376        maybeExtendBlockObject(Src);
5377        return CK_BlockPointerToObjCPointerCast;
5378      case Type::STK_Bool:
5379        return CK_PointerToBoolean;
5380      case Type::STK_Integral:
5381        return CK_PointerToIntegral;
5382      case Type::STK_Floating:
5383      case Type::STK_FloatingComplex:
5384      case Type::STK_IntegralComplex:
5385      case Type::STK_MemberPointer:
5386        llvm_unreachable("illegal cast from pointer");
5387      }
5388      llvm_unreachable("Should have returned before this");
5389  
5390    case Type::STK_Bool: // casting from bool is like casting from an integer
5391    case Type::STK_Integral:
5392      switch (DestTy->getScalarTypeKind()) {
5393      case Type::STK_CPointer:
5394      case Type::STK_ObjCObjectPointer:
5395      case Type::STK_BlockPointer:
5396        if (Src.get()->isNullPointerConstant(Context,
5397                                             Expr::NPC_ValueDependentIsNull))
5398          return CK_NullToPointer;
5399        return CK_IntegralToPointer;
5400      case Type::STK_Bool:
5401        return CK_IntegralToBoolean;
5402      case Type::STK_Integral:
5403        return CK_IntegralCast;
5404      case Type::STK_Floating:
5405        return CK_IntegralToFloating;
5406      case Type::STK_IntegralComplex:
5407        Src = ImpCastExprToType(Src.get(),
5408                        DestTy->castAs<ComplexType>()->getElementType(),
5409                        CK_IntegralCast);
5410        return CK_IntegralRealToComplex;
5411      case Type::STK_FloatingComplex:
5412        Src = ImpCastExprToType(Src.get(),
5413                        DestTy->castAs<ComplexType>()->getElementType(),
5414                        CK_IntegralToFloating);
5415        return CK_FloatingRealToComplex;
5416      case Type::STK_MemberPointer:
5417        llvm_unreachable("member pointer type in C");
5418      }
5419      llvm_unreachable("Should have returned before this");
5420  
5421    case Type::STK_Floating:
5422      switch (DestTy->getScalarTypeKind()) {
5423      case Type::STK_Floating:
5424        return CK_FloatingCast;
5425      case Type::STK_Bool:
5426        return CK_FloatingToBoolean;
5427      case Type::STK_Integral:
5428        return CK_FloatingToIntegral;
5429      case Type::STK_FloatingComplex:
5430        Src = ImpCastExprToType(Src.get(),
5431                                DestTy->castAs<ComplexType>()->getElementType(),
5432                                CK_FloatingCast);
5433        return CK_FloatingRealToComplex;
5434      case Type::STK_IntegralComplex:
5435        Src = ImpCastExprToType(Src.get(),
5436                                DestTy->castAs<ComplexType>()->getElementType(),
5437                                CK_FloatingToIntegral);
5438        return CK_IntegralRealToComplex;
5439      case Type::STK_CPointer:
5440      case Type::STK_ObjCObjectPointer:
5441      case Type::STK_BlockPointer:
5442        llvm_unreachable("valid float->pointer cast?");
5443      case Type::STK_MemberPointer:
5444        llvm_unreachable("member pointer type in C");
5445      }
5446      llvm_unreachable("Should have returned before this");
5447  
5448    case Type::STK_FloatingComplex:
5449      switch (DestTy->getScalarTypeKind()) {
5450      case Type::STK_FloatingComplex:
5451        return CK_FloatingComplexCast;
5452      case Type::STK_IntegralComplex:
5453        return CK_FloatingComplexToIntegralComplex;
5454      case Type::STK_Floating: {
5455        QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5456        if (Context.hasSameType(ET, DestTy))
5457          return CK_FloatingComplexToReal;
5458        Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5459        return CK_FloatingCast;
5460      }
5461      case Type::STK_Bool:
5462        return CK_FloatingComplexToBoolean;
5463      case Type::STK_Integral:
5464        Src = ImpCastExprToType(Src.get(),
5465                                SrcTy->castAs<ComplexType>()->getElementType(),
5466                                CK_FloatingComplexToReal);
5467        return CK_FloatingToIntegral;
5468      case Type::STK_CPointer:
5469      case Type::STK_ObjCObjectPointer:
5470      case Type::STK_BlockPointer:
5471        llvm_unreachable("valid complex float->pointer cast?");
5472      case Type::STK_MemberPointer:
5473        llvm_unreachable("member pointer type in C");
5474      }
5475      llvm_unreachable("Should have returned before this");
5476  
5477    case Type::STK_IntegralComplex:
5478      switch (DestTy->getScalarTypeKind()) {
5479      case Type::STK_FloatingComplex:
5480        return CK_IntegralComplexToFloatingComplex;
5481      case Type::STK_IntegralComplex:
5482        return CK_IntegralComplexCast;
5483      case Type::STK_Integral: {
5484        QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5485        if (Context.hasSameType(ET, DestTy))
5486          return CK_IntegralComplexToReal;
5487        Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5488        return CK_IntegralCast;
5489      }
5490      case Type::STK_Bool:
5491        return CK_IntegralComplexToBoolean;
5492      case Type::STK_Floating:
5493        Src = ImpCastExprToType(Src.get(),
5494                                SrcTy->castAs<ComplexType>()->getElementType(),
5495                                CK_IntegralComplexToReal);
5496        return CK_IntegralToFloating;
5497      case Type::STK_CPointer:
5498      case Type::STK_ObjCObjectPointer:
5499      case Type::STK_BlockPointer:
5500        llvm_unreachable("valid complex int->pointer cast?");
5501      case Type::STK_MemberPointer:
5502        llvm_unreachable("member pointer type in C");
5503      }
5504      llvm_unreachable("Should have returned before this");
5505    }
5506  
5507    llvm_unreachable("Unhandled scalar cast");
5508  }
5509  
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)5510  static bool breakDownVectorType(QualType type, uint64_t &len,
5511                                  QualType &eltType) {
5512    // Vectors are simple.
5513    if (const VectorType *vecType = type->getAs<VectorType>()) {
5514      len = vecType->getNumElements();
5515      eltType = vecType->getElementType();
5516      assert(eltType->isScalarType());
5517      return true;
5518    }
5519  
5520    // We allow lax conversion to and from non-vector types, but only if
5521    // they're real types (i.e. non-complex, non-pointer scalar types).
5522    if (!type->isRealType()) return false;
5523  
5524    len = 1;
5525    eltType = type;
5526    return true;
5527  }
5528  
5529  /// Are the two types lax-compatible vector types?  That is, given
5530  /// that one of them is a vector, do they have equal storage sizes,
5531  /// where the storage size is the number of elements times the element
5532  /// size?
5533  ///
5534  /// This will also return false if either of the types is neither a
5535  /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)5536  bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5537    assert(destTy->isVectorType() || srcTy->isVectorType());
5538  
5539    // Disallow lax conversions between scalars and ExtVectors (these
5540    // conversions are allowed for other vector types because common headers
5541    // depend on them).  Most scalar OP ExtVector cases are handled by the
5542    // splat path anyway, which does what we want (convert, not bitcast).
5543    // What this rules out for ExtVectors is crazy things like char4*float.
5544    if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5545    if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5546  
5547    uint64_t srcLen, destLen;
5548    QualType srcEltTy, destEltTy;
5549    if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5550    if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5551  
5552    // ASTContext::getTypeSize will return the size rounded up to a
5553    // power of 2, so instead of using that, we need to use the raw
5554    // element size multiplied by the element count.
5555    uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5556    uint64_t destEltSize = Context.getTypeSize(destEltTy);
5557  
5558    return (srcLen * srcEltSize == destLen * destEltSize);
5559  }
5560  
5561  /// Is this a legal conversion between two types, one of which is
5562  /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)5563  bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5564    assert(destTy->isVectorType() || srcTy->isVectorType());
5565  
5566    if (!Context.getLangOpts().LaxVectorConversions)
5567      return false;
5568    return areLaxCompatibleVectorTypes(srcTy, destTy);
5569  }
5570  
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)5571  bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5572                             CastKind &Kind) {
5573    assert(VectorTy->isVectorType() && "Not a vector type!");
5574  
5575    if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5576      if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5577        return Diag(R.getBegin(),
5578                    Ty->isVectorType() ?
5579                    diag::err_invalid_conversion_between_vectors :
5580                    diag::err_invalid_conversion_between_vector_and_integer)
5581          << VectorTy << Ty << R;
5582    } else
5583      return Diag(R.getBegin(),
5584                  diag::err_invalid_conversion_between_vector_and_scalar)
5585        << VectorTy << Ty << R;
5586  
5587    Kind = CK_BitCast;
5588    return false;
5589  }
5590  
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)5591  ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5592                                      Expr *CastExpr, CastKind &Kind) {
5593    assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5594  
5595    QualType SrcTy = CastExpr->getType();
5596  
5597    // If SrcTy is a VectorType, the total size must match to explicitly cast to
5598    // an ExtVectorType.
5599    // In OpenCL, casts between vectors of different types are not allowed.
5600    // (See OpenCL 6.2).
5601    if (SrcTy->isVectorType()) {
5602      if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5603          || (getLangOpts().OpenCL &&
5604              (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5605        Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5606          << DestTy << SrcTy << R;
5607        return ExprError();
5608      }
5609      Kind = CK_BitCast;
5610      return CastExpr;
5611    }
5612  
5613    // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5614    // conversion will take place first from scalar to elt type, and then
5615    // splat from elt type to vector.
5616    if (SrcTy->isPointerType())
5617      return Diag(R.getBegin(),
5618                  diag::err_invalid_conversion_between_vector_and_scalar)
5619        << DestTy << SrcTy << R;
5620  
5621    QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5622    ExprResult CastExprRes = CastExpr;
5623    CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5624    if (CastExprRes.isInvalid())
5625      return ExprError();
5626    CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5627  
5628    Kind = CK_VectorSplat;
5629    return CastExpr;
5630  }
5631  
5632  ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)5633  Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5634                      Declarator &D, ParsedType &Ty,
5635                      SourceLocation RParenLoc, Expr *CastExpr) {
5636    assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5637           "ActOnCastExpr(): missing type or expr");
5638  
5639    TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5640    if (D.isInvalidType())
5641      return ExprError();
5642  
5643    if (getLangOpts().CPlusPlus) {
5644      // Check that there are no default arguments (C++ only).
5645      CheckExtraCXXDefaultArguments(D);
5646    } else {
5647      // Make sure any TypoExprs have been dealt with.
5648      ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5649      if (!Res.isUsable())
5650        return ExprError();
5651      CastExpr = Res.get();
5652    }
5653  
5654    checkUnusedDeclAttributes(D);
5655  
5656    QualType castType = castTInfo->getType();
5657    Ty = CreateParsedType(castType, castTInfo);
5658  
5659    bool isVectorLiteral = false;
5660  
5661    // Check for an altivec or OpenCL literal,
5662    // i.e. all the elements are integer constants.
5663    ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5664    ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5665    if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5666         && castType->isVectorType() && (PE || PLE)) {
5667      if (PLE && PLE->getNumExprs() == 0) {
5668        Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5669        return ExprError();
5670      }
5671      if (PE || PLE->getNumExprs() == 1) {
5672        Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5673        if (!E->getType()->isVectorType())
5674          isVectorLiteral = true;
5675      }
5676      else
5677        isVectorLiteral = true;
5678    }
5679  
5680    // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5681    // then handle it as such.
5682    if (isVectorLiteral)
5683      return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5684  
5685    // If the Expr being casted is a ParenListExpr, handle it specially.
5686    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5687    // sequence of BinOp comma operators.
5688    if (isa<ParenListExpr>(CastExpr)) {
5689      ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5690      if (Result.isInvalid()) return ExprError();
5691      CastExpr = Result.get();
5692    }
5693  
5694    if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5695        !getSourceManager().isInSystemMacro(LParenLoc))
5696      Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5697  
5698    CheckTollFreeBridgeCast(castType, CastExpr);
5699  
5700    CheckObjCBridgeRelatedCast(castType, CastExpr);
5701  
5702    return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5703  }
5704  
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)5705  ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5706                                      SourceLocation RParenLoc, Expr *E,
5707                                      TypeSourceInfo *TInfo) {
5708    assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5709           "Expected paren or paren list expression");
5710  
5711    Expr **exprs;
5712    unsigned numExprs;
5713    Expr *subExpr;
5714    SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5715    if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5716      LiteralLParenLoc = PE->getLParenLoc();
5717      LiteralRParenLoc = PE->getRParenLoc();
5718      exprs = PE->getExprs();
5719      numExprs = PE->getNumExprs();
5720    } else { // isa<ParenExpr> by assertion at function entrance
5721      LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5722      LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5723      subExpr = cast<ParenExpr>(E)->getSubExpr();
5724      exprs = &subExpr;
5725      numExprs = 1;
5726    }
5727  
5728    QualType Ty = TInfo->getType();
5729    assert(Ty->isVectorType() && "Expected vector type");
5730  
5731    SmallVector<Expr *, 8> initExprs;
5732    const VectorType *VTy = Ty->getAs<VectorType>();
5733    unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5734  
5735    // '(...)' form of vector initialization in AltiVec: the number of
5736    // initializers must be one or must match the size of the vector.
5737    // If a single value is specified in the initializer then it will be
5738    // replicated to all the components of the vector
5739    if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5740      // The number of initializers must be one or must match the size of the
5741      // vector. If a single value is specified in the initializer then it will
5742      // be replicated to all the components of the vector
5743      if (numExprs == 1) {
5744        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5745        ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5746        if (Literal.isInvalid())
5747          return ExprError();
5748        Literal = ImpCastExprToType(Literal.get(), ElemTy,
5749                                    PrepareScalarCast(Literal, ElemTy));
5750        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5751      }
5752      else if (numExprs < numElems) {
5753        Diag(E->getExprLoc(),
5754             diag::err_incorrect_number_of_vector_initializers);
5755        return ExprError();
5756      }
5757      else
5758        initExprs.append(exprs, exprs + numExprs);
5759    }
5760    else {
5761      // For OpenCL, when the number of initializers is a single value,
5762      // it will be replicated to all components of the vector.
5763      if (getLangOpts().OpenCL &&
5764          VTy->getVectorKind() == VectorType::GenericVector &&
5765          numExprs == 1) {
5766          QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5767          ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5768          if (Literal.isInvalid())
5769            return ExprError();
5770          Literal = ImpCastExprToType(Literal.get(), ElemTy,
5771                                      PrepareScalarCast(Literal, ElemTy));
5772          return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5773      }
5774  
5775      initExprs.append(exprs, exprs + numExprs);
5776    }
5777    // FIXME: This means that pretty-printing the final AST will produce curly
5778    // braces instead of the original commas.
5779    InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5780                                                     initExprs, LiteralRParenLoc);
5781    initE->setType(Ty);
5782    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5783  }
5784  
5785  /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5786  /// the ParenListExpr into a sequence of comma binary operators.
5787  ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)5788  Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5789    ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5790    if (!E)
5791      return OrigExpr;
5792  
5793    ExprResult Result(E->getExpr(0));
5794  
5795    for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5796      Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5797                          E->getExpr(i));
5798  
5799    if (Result.isInvalid()) return ExprError();
5800  
5801    return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5802  }
5803  
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)5804  ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5805                                      SourceLocation R,
5806                                      MultiExprArg Val) {
5807    Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5808    return expr;
5809  }
5810  
5811  /// \brief Emit a specialized diagnostic when one expression is a null pointer
5812  /// constant and the other is not a pointer.  Returns true if a diagnostic is
5813  /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)5814  bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5815                                        SourceLocation QuestionLoc) {
5816    Expr *NullExpr = LHSExpr;
5817    Expr *NonPointerExpr = RHSExpr;
5818    Expr::NullPointerConstantKind NullKind =
5819        NullExpr->isNullPointerConstant(Context,
5820                                        Expr::NPC_ValueDependentIsNotNull);
5821  
5822    if (NullKind == Expr::NPCK_NotNull) {
5823      NullExpr = RHSExpr;
5824      NonPointerExpr = LHSExpr;
5825      NullKind =
5826          NullExpr->isNullPointerConstant(Context,
5827                                          Expr::NPC_ValueDependentIsNotNull);
5828    }
5829  
5830    if (NullKind == Expr::NPCK_NotNull)
5831      return false;
5832  
5833    if (NullKind == Expr::NPCK_ZeroExpression)
5834      return false;
5835  
5836    if (NullKind == Expr::NPCK_ZeroLiteral) {
5837      // In this case, check to make sure that we got here from a "NULL"
5838      // string in the source code.
5839      NullExpr = NullExpr->IgnoreParenImpCasts();
5840      SourceLocation loc = NullExpr->getExprLoc();
5841      if (!findMacroSpelling(loc, "NULL"))
5842        return false;
5843    }
5844  
5845    int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5846    Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5847        << NonPointerExpr->getType() << DiagType
5848        << NonPointerExpr->getSourceRange();
5849    return true;
5850  }
5851  
5852  /// \brief Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)5853  static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
5854    QualType CondTy = Cond->getType();
5855  
5856    // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5857    if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5858      S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5859        << CondTy << Cond->getSourceRange();
5860      return true;
5861    }
5862  
5863    // C99 6.5.15p2
5864    if (CondTy->isScalarType()) return false;
5865  
5866    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5867      << CondTy << Cond->getSourceRange();
5868    return true;
5869  }
5870  
5871  /// \brief Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)5872  static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5873                                           ExprResult &RHS) {
5874      Expr *LHSExpr = LHS.get();
5875      Expr *RHSExpr = RHS.get();
5876  
5877      if (!LHSExpr->getType()->isVoidType())
5878        S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5879          << RHSExpr->getSourceRange();
5880      if (!RHSExpr->getType()->isVoidType())
5881        S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5882          << LHSExpr->getSourceRange();
5883      LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5884      RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5885      return S.Context.VoidTy;
5886  }
5887  
5888  /// \brief Return false if the NullExpr can be promoted to PointerTy,
5889  /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)5890  static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5891                                          QualType PointerTy) {
5892    if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5893        !NullExpr.get()->isNullPointerConstant(S.Context,
5894                                              Expr::NPC_ValueDependentIsNull))
5895      return true;
5896  
5897    NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5898    return false;
5899  }
5900  
5901  /// \brief Checks compatibility between two pointers and return the resulting
5902  /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5903  static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5904                                                       ExprResult &RHS,
5905                                                       SourceLocation Loc) {
5906    QualType LHSTy = LHS.get()->getType();
5907    QualType RHSTy = RHS.get()->getType();
5908  
5909    if (S.Context.hasSameType(LHSTy, RHSTy)) {
5910      // Two identical pointers types are always compatible.
5911      return LHSTy;
5912    }
5913  
5914    QualType lhptee, rhptee;
5915  
5916    // Get the pointee types.
5917    bool IsBlockPointer = false;
5918    if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5919      lhptee = LHSBTy->getPointeeType();
5920      rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5921      IsBlockPointer = true;
5922    } else {
5923      lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5924      rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5925    }
5926  
5927    // C99 6.5.15p6: If both operands are pointers to compatible types or to
5928    // differently qualified versions of compatible types, the result type is
5929    // a pointer to an appropriately qualified version of the composite
5930    // type.
5931  
5932    // Only CVR-qualifiers exist in the standard, and the differently-qualified
5933    // clause doesn't make sense for our extensions. E.g. address space 2 should
5934    // be incompatible with address space 3: they may live on different devices or
5935    // anything.
5936    Qualifiers lhQual = lhptee.getQualifiers();
5937    Qualifiers rhQual = rhptee.getQualifiers();
5938  
5939    unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5940    lhQual.removeCVRQualifiers();
5941    rhQual.removeCVRQualifiers();
5942  
5943    lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5944    rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5945  
5946    QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5947  
5948    if (CompositeTy.isNull()) {
5949      S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5950        << LHSTy << RHSTy << LHS.get()->getSourceRange()
5951        << RHS.get()->getSourceRange();
5952      // In this situation, we assume void* type. No especially good
5953      // reason, but this is what gcc does, and we do have to pick
5954      // to get a consistent AST.
5955      QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5956      LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5957      RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5958      return incompatTy;
5959    }
5960  
5961    // The pointer types are compatible.
5962    QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5963    if (IsBlockPointer)
5964      ResultTy = S.Context.getBlockPointerType(ResultTy);
5965    else
5966      ResultTy = S.Context.getPointerType(ResultTy);
5967  
5968    LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5969    RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5970    return ResultTy;
5971  }
5972  
5973  /// \brief Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)5974  static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5975                                                            ExprResult &LHS,
5976                                                            ExprResult &RHS,
5977                                                            SourceLocation Loc) {
5978    QualType LHSTy = LHS.get()->getType();
5979    QualType RHSTy = RHS.get()->getType();
5980  
5981    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5982      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5983        QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5984        LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5985        RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5986        return destType;
5987      }
5988      S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5989        << LHSTy << RHSTy << LHS.get()->getSourceRange()
5990        << RHS.get()->getSourceRange();
5991      return QualType();
5992    }
5993  
5994    // We have 2 block pointer types.
5995    return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5996  }
5997  
5998  /// \brief Return the resulting type when the operands are both pointers.
5999  static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)6000  checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6001                                              ExprResult &RHS,
6002                                              SourceLocation Loc) {
6003    // get the pointer types
6004    QualType LHSTy = LHS.get()->getType();
6005    QualType RHSTy = RHS.get()->getType();
6006  
6007    // get the "pointed to" types
6008    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6009    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6010  
6011    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6012    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6013      // Figure out necessary qualifiers (C99 6.5.15p6)
6014      QualType destPointee
6015        = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6016      QualType destType = S.Context.getPointerType(destPointee);
6017      // Add qualifiers if necessary.
6018      LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6019      // Promote to void*.
6020      RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6021      return destType;
6022    }
6023    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6024      QualType destPointee
6025        = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6026      QualType destType = S.Context.getPointerType(destPointee);
6027      // Add qualifiers if necessary.
6028      RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6029      // Promote to void*.
6030      LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6031      return destType;
6032    }
6033  
6034    return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6035  }
6036  
6037  /// \brief Return false if the first expression is not an integer and the second
6038  /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)6039  static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6040                                          Expr* PointerExpr, SourceLocation Loc,
6041                                          bool IsIntFirstExpr) {
6042    if (!PointerExpr->getType()->isPointerType() ||
6043        !Int.get()->getType()->isIntegerType())
6044      return false;
6045  
6046    Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6047    Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6048  
6049    S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6050      << Expr1->getType() << Expr2->getType()
6051      << Expr1->getSourceRange() << Expr2->getSourceRange();
6052    Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6053                              CK_IntegralToPointer);
6054    return true;
6055  }
6056  
6057  /// \brief Simple conversion between integer and floating point types.
6058  ///
6059  /// Used when handling the OpenCL conditional operator where the
6060  /// condition is a vector while the other operands are scalar.
6061  ///
6062  /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6063  /// types are either integer or floating type. Between the two
6064  /// operands, the type with the higher rank is defined as the "result
6065  /// type". The other operand needs to be promoted to the same type. No
6066  /// other type promotion is allowed. We cannot use
6067  /// UsualArithmeticConversions() for this purpose, since it always
6068  /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6069  static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6070                                              ExprResult &RHS,
6071                                              SourceLocation QuestionLoc) {
6072    LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6073    if (LHS.isInvalid())
6074      return QualType();
6075    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6076    if (RHS.isInvalid())
6077      return QualType();
6078  
6079    // For conversion purposes, we ignore any qualifiers.
6080    // For example, "const float" and "float" are equivalent.
6081    QualType LHSType =
6082      S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6083    QualType RHSType =
6084      S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6085  
6086    if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6087      S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6088        << LHSType << LHS.get()->getSourceRange();
6089      return QualType();
6090    }
6091  
6092    if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6093      S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6094        << RHSType << RHS.get()->getSourceRange();
6095      return QualType();
6096    }
6097  
6098    // If both types are identical, no conversion is needed.
6099    if (LHSType == RHSType)
6100      return LHSType;
6101  
6102    // Now handle "real" floating types (i.e. float, double, long double).
6103    if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6104      return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6105                                   /*IsCompAssign = */ false);
6106  
6107    // Finally, we have two differing integer types.
6108    return handleIntegerConversion<doIntegralCast, doIntegralCast>
6109    (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6110  }
6111  
6112  /// \brief Convert scalar operands to a vector that matches the
6113  ///        condition in length.
6114  ///
6115  /// Used when handling the OpenCL conditional operator where the
6116  /// condition is a vector while the other operands are scalar.
6117  ///
6118  /// We first compute the "result type" for the scalar operands
6119  /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6120  /// into a vector of that type where the length matches the condition
6121  /// vector type. s6.11.6 requires that the element types of the result
6122  /// and the condition must have the same number of bits.
6123  static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)6124  OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6125                                QualType CondTy, SourceLocation QuestionLoc) {
6126    QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6127    if (ResTy.isNull()) return QualType();
6128  
6129    const VectorType *CV = CondTy->getAs<VectorType>();
6130    assert(CV);
6131  
6132    // Determine the vector result type
6133    unsigned NumElements = CV->getNumElements();
6134    QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6135  
6136    // Ensure that all types have the same number of bits
6137    if (S.Context.getTypeSize(CV->getElementType())
6138        != S.Context.getTypeSize(ResTy)) {
6139      // Since VectorTy is created internally, it does not pretty print
6140      // with an OpenCL name. Instead, we just print a description.
6141      std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6142      SmallString<64> Str;
6143      llvm::raw_svector_ostream OS(Str);
6144      OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6145      S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6146        << CondTy << OS.str();
6147      return QualType();
6148    }
6149  
6150    // Convert operands to the vector result type
6151    LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6152    RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6153  
6154    return VectorTy;
6155  }
6156  
6157  /// \brief Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)6158  static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6159                                         SourceLocation QuestionLoc) {
6160    // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6161    // integral type.
6162    const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6163    assert(CondTy);
6164    QualType EleTy = CondTy->getElementType();
6165    if (EleTy->isIntegerType()) return false;
6166  
6167    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6168      << Cond->getType() << Cond->getSourceRange();
6169    return true;
6170  }
6171  
6172  /// \brief Return false if the vector condition type and the vector
6173  ///        result type are compatible.
6174  ///
6175  /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6176  /// number of elements, and their element types have the same number
6177  /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)6178  static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6179                                SourceLocation QuestionLoc) {
6180    const VectorType *CV = CondTy->getAs<VectorType>();
6181    const VectorType *RV = VecResTy->getAs<VectorType>();
6182    assert(CV && RV);
6183  
6184    if (CV->getNumElements() != RV->getNumElements()) {
6185      S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6186        << CondTy << VecResTy;
6187      return true;
6188    }
6189  
6190    QualType CVE = CV->getElementType();
6191    QualType RVE = RV->getElementType();
6192  
6193    if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6194      S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6195        << CondTy << VecResTy;
6196      return true;
6197    }
6198  
6199    return false;
6200  }
6201  
6202  /// \brief Return the resulting type for the conditional operator in
6203  ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6204  ///        s6.3.i) when the condition is a vector type.
6205  static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6206  OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6207                               ExprResult &LHS, ExprResult &RHS,
6208                               SourceLocation QuestionLoc) {
6209    Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6210    if (Cond.isInvalid())
6211      return QualType();
6212    QualType CondTy = Cond.get()->getType();
6213  
6214    if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6215      return QualType();
6216  
6217    // If either operand is a vector then find the vector type of the
6218    // result as specified in OpenCL v1.1 s6.3.i.
6219    if (LHS.get()->getType()->isVectorType() ||
6220        RHS.get()->getType()->isVectorType()) {
6221      QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6222                                                /*isCompAssign*/false,
6223                                                /*AllowBothBool*/true,
6224                                                /*AllowBoolConversions*/false);
6225      if (VecResTy.isNull()) return QualType();
6226      // The result type must match the condition type as specified in
6227      // OpenCL v1.1 s6.11.6.
6228      if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6229        return QualType();
6230      return VecResTy;
6231    }
6232  
6233    // Both operands are scalar.
6234    return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6235  }
6236  
6237  /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6238  /// In that case, LHS = cond.
6239  /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)6240  QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6241                                          ExprResult &RHS, ExprValueKind &VK,
6242                                          ExprObjectKind &OK,
6243                                          SourceLocation QuestionLoc) {
6244  
6245    ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6246    if (!LHSResult.isUsable()) return QualType();
6247    LHS = LHSResult;
6248  
6249    ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6250    if (!RHSResult.isUsable()) return QualType();
6251    RHS = RHSResult;
6252  
6253    // C++ is sufficiently different to merit its own checker.
6254    if (getLangOpts().CPlusPlus)
6255      return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6256  
6257    VK = VK_RValue;
6258    OK = OK_Ordinary;
6259  
6260    // The OpenCL operator with a vector condition is sufficiently
6261    // different to merit its own checker.
6262    if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6263      return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6264  
6265    // First, check the condition.
6266    Cond = UsualUnaryConversions(Cond.get());
6267    if (Cond.isInvalid())
6268      return QualType();
6269    if (checkCondition(*this, Cond.get(), QuestionLoc))
6270      return QualType();
6271  
6272    // Now check the two expressions.
6273    if (LHS.get()->getType()->isVectorType() ||
6274        RHS.get()->getType()->isVectorType())
6275      return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6276                                 /*AllowBothBool*/true,
6277                                 /*AllowBoolConversions*/false);
6278  
6279    QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6280    if (LHS.isInvalid() || RHS.isInvalid())
6281      return QualType();
6282  
6283    QualType LHSTy = LHS.get()->getType();
6284    QualType RHSTy = RHS.get()->getType();
6285  
6286    // If both operands have arithmetic type, do the usual arithmetic conversions
6287    // to find a common type: C99 6.5.15p3,5.
6288    if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6289      LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6290      RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6291  
6292      return ResTy;
6293    }
6294  
6295    // If both operands are the same structure or union type, the result is that
6296    // type.
6297    if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6298      if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6299        if (LHSRT->getDecl() == RHSRT->getDecl())
6300          // "If both the operands have structure or union type, the result has
6301          // that type."  This implies that CV qualifiers are dropped.
6302          return LHSTy.getUnqualifiedType();
6303      // FIXME: Type of conditional expression must be complete in C mode.
6304    }
6305  
6306    // C99 6.5.15p5: "If both operands have void type, the result has void type."
6307    // The following || allows only one side to be void (a GCC-ism).
6308    if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6309      return checkConditionalVoidType(*this, LHS, RHS);
6310    }
6311  
6312    // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6313    // the type of the other operand."
6314    if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6315    if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6316  
6317    // All objective-c pointer type analysis is done here.
6318    QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6319                                                          QuestionLoc);
6320    if (LHS.isInvalid() || RHS.isInvalid())
6321      return QualType();
6322    if (!compositeType.isNull())
6323      return compositeType;
6324  
6325  
6326    // Handle block pointer types.
6327    if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6328      return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6329                                                       QuestionLoc);
6330  
6331    // Check constraints for C object pointers types (C99 6.5.15p3,6).
6332    if (LHSTy->isPointerType() && RHSTy->isPointerType())
6333      return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6334                                                         QuestionLoc);
6335  
6336    // GCC compatibility: soften pointer/integer mismatch.  Note that
6337    // null pointers have been filtered out by this point.
6338    if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6339        /*isIntFirstExpr=*/true))
6340      return RHSTy;
6341    if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6342        /*isIntFirstExpr=*/false))
6343      return LHSTy;
6344  
6345    // Emit a better diagnostic if one of the expressions is a null pointer
6346    // constant and the other is not a pointer type. In this case, the user most
6347    // likely forgot to take the address of the other expression.
6348    if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6349      return QualType();
6350  
6351    // Otherwise, the operands are not compatible.
6352    Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6353      << LHSTy << RHSTy << LHS.get()->getSourceRange()
6354      << RHS.get()->getSourceRange();
6355    return QualType();
6356  }
6357  
6358  /// FindCompositeObjCPointerType - Helper method to find composite type of
6359  /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)6360  QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6361                                              SourceLocation QuestionLoc) {
6362    QualType LHSTy = LHS.get()->getType();
6363    QualType RHSTy = RHS.get()->getType();
6364  
6365    // Handle things like Class and struct objc_class*.  Here we case the result
6366    // to the pseudo-builtin, because that will be implicitly cast back to the
6367    // redefinition type if an attempt is made to access its fields.
6368    if (LHSTy->isObjCClassType() &&
6369        (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6370      RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6371      return LHSTy;
6372    }
6373    if (RHSTy->isObjCClassType() &&
6374        (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6375      LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6376      return RHSTy;
6377    }
6378    // And the same for struct objc_object* / id
6379    if (LHSTy->isObjCIdType() &&
6380        (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6381      RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6382      return LHSTy;
6383    }
6384    if (RHSTy->isObjCIdType() &&
6385        (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6386      LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6387      return RHSTy;
6388    }
6389    // And the same for struct objc_selector* / SEL
6390    if (Context.isObjCSelType(LHSTy) &&
6391        (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6392      RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6393      return LHSTy;
6394    }
6395    if (Context.isObjCSelType(RHSTy) &&
6396        (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6397      LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6398      return RHSTy;
6399    }
6400    // Check constraints for Objective-C object pointers types.
6401    if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6402  
6403      if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6404        // Two identical object pointer types are always compatible.
6405        return LHSTy;
6406      }
6407      const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6408      const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6409      QualType compositeType = LHSTy;
6410  
6411      // If both operands are interfaces and either operand can be
6412      // assigned to the other, use that type as the composite
6413      // type. This allows
6414      //   xxx ? (A*) a : (B*) b
6415      // where B is a subclass of A.
6416      //
6417      // Additionally, as for assignment, if either type is 'id'
6418      // allow silent coercion. Finally, if the types are
6419      // incompatible then make sure to use 'id' as the composite
6420      // type so the result is acceptable for sending messages to.
6421  
6422      // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6423      // It could return the composite type.
6424      if (!(compositeType =
6425            Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6426        // Nothing more to do.
6427      } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6428        compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6429      } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6430        compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6431      } else if ((LHSTy->isObjCQualifiedIdType() ||
6432                  RHSTy->isObjCQualifiedIdType()) &&
6433                 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6434        // Need to handle "id<xx>" explicitly.
6435        // GCC allows qualified id and any Objective-C type to devolve to
6436        // id. Currently localizing to here until clear this should be
6437        // part of ObjCQualifiedIdTypesAreCompatible.
6438        compositeType = Context.getObjCIdType();
6439      } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6440        compositeType = Context.getObjCIdType();
6441      } else {
6442        Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6443        << LHSTy << RHSTy
6444        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6445        QualType incompatTy = Context.getObjCIdType();
6446        LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6447        RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6448        return incompatTy;
6449      }
6450      // The object pointer types are compatible.
6451      LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6452      RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6453      return compositeType;
6454    }
6455    // Check Objective-C object pointer types and 'void *'
6456    if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6457      if (getLangOpts().ObjCAutoRefCount) {
6458        // ARC forbids the implicit conversion of object pointers to 'void *',
6459        // so these types are not compatible.
6460        Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6461            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6462        LHS = RHS = true;
6463        return QualType();
6464      }
6465      QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6466      QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6467      QualType destPointee
6468      = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6469      QualType destType = Context.getPointerType(destPointee);
6470      // Add qualifiers if necessary.
6471      LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6472      // Promote to void*.
6473      RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6474      return destType;
6475    }
6476    if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6477      if (getLangOpts().ObjCAutoRefCount) {
6478        // ARC forbids the implicit conversion of object pointers to 'void *',
6479        // so these types are not compatible.
6480        Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6481            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6482        LHS = RHS = true;
6483        return QualType();
6484      }
6485      QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6486      QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6487      QualType destPointee
6488      = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6489      QualType destType = Context.getPointerType(destPointee);
6490      // Add qualifiers if necessary.
6491      RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6492      // Promote to void*.
6493      LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6494      return destType;
6495    }
6496    return QualType();
6497  }
6498  
6499  /// SuggestParentheses - Emit a note with a fixit hint that wraps
6500  /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)6501  static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6502                                 const PartialDiagnostic &Note,
6503                                 SourceRange ParenRange) {
6504    SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6505    if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6506        EndLoc.isValid()) {
6507      Self.Diag(Loc, Note)
6508        << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6509        << FixItHint::CreateInsertion(EndLoc, ")");
6510    } else {
6511      // We can't display the parentheses, so just show the bare note.
6512      Self.Diag(Loc, Note) << ParenRange;
6513    }
6514  }
6515  
IsArithmeticOp(BinaryOperatorKind Opc)6516  static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6517    return BinaryOperator::isAdditiveOp(Opc) ||
6518           BinaryOperator::isMultiplicativeOp(Opc) ||
6519           BinaryOperator::isShiftOp(Opc);
6520  }
6521  
6522  /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6523  /// expression, either using a built-in or overloaded operator,
6524  /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6525  /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)6526  static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6527                                     Expr **RHSExprs) {
6528    // Don't strip parenthesis: we should not warn if E is in parenthesis.
6529    E = E->IgnoreImpCasts();
6530    E = E->IgnoreConversionOperator();
6531    E = E->IgnoreImpCasts();
6532  
6533    // Built-in binary operator.
6534    if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6535      if (IsArithmeticOp(OP->getOpcode())) {
6536        *Opcode = OP->getOpcode();
6537        *RHSExprs = OP->getRHS();
6538        return true;
6539      }
6540    }
6541  
6542    // Overloaded operator.
6543    if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6544      if (Call->getNumArgs() != 2)
6545        return false;
6546  
6547      // Make sure this is really a binary operator that is safe to pass into
6548      // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6549      OverloadedOperatorKind OO = Call->getOperator();
6550      if (OO < OO_Plus || OO > OO_Arrow ||
6551          OO == OO_PlusPlus || OO == OO_MinusMinus)
6552        return false;
6553  
6554      BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6555      if (IsArithmeticOp(OpKind)) {
6556        *Opcode = OpKind;
6557        *RHSExprs = Call->getArg(1);
6558        return true;
6559      }
6560    }
6561  
6562    return false;
6563  }
6564  
6565  /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6566  /// or is a logical expression such as (x==y) which has int type, but is
6567  /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)6568  static bool ExprLooksBoolean(Expr *E) {
6569    E = E->IgnoreParenImpCasts();
6570  
6571    if (E->getType()->isBooleanType())
6572      return true;
6573    if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6574      return OP->isComparisonOp() || OP->isLogicalOp();
6575    if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6576      return OP->getOpcode() == UO_LNot;
6577    if (E->getType()->isPointerType())
6578      return true;
6579  
6580    return false;
6581  }
6582  
6583  /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6584  /// and binary operator are mixed in a way that suggests the programmer assumed
6585  /// the conditional operator has higher precedence, for example:
6586  /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)6587  static void DiagnoseConditionalPrecedence(Sema &Self,
6588                                            SourceLocation OpLoc,
6589                                            Expr *Condition,
6590                                            Expr *LHSExpr,
6591                                            Expr *RHSExpr) {
6592    BinaryOperatorKind CondOpcode;
6593    Expr *CondRHS;
6594  
6595    if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6596      return;
6597    if (!ExprLooksBoolean(CondRHS))
6598      return;
6599  
6600    // The condition is an arithmetic binary expression, with a right-
6601    // hand side that looks boolean, so warn.
6602  
6603    Self.Diag(OpLoc, diag::warn_precedence_conditional)
6604        << Condition->getSourceRange()
6605        << BinaryOperator::getOpcodeStr(CondOpcode);
6606  
6607    SuggestParentheses(Self, OpLoc,
6608      Self.PDiag(diag::note_precedence_silence)
6609        << BinaryOperator::getOpcodeStr(CondOpcode),
6610      SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6611  
6612    SuggestParentheses(Self, OpLoc,
6613      Self.PDiag(diag::note_precedence_conditional_first),
6614      SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6615  }
6616  
6617  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6618  /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)6619  ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6620                                      SourceLocation ColonLoc,
6621                                      Expr *CondExpr, Expr *LHSExpr,
6622                                      Expr *RHSExpr) {
6623    if (!getLangOpts().CPlusPlus) {
6624      // C cannot handle TypoExpr nodes in the condition because it
6625      // doesn't handle dependent types properly, so make sure any TypoExprs have
6626      // been dealt with before checking the operands.
6627      ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6628      if (!CondResult.isUsable()) return ExprError();
6629      CondExpr = CondResult.get();
6630    }
6631  
6632    // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6633    // was the condition.
6634    OpaqueValueExpr *opaqueValue = nullptr;
6635    Expr *commonExpr = nullptr;
6636    if (!LHSExpr) {
6637      commonExpr = CondExpr;
6638      // Lower out placeholder types first.  This is important so that we don't
6639      // try to capture a placeholder. This happens in few cases in C++; such
6640      // as Objective-C++'s dictionary subscripting syntax.
6641      if (commonExpr->hasPlaceholderType()) {
6642        ExprResult result = CheckPlaceholderExpr(commonExpr);
6643        if (!result.isUsable()) return ExprError();
6644        commonExpr = result.get();
6645      }
6646      // We usually want to apply unary conversions *before* saving, except
6647      // in the special case of a C++ l-value conditional.
6648      if (!(getLangOpts().CPlusPlus
6649            && !commonExpr->isTypeDependent()
6650            && commonExpr->getValueKind() == RHSExpr->getValueKind()
6651            && commonExpr->isGLValue()
6652            && commonExpr->isOrdinaryOrBitFieldObject()
6653            && RHSExpr->isOrdinaryOrBitFieldObject()
6654            && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6655        ExprResult commonRes = UsualUnaryConversions(commonExpr);
6656        if (commonRes.isInvalid())
6657          return ExprError();
6658        commonExpr = commonRes.get();
6659      }
6660  
6661      opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6662                                                  commonExpr->getType(),
6663                                                  commonExpr->getValueKind(),
6664                                                  commonExpr->getObjectKind(),
6665                                                  commonExpr);
6666      LHSExpr = CondExpr = opaqueValue;
6667    }
6668  
6669    ExprValueKind VK = VK_RValue;
6670    ExprObjectKind OK = OK_Ordinary;
6671    ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6672    QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6673                                               VK, OK, QuestionLoc);
6674    if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6675        RHS.isInvalid())
6676      return ExprError();
6677  
6678    DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6679                                  RHS.get());
6680  
6681    CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6682  
6683    if (!commonExpr)
6684      return new (Context)
6685          ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6686                              RHS.get(), result, VK, OK);
6687  
6688    return new (Context) BinaryConditionalOperator(
6689        commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6690        ColonLoc, result, VK, OK);
6691  }
6692  
6693  // checkPointerTypesForAssignment - This is a very tricky routine (despite
6694  // being closely modeled after the C99 spec:-). The odd characteristic of this
6695  // routine is it effectively iqnores the qualifiers on the top level pointee.
6696  // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6697  // FIXME: add a couple examples in this comment.
6698  static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6699  checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6700    assert(LHSType.isCanonical() && "LHS not canonicalized!");
6701    assert(RHSType.isCanonical() && "RHS not canonicalized!");
6702  
6703    // get the "pointed to" type (ignoring qualifiers at the top level)
6704    const Type *lhptee, *rhptee;
6705    Qualifiers lhq, rhq;
6706    std::tie(lhptee, lhq) =
6707        cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6708    std::tie(rhptee, rhq) =
6709        cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6710  
6711    Sema::AssignConvertType ConvTy = Sema::Compatible;
6712  
6713    // C99 6.5.16.1p1: This following citation is common to constraints
6714    // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6715    // qualifiers of the type *pointed to* by the right;
6716  
6717    // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6718    if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6719        lhq.compatiblyIncludesObjCLifetime(rhq)) {
6720      // Ignore lifetime for further calculation.
6721      lhq.removeObjCLifetime();
6722      rhq.removeObjCLifetime();
6723    }
6724  
6725    if (!lhq.compatiblyIncludes(rhq)) {
6726      // Treat address-space mismatches as fatal.  TODO: address subspaces
6727      if (!lhq.isAddressSpaceSupersetOf(rhq))
6728        ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6729  
6730      // It's okay to add or remove GC or lifetime qualifiers when converting to
6731      // and from void*.
6732      else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6733                          .compatiblyIncludes(
6734                                  rhq.withoutObjCGCAttr().withoutObjCLifetime())
6735               && (lhptee->isVoidType() || rhptee->isVoidType()))
6736        ; // keep old
6737  
6738      // Treat lifetime mismatches as fatal.
6739      else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6740        ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6741  
6742      // For GCC compatibility, other qualifier mismatches are treated
6743      // as still compatible in C.
6744      else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6745    }
6746  
6747    // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6748    // incomplete type and the other is a pointer to a qualified or unqualified
6749    // version of void...
6750    if (lhptee->isVoidType()) {
6751      if (rhptee->isIncompleteOrObjectType())
6752        return ConvTy;
6753  
6754      // As an extension, we allow cast to/from void* to function pointer.
6755      assert(rhptee->isFunctionType());
6756      return Sema::FunctionVoidPointer;
6757    }
6758  
6759    if (rhptee->isVoidType()) {
6760      if (lhptee->isIncompleteOrObjectType())
6761        return ConvTy;
6762  
6763      // As an extension, we allow cast to/from void* to function pointer.
6764      assert(lhptee->isFunctionType());
6765      return Sema::FunctionVoidPointer;
6766    }
6767  
6768    // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6769    // unqualified versions of compatible types, ...
6770    QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6771    if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6772      // Check if the pointee types are compatible ignoring the sign.
6773      // We explicitly check for char so that we catch "char" vs
6774      // "unsigned char" on systems where "char" is unsigned.
6775      if (lhptee->isCharType())
6776        ltrans = S.Context.UnsignedCharTy;
6777      else if (lhptee->hasSignedIntegerRepresentation())
6778        ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6779  
6780      if (rhptee->isCharType())
6781        rtrans = S.Context.UnsignedCharTy;
6782      else if (rhptee->hasSignedIntegerRepresentation())
6783        rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6784  
6785      if (ltrans == rtrans) {
6786        // Types are compatible ignoring the sign. Qualifier incompatibility
6787        // takes priority over sign incompatibility because the sign
6788        // warning can be disabled.
6789        if (ConvTy != Sema::Compatible)
6790          return ConvTy;
6791  
6792        return Sema::IncompatiblePointerSign;
6793      }
6794  
6795      // If we are a multi-level pointer, it's possible that our issue is simply
6796      // one of qualification - e.g. char ** -> const char ** is not allowed. If
6797      // the eventual target type is the same and the pointers have the same
6798      // level of indirection, this must be the issue.
6799      if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6800        do {
6801          lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6802          rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6803        } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6804  
6805        if (lhptee == rhptee)
6806          return Sema::IncompatibleNestedPointerQualifiers;
6807      }
6808  
6809      // General pointer incompatibility takes priority over qualifiers.
6810      return Sema::IncompatiblePointer;
6811    }
6812    if (!S.getLangOpts().CPlusPlus &&
6813        S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6814      return Sema::IncompatiblePointer;
6815    return ConvTy;
6816  }
6817  
6818  /// checkBlockPointerTypesForAssignment - This routine determines whether two
6819  /// block pointer types are compatible or whether a block and normal pointer
6820  /// are compatible. It is more restrict than comparing two function pointer
6821  // types.
6822  static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6823  checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6824                                      QualType RHSType) {
6825    assert(LHSType.isCanonical() && "LHS not canonicalized!");
6826    assert(RHSType.isCanonical() && "RHS not canonicalized!");
6827  
6828    QualType lhptee, rhptee;
6829  
6830    // get the "pointed to" type (ignoring qualifiers at the top level)
6831    lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6832    rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6833  
6834    // In C++, the types have to match exactly.
6835    if (S.getLangOpts().CPlusPlus)
6836      return Sema::IncompatibleBlockPointer;
6837  
6838    Sema::AssignConvertType ConvTy = Sema::Compatible;
6839  
6840    // For blocks we enforce that qualifiers are identical.
6841    if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6842      ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6843  
6844    if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6845      return Sema::IncompatibleBlockPointer;
6846  
6847    return ConvTy;
6848  }
6849  
6850  /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6851  /// for assignment compatibility.
6852  static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)6853  checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6854                                     QualType RHSType) {
6855    assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6856    assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6857  
6858    if (LHSType->isObjCBuiltinType()) {
6859      // Class is not compatible with ObjC object pointers.
6860      if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6861          !RHSType->isObjCQualifiedClassType())
6862        return Sema::IncompatiblePointer;
6863      return Sema::Compatible;
6864    }
6865    if (RHSType->isObjCBuiltinType()) {
6866      if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6867          !LHSType->isObjCQualifiedClassType())
6868        return Sema::IncompatiblePointer;
6869      return Sema::Compatible;
6870    }
6871    QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6872    QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6873  
6874    if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6875        // make an exception for id<P>
6876        !LHSType->isObjCQualifiedIdType())
6877      return Sema::CompatiblePointerDiscardsQualifiers;
6878  
6879    if (S.Context.typesAreCompatible(LHSType, RHSType))
6880      return Sema::Compatible;
6881    if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6882      return Sema::IncompatibleObjCQualifiedId;
6883    return Sema::IncompatiblePointer;
6884  }
6885  
6886  Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)6887  Sema::CheckAssignmentConstraints(SourceLocation Loc,
6888                                   QualType LHSType, QualType RHSType) {
6889    // Fake up an opaque expression.  We don't actually care about what
6890    // cast operations are required, so if CheckAssignmentConstraints
6891    // adds casts to this they'll be wasted, but fortunately that doesn't
6892    // usually happen on valid code.
6893    OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6894    ExprResult RHSPtr = &RHSExpr;
6895    CastKind K = CK_Invalid;
6896  
6897    return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
6898  }
6899  
6900  /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6901  /// has code to accommodate several GCC extensions when type checking
6902  /// pointers. Here are some objectionable examples that GCC considers warnings:
6903  ///
6904  ///  int a, *pint;
6905  ///  short *pshort;
6906  ///  struct foo *pfoo;
6907  ///
6908  ///  pint = pshort; // warning: assignment from incompatible pointer type
6909  ///  a = pint; // warning: assignment makes integer from pointer without a cast
6910  ///  pint = a; // warning: assignment makes pointer from integer without a cast
6911  ///  pint = pfoo; // warning: assignment from incompatible pointer type
6912  ///
6913  /// As a result, the code for dealing with pointers is more complex than the
6914  /// C99 spec dictates.
6915  ///
6916  /// Sets 'Kind' for any result kind except Incompatible.
6917  Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)6918  Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6919                                   CastKind &Kind, bool ConvertRHS) {
6920    QualType RHSType = RHS.get()->getType();
6921    QualType OrigLHSType = LHSType;
6922  
6923    // Get canonical types.  We're not formatting these types, just comparing
6924    // them.
6925    LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6926    RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6927  
6928    // Common case: no conversion required.
6929    if (LHSType == RHSType) {
6930      Kind = CK_NoOp;
6931      return Compatible;
6932    }
6933  
6934    // If we have an atomic type, try a non-atomic assignment, then just add an
6935    // atomic qualification step.
6936    if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6937      Sema::AssignConvertType result =
6938        CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6939      if (result != Compatible)
6940        return result;
6941      if (Kind != CK_NoOp && ConvertRHS)
6942        RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6943      Kind = CK_NonAtomicToAtomic;
6944      return Compatible;
6945    }
6946  
6947    // If the left-hand side is a reference type, then we are in a
6948    // (rare!) case where we've allowed the use of references in C,
6949    // e.g., as a parameter type in a built-in function. In this case,
6950    // just make sure that the type referenced is compatible with the
6951    // right-hand side type. The caller is responsible for adjusting
6952    // LHSType so that the resulting expression does not have reference
6953    // type.
6954    if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6955      if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6956        Kind = CK_LValueBitCast;
6957        return Compatible;
6958      }
6959      return Incompatible;
6960    }
6961  
6962    // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6963    // to the same ExtVector type.
6964    if (LHSType->isExtVectorType()) {
6965      if (RHSType->isExtVectorType())
6966        return Incompatible;
6967      if (RHSType->isArithmeticType()) {
6968        // CK_VectorSplat does T -> vector T, so first cast to the
6969        // element type.
6970        QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6971        if (elType != RHSType && ConvertRHS) {
6972          Kind = PrepareScalarCast(RHS, elType);
6973          RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6974        }
6975        Kind = CK_VectorSplat;
6976        return Compatible;
6977      }
6978    }
6979  
6980    // Conversions to or from vector type.
6981    if (LHSType->isVectorType() || RHSType->isVectorType()) {
6982      if (LHSType->isVectorType() && RHSType->isVectorType()) {
6983        // Allow assignments of an AltiVec vector type to an equivalent GCC
6984        // vector type and vice versa
6985        if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6986          Kind = CK_BitCast;
6987          return Compatible;
6988        }
6989  
6990        // If we are allowing lax vector conversions, and LHS and RHS are both
6991        // vectors, the total size only needs to be the same. This is a bitcast;
6992        // no bits are changed but the result type is different.
6993        if (isLaxVectorConversion(RHSType, LHSType)) {
6994          Kind = CK_BitCast;
6995          return IncompatibleVectors;
6996        }
6997      }
6998      return Incompatible;
6999    }
7000  
7001    // Arithmetic conversions.
7002    if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7003        !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7004      if (ConvertRHS)
7005        Kind = PrepareScalarCast(RHS, LHSType);
7006      return Compatible;
7007    }
7008  
7009    // Conversions to normal pointers.
7010    if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7011      // U* -> T*
7012      if (isa<PointerType>(RHSType)) {
7013        unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7014        unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7015        Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7016        return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7017      }
7018  
7019      // int -> T*
7020      if (RHSType->isIntegerType()) {
7021        Kind = CK_IntegralToPointer; // FIXME: null?
7022        return IntToPointer;
7023      }
7024  
7025      // C pointers are not compatible with ObjC object pointers,
7026      // with two exceptions:
7027      if (isa<ObjCObjectPointerType>(RHSType)) {
7028        //  - conversions to void*
7029        if (LHSPointer->getPointeeType()->isVoidType()) {
7030          Kind = CK_BitCast;
7031          return Compatible;
7032        }
7033  
7034        //  - conversions from 'Class' to the redefinition type
7035        if (RHSType->isObjCClassType() &&
7036            Context.hasSameType(LHSType,
7037                                Context.getObjCClassRedefinitionType())) {
7038          Kind = CK_BitCast;
7039          return Compatible;
7040        }
7041  
7042        Kind = CK_BitCast;
7043        return IncompatiblePointer;
7044      }
7045  
7046      // U^ -> void*
7047      if (RHSType->getAs<BlockPointerType>()) {
7048        if (LHSPointer->getPointeeType()->isVoidType()) {
7049          Kind = CK_BitCast;
7050          return Compatible;
7051        }
7052      }
7053  
7054      return Incompatible;
7055    }
7056  
7057    // Conversions to block pointers.
7058    if (isa<BlockPointerType>(LHSType)) {
7059      // U^ -> T^
7060      if (RHSType->isBlockPointerType()) {
7061        Kind = CK_BitCast;
7062        return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7063      }
7064  
7065      // int or null -> T^
7066      if (RHSType->isIntegerType()) {
7067        Kind = CK_IntegralToPointer; // FIXME: null
7068        return IntToBlockPointer;
7069      }
7070  
7071      // id -> T^
7072      if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7073        Kind = CK_AnyPointerToBlockPointerCast;
7074        return Compatible;
7075      }
7076  
7077      // void* -> T^
7078      if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7079        if (RHSPT->getPointeeType()->isVoidType()) {
7080          Kind = CK_AnyPointerToBlockPointerCast;
7081          return Compatible;
7082        }
7083  
7084      return Incompatible;
7085    }
7086  
7087    // Conversions to Objective-C pointers.
7088    if (isa<ObjCObjectPointerType>(LHSType)) {
7089      // A* -> B*
7090      if (RHSType->isObjCObjectPointerType()) {
7091        Kind = CK_BitCast;
7092        Sema::AssignConvertType result =
7093          checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7094        if (getLangOpts().ObjCAutoRefCount &&
7095            result == Compatible &&
7096            !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7097          result = IncompatibleObjCWeakRef;
7098        return result;
7099      }
7100  
7101      // int or null -> A*
7102      if (RHSType->isIntegerType()) {
7103        Kind = CK_IntegralToPointer; // FIXME: null
7104        return IntToPointer;
7105      }
7106  
7107      // In general, C pointers are not compatible with ObjC object pointers,
7108      // with two exceptions:
7109      if (isa<PointerType>(RHSType)) {
7110        Kind = CK_CPointerToObjCPointerCast;
7111  
7112        //  - conversions from 'void*'
7113        if (RHSType->isVoidPointerType()) {
7114          return Compatible;
7115        }
7116  
7117        //  - conversions to 'Class' from its redefinition type
7118        if (LHSType->isObjCClassType() &&
7119            Context.hasSameType(RHSType,
7120                                Context.getObjCClassRedefinitionType())) {
7121          return Compatible;
7122        }
7123  
7124        return IncompatiblePointer;
7125      }
7126  
7127      // Only under strict condition T^ is compatible with an Objective-C pointer.
7128      if (RHSType->isBlockPointerType() &&
7129          LHSType->isBlockCompatibleObjCPointerType(Context)) {
7130        if (ConvertRHS)
7131          maybeExtendBlockObject(RHS);
7132        Kind = CK_BlockPointerToObjCPointerCast;
7133        return Compatible;
7134      }
7135  
7136      return Incompatible;
7137    }
7138  
7139    // Conversions from pointers that are not covered by the above.
7140    if (isa<PointerType>(RHSType)) {
7141      // T* -> _Bool
7142      if (LHSType == Context.BoolTy) {
7143        Kind = CK_PointerToBoolean;
7144        return Compatible;
7145      }
7146  
7147      // T* -> int
7148      if (LHSType->isIntegerType()) {
7149        Kind = CK_PointerToIntegral;
7150        return PointerToInt;
7151      }
7152  
7153      return Incompatible;
7154    }
7155  
7156    // Conversions from Objective-C pointers that are not covered by the above.
7157    if (isa<ObjCObjectPointerType>(RHSType)) {
7158      // T* -> _Bool
7159      if (LHSType == Context.BoolTy) {
7160        Kind = CK_PointerToBoolean;
7161        return Compatible;
7162      }
7163  
7164      // T* -> int
7165      if (LHSType->isIntegerType()) {
7166        Kind = CK_PointerToIntegral;
7167        return PointerToInt;
7168      }
7169  
7170      return Incompatible;
7171    }
7172  
7173    // struct A -> struct B
7174    if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7175      if (Context.typesAreCompatible(LHSType, RHSType)) {
7176        Kind = CK_NoOp;
7177        return Compatible;
7178      }
7179    }
7180  
7181    return Incompatible;
7182  }
7183  
7184  /// \brief Constructs a transparent union from an expression that is
7185  /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)7186  static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7187                                        ExprResult &EResult, QualType UnionType,
7188                                        FieldDecl *Field) {
7189    // Build an initializer list that designates the appropriate member
7190    // of the transparent union.
7191    Expr *E = EResult.get();
7192    InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7193                                                     E, SourceLocation());
7194    Initializer->setType(UnionType);
7195    Initializer->setInitializedFieldInUnion(Field);
7196  
7197    // Build a compound literal constructing a value of the transparent
7198    // union type from this initializer list.
7199    TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7200    EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7201                                          VK_RValue, Initializer, false);
7202  }
7203  
7204  Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)7205  Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7206                                                 ExprResult &RHS) {
7207    QualType RHSType = RHS.get()->getType();
7208  
7209    // If the ArgType is a Union type, we want to handle a potential
7210    // transparent_union GCC extension.
7211    const RecordType *UT = ArgType->getAsUnionType();
7212    if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7213      return Incompatible;
7214  
7215    // The field to initialize within the transparent union.
7216    RecordDecl *UD = UT->getDecl();
7217    FieldDecl *InitField = nullptr;
7218    // It's compatible if the expression matches any of the fields.
7219    for (auto *it : UD->fields()) {
7220      if (it->getType()->isPointerType()) {
7221        // If the transparent union contains a pointer type, we allow:
7222        // 1) void pointer
7223        // 2) null pointer constant
7224        if (RHSType->isPointerType())
7225          if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7226            RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7227            InitField = it;
7228            break;
7229          }
7230  
7231        if (RHS.get()->isNullPointerConstant(Context,
7232                                             Expr::NPC_ValueDependentIsNull)) {
7233          RHS = ImpCastExprToType(RHS.get(), it->getType(),
7234                                  CK_NullToPointer);
7235          InitField = it;
7236          break;
7237        }
7238      }
7239  
7240      CastKind Kind = CK_Invalid;
7241      if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7242            == Compatible) {
7243        RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7244        InitField = it;
7245        break;
7246      }
7247    }
7248  
7249    if (!InitField)
7250      return Incompatible;
7251  
7252    ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7253    return Compatible;
7254  }
7255  
7256  Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)7257  Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7258                                         bool Diagnose,
7259                                         bool DiagnoseCFAudited,
7260                                         bool ConvertRHS) {
7261    // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7262    // we can't avoid *all* modifications at the moment, so we need some somewhere
7263    // to put the updated value.
7264    ExprResult LocalRHS = CallerRHS;
7265    ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7266  
7267    if (getLangOpts().CPlusPlus) {
7268      if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7269        // C++ 5.17p3: If the left operand is not of class type, the
7270        // expression is implicitly converted (C++ 4) to the
7271        // cv-unqualified type of the left operand.
7272        ExprResult Res;
7273        if (Diagnose) {
7274          Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7275                                          AA_Assigning);
7276        } else {
7277          ImplicitConversionSequence ICS =
7278              TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7279                                    /*SuppressUserConversions=*/false,
7280                                    /*AllowExplicit=*/false,
7281                                    /*InOverloadResolution=*/false,
7282                                    /*CStyle=*/false,
7283                                    /*AllowObjCWritebackConversion=*/false);
7284          if (ICS.isFailure())
7285            return Incompatible;
7286          Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7287                                          ICS, AA_Assigning);
7288        }
7289        if (Res.isInvalid())
7290          return Incompatible;
7291        Sema::AssignConvertType result = Compatible;
7292        if (getLangOpts().ObjCAutoRefCount &&
7293            !CheckObjCARCUnavailableWeakConversion(LHSType,
7294                                                   RHS.get()->getType()))
7295          result = IncompatibleObjCWeakRef;
7296        RHS = Res;
7297        return result;
7298      }
7299  
7300      // FIXME: Currently, we fall through and treat C++ classes like C
7301      // structures.
7302      // FIXME: We also fall through for atomics; not sure what should
7303      // happen there, though.
7304    } else if (RHS.get()->getType() == Context.OverloadTy) {
7305      // As a set of extensions to C, we support overloading on functions. These
7306      // functions need to be resolved here.
7307      DeclAccessPair DAP;
7308      if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7309              RHS.get(), LHSType, /*Complain=*/false, DAP))
7310        RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7311      else
7312        return Incompatible;
7313    }
7314  
7315    // C99 6.5.16.1p1: the left operand is a pointer and the right is
7316    // a null pointer constant.
7317    if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7318         LHSType->isBlockPointerType()) &&
7319        RHS.get()->isNullPointerConstant(Context,
7320                                         Expr::NPC_ValueDependentIsNull)) {
7321      CastKind Kind;
7322      CXXCastPath Path;
7323      CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
7324      if (ConvertRHS)
7325        RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7326      return Compatible;
7327    }
7328  
7329    // This check seems unnatural, however it is necessary to ensure the proper
7330    // conversion of functions/arrays. If the conversion were done for all
7331    // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7332    // expressions that suppress this implicit conversion (&, sizeof).
7333    //
7334    // Suppress this for references: C++ 8.5.3p5.
7335    if (!LHSType->isReferenceType()) {
7336      // FIXME: We potentially allocate here even if ConvertRHS is false.
7337      RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7338      if (RHS.isInvalid())
7339        return Incompatible;
7340    }
7341  
7342    Expr *PRE = RHS.get()->IgnoreParenCasts();
7343    if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7344      ObjCProtocolDecl *PDecl = OPE->getProtocol();
7345      if (PDecl && !PDecl->hasDefinition()) {
7346        Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7347        Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7348      }
7349    }
7350  
7351    CastKind Kind = CK_Invalid;
7352    Sema::AssignConvertType result =
7353      CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7354  
7355    // C99 6.5.16.1p2: The value of the right operand is converted to the
7356    // type of the assignment expression.
7357    // CheckAssignmentConstraints allows the left-hand side to be a reference,
7358    // so that we can use references in built-in functions even in C.
7359    // The getNonReferenceType() call makes sure that the resulting expression
7360    // does not have reference type.
7361    if (result != Incompatible && RHS.get()->getType() != LHSType) {
7362      QualType Ty = LHSType.getNonLValueExprType(Context);
7363      Expr *E = RHS.get();
7364      if (getLangOpts().ObjCAutoRefCount)
7365        CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7366                               DiagnoseCFAudited);
7367      if (getLangOpts().ObjC1 &&
7368          (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7369                                            LHSType, E->getType(), E) ||
7370           ConversionToObjCStringLiteralCheck(LHSType, E))) {
7371        RHS = E;
7372        return Compatible;
7373      }
7374  
7375      if (ConvertRHS)
7376        RHS = ImpCastExprToType(E, Ty, Kind);
7377    }
7378    return result;
7379  }
7380  
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)7381  QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7382                                 ExprResult &RHS) {
7383    Diag(Loc, diag::err_typecheck_invalid_operands)
7384      << LHS.get()->getType() << RHS.get()->getType()
7385      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7386    return QualType();
7387  }
7388  
7389  /// Try to convert a value of non-vector type to a vector type by converting
7390  /// the type to the element type of the vector and then performing a splat.
7391  /// If the language is OpenCL, we only use conversions that promote scalar
7392  /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7393  /// for float->int.
7394  ///
7395  /// \param scalar - if non-null, actually perform the conversions
7396  /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy)7397  static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7398                                       QualType scalarTy,
7399                                       QualType vectorEltTy,
7400                                       QualType vectorTy) {
7401    // The conversion to apply to the scalar before splatting it,
7402    // if necessary.
7403    CastKind scalarCast = CK_Invalid;
7404  
7405    if (vectorEltTy->isIntegralType(S.Context)) {
7406      if (!scalarTy->isIntegralType(S.Context))
7407        return true;
7408      if (S.getLangOpts().OpenCL &&
7409          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7410        return true;
7411      scalarCast = CK_IntegralCast;
7412    } else if (vectorEltTy->isRealFloatingType()) {
7413      if (scalarTy->isRealFloatingType()) {
7414        if (S.getLangOpts().OpenCL &&
7415            S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7416          return true;
7417        scalarCast = CK_FloatingCast;
7418      }
7419      else if (scalarTy->isIntegralType(S.Context))
7420        scalarCast = CK_IntegralToFloating;
7421      else
7422        return true;
7423    } else {
7424      return true;
7425    }
7426  
7427    // Adjust scalar if desired.
7428    if (scalar) {
7429      if (scalarCast != CK_Invalid)
7430        *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7431      *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7432    }
7433    return false;
7434  }
7435  
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)7436  QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7437                                     SourceLocation Loc, bool IsCompAssign,
7438                                     bool AllowBothBool,
7439                                     bool AllowBoolConversions) {
7440    if (!IsCompAssign) {
7441      LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7442      if (LHS.isInvalid())
7443        return QualType();
7444    }
7445    RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7446    if (RHS.isInvalid())
7447      return QualType();
7448  
7449    // For conversion purposes, we ignore any qualifiers.
7450    // For example, "const float" and "float" are equivalent.
7451    QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7452    QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7453  
7454    const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7455    const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7456    assert(LHSVecType || RHSVecType);
7457  
7458    // AltiVec-style "vector bool op vector bool" combinations are allowed
7459    // for some operators but not others.
7460    if (!AllowBothBool &&
7461        LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7462        RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7463      return InvalidOperands(Loc, LHS, RHS);
7464  
7465    // If the vector types are identical, return.
7466    if (Context.hasSameType(LHSType, RHSType))
7467      return LHSType;
7468  
7469    // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7470    if (LHSVecType && RHSVecType &&
7471        Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7472      if (isa<ExtVectorType>(LHSVecType)) {
7473        RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7474        return LHSType;
7475      }
7476  
7477      if (!IsCompAssign)
7478        LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7479      return RHSType;
7480    }
7481  
7482    // AllowBoolConversions says that bool and non-bool AltiVec vectors
7483    // can be mixed, with the result being the non-bool type.  The non-bool
7484    // operand must have integer element type.
7485    if (AllowBoolConversions && LHSVecType && RHSVecType &&
7486        LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7487        (Context.getTypeSize(LHSVecType->getElementType()) ==
7488         Context.getTypeSize(RHSVecType->getElementType()))) {
7489      if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7490          LHSVecType->getElementType()->isIntegerType() &&
7491          RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7492        RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7493        return LHSType;
7494      }
7495      if (!IsCompAssign &&
7496          LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7497          RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7498          RHSVecType->getElementType()->isIntegerType()) {
7499        LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7500        return RHSType;
7501      }
7502    }
7503  
7504    // If there's an ext-vector type and a scalar, try to convert the scalar to
7505    // the vector element type and splat.
7506    if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7507      if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7508                                    LHSVecType->getElementType(), LHSType))
7509        return LHSType;
7510    }
7511    if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7512      if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7513                                    LHSType, RHSVecType->getElementType(),
7514                                    RHSType))
7515        return RHSType;
7516    }
7517  
7518    // If we're allowing lax vector conversions, only the total (data) size
7519    // needs to be the same.
7520    // FIXME: Should we really be allowing this?
7521    // FIXME: We really just pick the LHS type arbitrarily?
7522    if (isLaxVectorConversion(RHSType, LHSType)) {
7523      QualType resultType = LHSType;
7524      RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7525      return resultType;
7526    }
7527  
7528    // Okay, the expression is invalid.
7529  
7530    // If there's a non-vector, non-real operand, diagnose that.
7531    if ((!RHSVecType && !RHSType->isRealType()) ||
7532        (!LHSVecType && !LHSType->isRealType())) {
7533      Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7534        << LHSType << RHSType
7535        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7536      return QualType();
7537    }
7538  
7539    // OpenCL V1.1 6.2.6.p1:
7540    // If the operands are of more than one vector type, then an error shall
7541    // occur. Implicit conversions between vector types are not permitted, per
7542    // section 6.2.1.
7543    if (getLangOpts().OpenCL &&
7544        RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7545        LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7546      Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7547                                                             << RHSType;
7548      return QualType();
7549    }
7550  
7551    // Otherwise, use the generic diagnostic.
7552    Diag(Loc, diag::err_typecheck_vector_not_convertable)
7553      << LHSType << RHSType
7554      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7555    return QualType();
7556  }
7557  
7558  // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7559  // expression.  These are mainly cases where the null pointer is used as an
7560  // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)7561  static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7562                                  SourceLocation Loc, bool IsCompare) {
7563    // The canonical way to check for a GNU null is with isNullPointerConstant,
7564    // but we use a bit of a hack here for speed; this is a relatively
7565    // hot path, and isNullPointerConstant is slow.
7566    bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7567    bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7568  
7569    QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7570  
7571    // Avoid analyzing cases where the result will either be invalid (and
7572    // diagnosed as such) or entirely valid and not something to warn about.
7573    if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7574        NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7575      return;
7576  
7577    // Comparison operations would not make sense with a null pointer no matter
7578    // what the other expression is.
7579    if (!IsCompare) {
7580      S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7581          << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7582          << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7583      return;
7584    }
7585  
7586    // The rest of the operations only make sense with a null pointer
7587    // if the other expression is a pointer.
7588    if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7589        NonNullType->canDecayToPointerType())
7590      return;
7591  
7592    S.Diag(Loc, diag::warn_null_in_comparison_operation)
7593        << LHSNull /* LHS is NULL */ << NonNullType
7594        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7595  }
7596  
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)7597  static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7598                                                 ExprResult &RHS,
7599                                                 SourceLocation Loc, bool IsDiv) {
7600    // Check for division/remainder by zero.
7601    llvm::APSInt RHSValue;
7602    if (!RHS.get()->isValueDependent() &&
7603        RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7604      S.DiagRuntimeBehavior(Loc, RHS.get(),
7605                            S.PDiag(diag::warn_remainder_division_by_zero)
7606                              << IsDiv << RHS.get()->getSourceRange());
7607  }
7608  
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)7609  QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7610                                             SourceLocation Loc,
7611                                             bool IsCompAssign, bool IsDiv) {
7612    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7613  
7614    if (LHS.get()->getType()->isVectorType() ||
7615        RHS.get()->getType()->isVectorType())
7616      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7617                                 /*AllowBothBool*/getLangOpts().AltiVec,
7618                                 /*AllowBoolConversions*/false);
7619  
7620    QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7621    if (LHS.isInvalid() || RHS.isInvalid())
7622      return QualType();
7623  
7624  
7625    if (compType.isNull() || !compType->isArithmeticType())
7626      return InvalidOperands(Loc, LHS, RHS);
7627    if (IsDiv)
7628      DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
7629    return compType;
7630  }
7631  
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)7632  QualType Sema::CheckRemainderOperands(
7633    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7634    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7635  
7636    if (LHS.get()->getType()->isVectorType() ||
7637        RHS.get()->getType()->isVectorType()) {
7638      if (LHS.get()->getType()->hasIntegerRepresentation() &&
7639          RHS.get()->getType()->hasIntegerRepresentation())
7640        return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7641                                   /*AllowBothBool*/getLangOpts().AltiVec,
7642                                   /*AllowBoolConversions*/false);
7643      return InvalidOperands(Loc, LHS, RHS);
7644    }
7645  
7646    QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7647    if (LHS.isInvalid() || RHS.isInvalid())
7648      return QualType();
7649  
7650    if (compType.isNull() || !compType->isIntegerType())
7651      return InvalidOperands(Loc, LHS, RHS);
7652    DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
7653    return compType;
7654  }
7655  
7656  /// \brief Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7657  static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7658                                                  Expr *LHSExpr, Expr *RHSExpr) {
7659    S.Diag(Loc, S.getLangOpts().CPlusPlus
7660                  ? diag::err_typecheck_pointer_arith_void_type
7661                  : diag::ext_gnu_void_ptr)
7662      << 1 /* two pointers */ << LHSExpr->getSourceRange()
7663                              << RHSExpr->getSourceRange();
7664  }
7665  
7666  /// \brief Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7667  static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7668                                              Expr *Pointer) {
7669    S.Diag(Loc, S.getLangOpts().CPlusPlus
7670                  ? diag::err_typecheck_pointer_arith_void_type
7671                  : diag::ext_gnu_void_ptr)
7672      << 0 /* one pointer */ << Pointer->getSourceRange();
7673  }
7674  
7675  /// \brief Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)7676  static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7677                                                      Expr *LHS, Expr *RHS) {
7678    assert(LHS->getType()->isAnyPointerType());
7679    assert(RHS->getType()->isAnyPointerType());
7680    S.Diag(Loc, S.getLangOpts().CPlusPlus
7681                  ? diag::err_typecheck_pointer_arith_function_type
7682                  : diag::ext_gnu_ptr_func_arith)
7683      << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7684      // We only show the second type if it differs from the first.
7685      << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7686                                                     RHS->getType())
7687      << RHS->getType()->getPointeeType()
7688      << LHS->getSourceRange() << RHS->getSourceRange();
7689  }
7690  
7691  /// \brief Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)7692  static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7693                                                  Expr *Pointer) {
7694    assert(Pointer->getType()->isAnyPointerType());
7695    S.Diag(Loc, S.getLangOpts().CPlusPlus
7696                  ? diag::err_typecheck_pointer_arith_function_type
7697                  : diag::ext_gnu_ptr_func_arith)
7698      << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7699      << 0 /* one pointer, so only one type */
7700      << Pointer->getSourceRange();
7701  }
7702  
7703  /// \brief Emit error if Operand is incomplete pointer type
7704  ///
7705  /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)7706  static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7707                                                   Expr *Operand) {
7708    QualType ResType = Operand->getType();
7709    if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7710      ResType = ResAtomicType->getValueType();
7711  
7712    assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7713    QualType PointeeTy = ResType->getPointeeType();
7714    return S.RequireCompleteType(Loc, PointeeTy,
7715                                 diag::err_typecheck_arithmetic_incomplete_type,
7716                                 PointeeTy, Operand->getSourceRange());
7717  }
7718  
7719  /// \brief Check the validity of an arithmetic pointer operand.
7720  ///
7721  /// If the operand has pointer type, this code will check for pointer types
7722  /// which are invalid in arithmetic operations. These will be diagnosed
7723  /// appropriately, including whether or not the use is supported as an
7724  /// extension.
7725  ///
7726  /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)7727  static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7728                                              Expr *Operand) {
7729    QualType ResType = Operand->getType();
7730    if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7731      ResType = ResAtomicType->getValueType();
7732  
7733    if (!ResType->isAnyPointerType()) return true;
7734  
7735    QualType PointeeTy = ResType->getPointeeType();
7736    if (PointeeTy->isVoidType()) {
7737      diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7738      return !S.getLangOpts().CPlusPlus;
7739    }
7740    if (PointeeTy->isFunctionType()) {
7741      diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7742      return !S.getLangOpts().CPlusPlus;
7743    }
7744  
7745    if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7746  
7747    return true;
7748  }
7749  
7750  /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7751  /// operands.
7752  ///
7753  /// This routine will diagnose any invalid arithmetic on pointer operands much
7754  /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7755  /// for emitting a single diagnostic even for operations where both LHS and RHS
7756  /// are (potentially problematic) pointers.
7757  ///
7758  /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7759  static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7760                                                  Expr *LHSExpr, Expr *RHSExpr) {
7761    bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7762    bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7763    if (!isLHSPointer && !isRHSPointer) return true;
7764  
7765    QualType LHSPointeeTy, RHSPointeeTy;
7766    if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7767    if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7768  
7769    // if both are pointers check if operation is valid wrt address spaces
7770    if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
7771      const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7772      const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7773      if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7774        S.Diag(Loc,
7775               diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7776            << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7777            << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7778        return false;
7779      }
7780    }
7781  
7782    // Check for arithmetic on pointers to incomplete types.
7783    bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7784    bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7785    if (isLHSVoidPtr || isRHSVoidPtr) {
7786      if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7787      else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7788      else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7789  
7790      return !S.getLangOpts().CPlusPlus;
7791    }
7792  
7793    bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7794    bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7795    if (isLHSFuncPtr || isRHSFuncPtr) {
7796      if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7797      else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7798                                                                  RHSExpr);
7799      else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7800  
7801      return !S.getLangOpts().CPlusPlus;
7802    }
7803  
7804    if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7805      return false;
7806    if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7807      return false;
7808  
7809    return true;
7810  }
7811  
7812  /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7813  /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7814  static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7815                                    Expr *LHSExpr, Expr *RHSExpr) {
7816    StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7817    Expr* IndexExpr = RHSExpr;
7818    if (!StrExpr) {
7819      StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7820      IndexExpr = LHSExpr;
7821    }
7822  
7823    bool IsStringPlusInt = StrExpr &&
7824        IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7825    if (!IsStringPlusInt || IndexExpr->isValueDependent())
7826      return;
7827  
7828    llvm::APSInt index;
7829    if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7830      unsigned StrLenWithNull = StrExpr->getLength() + 1;
7831      if (index.isNonNegative() &&
7832          index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7833                                index.isUnsigned()))
7834        return;
7835    }
7836  
7837    SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7838    Self.Diag(OpLoc, diag::warn_string_plus_int)
7839        << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7840  
7841    // Only print a fixit for "str" + int, not for int + "str".
7842    if (IndexExpr == RHSExpr) {
7843      SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7844      Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7845          << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7846          << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7847          << FixItHint::CreateInsertion(EndLoc, "]");
7848    } else
7849      Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7850  }
7851  
7852  /// \brief Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)7853  static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7854                                     Expr *LHSExpr, Expr *RHSExpr) {
7855    const Expr *StringRefExpr = LHSExpr;
7856    const CharacterLiteral *CharExpr =
7857        dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7858  
7859    if (!CharExpr) {
7860      CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7861      StringRefExpr = RHSExpr;
7862    }
7863  
7864    if (!CharExpr || !StringRefExpr)
7865      return;
7866  
7867    const QualType StringType = StringRefExpr->getType();
7868  
7869    // Return if not a PointerType.
7870    if (!StringType->isAnyPointerType())
7871      return;
7872  
7873    // Return if not a CharacterType.
7874    if (!StringType->getPointeeType()->isAnyCharacterType())
7875      return;
7876  
7877    ASTContext &Ctx = Self.getASTContext();
7878    SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7879  
7880    const QualType CharType = CharExpr->getType();
7881    if (!CharType->isAnyCharacterType() &&
7882        CharType->isIntegerType() &&
7883        llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7884      Self.Diag(OpLoc, diag::warn_string_plus_char)
7885          << DiagRange << Ctx.CharTy;
7886    } else {
7887      Self.Diag(OpLoc, diag::warn_string_plus_char)
7888          << DiagRange << CharExpr->getType();
7889    }
7890  
7891    // Only print a fixit for str + char, not for char + str.
7892    if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7893      SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7894      Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7895          << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7896          << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7897          << FixItHint::CreateInsertion(EndLoc, "]");
7898    } else {
7899      Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7900    }
7901  }
7902  
7903  /// \brief Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)7904  static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7905                                             Expr *LHSExpr, Expr *RHSExpr) {
7906    assert(LHSExpr->getType()->isAnyPointerType());
7907    assert(RHSExpr->getType()->isAnyPointerType());
7908    S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7909      << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7910      << RHSExpr->getSourceRange();
7911  }
7912  
7913  // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)7914  QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
7915                                       SourceLocation Loc, BinaryOperatorKind Opc,
7916                                       QualType* CompLHSTy) {
7917    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7918  
7919    if (LHS.get()->getType()->isVectorType() ||
7920        RHS.get()->getType()->isVectorType()) {
7921      QualType compType = CheckVectorOperands(
7922          LHS, RHS, Loc, CompLHSTy,
7923          /*AllowBothBool*/getLangOpts().AltiVec,
7924          /*AllowBoolConversions*/getLangOpts().ZVector);
7925      if (CompLHSTy) *CompLHSTy = compType;
7926      return compType;
7927    }
7928  
7929    QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7930    if (LHS.isInvalid() || RHS.isInvalid())
7931      return QualType();
7932  
7933    // Diagnose "string literal" '+' int and string '+' "char literal".
7934    if (Opc == BO_Add) {
7935      diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7936      diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7937    }
7938  
7939    // handle the common case first (both operands are arithmetic).
7940    if (!compType.isNull() && compType->isArithmeticType()) {
7941      if (CompLHSTy) *CompLHSTy = compType;
7942      return compType;
7943    }
7944  
7945    // Type-checking.  Ultimately the pointer's going to be in PExp;
7946    // note that we bias towards the LHS being the pointer.
7947    Expr *PExp = LHS.get(), *IExp = RHS.get();
7948  
7949    bool isObjCPointer;
7950    if (PExp->getType()->isPointerType()) {
7951      isObjCPointer = false;
7952    } else if (PExp->getType()->isObjCObjectPointerType()) {
7953      isObjCPointer = true;
7954    } else {
7955      std::swap(PExp, IExp);
7956      if (PExp->getType()->isPointerType()) {
7957        isObjCPointer = false;
7958      } else if (PExp->getType()->isObjCObjectPointerType()) {
7959        isObjCPointer = true;
7960      } else {
7961        return InvalidOperands(Loc, LHS, RHS);
7962      }
7963    }
7964    assert(PExp->getType()->isAnyPointerType());
7965  
7966    if (!IExp->getType()->isIntegerType())
7967      return InvalidOperands(Loc, LHS, RHS);
7968  
7969    if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7970      return QualType();
7971  
7972    if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7973      return QualType();
7974  
7975    // Check array bounds for pointer arithemtic
7976    CheckArrayAccess(PExp, IExp);
7977  
7978    if (CompLHSTy) {
7979      QualType LHSTy = Context.isPromotableBitField(LHS.get());
7980      if (LHSTy.isNull()) {
7981        LHSTy = LHS.get()->getType();
7982        if (LHSTy->isPromotableIntegerType())
7983          LHSTy = Context.getPromotedIntegerType(LHSTy);
7984      }
7985      *CompLHSTy = LHSTy;
7986    }
7987  
7988    return PExp->getType();
7989  }
7990  
7991  // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)7992  QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7993                                          SourceLocation Loc,
7994                                          QualType* CompLHSTy) {
7995    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7996  
7997    if (LHS.get()->getType()->isVectorType() ||
7998        RHS.get()->getType()->isVectorType()) {
7999      QualType compType = CheckVectorOperands(
8000          LHS, RHS, Loc, CompLHSTy,
8001          /*AllowBothBool*/getLangOpts().AltiVec,
8002          /*AllowBoolConversions*/getLangOpts().ZVector);
8003      if (CompLHSTy) *CompLHSTy = compType;
8004      return compType;
8005    }
8006  
8007    QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8008    if (LHS.isInvalid() || RHS.isInvalid())
8009      return QualType();
8010  
8011    // Enforce type constraints: C99 6.5.6p3.
8012  
8013    // Handle the common case first (both operands are arithmetic).
8014    if (!compType.isNull() && compType->isArithmeticType()) {
8015      if (CompLHSTy) *CompLHSTy = compType;
8016      return compType;
8017    }
8018  
8019    // Either ptr - int   or   ptr - ptr.
8020    if (LHS.get()->getType()->isAnyPointerType()) {
8021      QualType lpointee = LHS.get()->getType()->getPointeeType();
8022  
8023      // Diagnose bad cases where we step over interface counts.
8024      if (LHS.get()->getType()->isObjCObjectPointerType() &&
8025          checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8026        return QualType();
8027  
8028      // The result type of a pointer-int computation is the pointer type.
8029      if (RHS.get()->getType()->isIntegerType()) {
8030        if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8031          return QualType();
8032  
8033        // Check array bounds for pointer arithemtic
8034        CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8035                         /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8036  
8037        if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8038        return LHS.get()->getType();
8039      }
8040  
8041      // Handle pointer-pointer subtractions.
8042      if (const PointerType *RHSPTy
8043            = RHS.get()->getType()->getAs<PointerType>()) {
8044        QualType rpointee = RHSPTy->getPointeeType();
8045  
8046        if (getLangOpts().CPlusPlus) {
8047          // Pointee types must be the same: C++ [expr.add]
8048          if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8049            diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8050          }
8051        } else {
8052          // Pointee types must be compatible C99 6.5.6p3
8053          if (!Context.typesAreCompatible(
8054                  Context.getCanonicalType(lpointee).getUnqualifiedType(),
8055                  Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8056            diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8057            return QualType();
8058          }
8059        }
8060  
8061        if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8062                                                 LHS.get(), RHS.get()))
8063          return QualType();
8064  
8065        // The pointee type may have zero size.  As an extension, a structure or
8066        // union may have zero size or an array may have zero length.  In this
8067        // case subtraction does not make sense.
8068        if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8069          CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8070          if (ElementSize.isZero()) {
8071            Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8072              << rpointee.getUnqualifiedType()
8073              << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8074          }
8075        }
8076  
8077        if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8078        return Context.getPointerDiffType();
8079      }
8080    }
8081  
8082    return InvalidOperands(Loc, LHS, RHS);
8083  }
8084  
isScopedEnumerationType(QualType T)8085  static bool isScopedEnumerationType(QualType T) {
8086    if (const EnumType *ET = T->getAs<EnumType>())
8087      return ET->getDecl()->isScoped();
8088    return false;
8089  }
8090  
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)8091  static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8092                                     SourceLocation Loc, BinaryOperatorKind Opc,
8093                                     QualType LHSType) {
8094    // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8095    // so skip remaining warnings as we don't want to modify values within Sema.
8096    if (S.getLangOpts().OpenCL)
8097      return;
8098  
8099    llvm::APSInt Right;
8100    // Check right/shifter operand
8101    if (RHS.get()->isValueDependent() ||
8102        !RHS.get()->EvaluateAsInt(Right, S.Context))
8103      return;
8104  
8105    if (Right.isNegative()) {
8106      S.DiagRuntimeBehavior(Loc, RHS.get(),
8107                            S.PDiag(diag::warn_shift_negative)
8108                              << RHS.get()->getSourceRange());
8109      return;
8110    }
8111    llvm::APInt LeftBits(Right.getBitWidth(),
8112                         S.Context.getTypeSize(LHS.get()->getType()));
8113    if (Right.uge(LeftBits)) {
8114      S.DiagRuntimeBehavior(Loc, RHS.get(),
8115                            S.PDiag(diag::warn_shift_gt_typewidth)
8116                              << RHS.get()->getSourceRange());
8117      return;
8118    }
8119    if (Opc != BO_Shl)
8120      return;
8121  
8122    // When left shifting an ICE which is signed, we can check for overflow which
8123    // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8124    // integers have defined behavior modulo one more than the maximum value
8125    // representable in the result type, so never warn for those.
8126    llvm::APSInt Left;
8127    if (LHS.get()->isValueDependent() ||
8128        LHSType->hasUnsignedIntegerRepresentation() ||
8129        !LHS.get()->EvaluateAsInt(Left, S.Context))
8130      return;
8131  
8132    // If LHS does not have a signed type and non-negative value
8133    // then, the behavior is undefined. Warn about it.
8134    if (Left.isNegative()) {
8135      S.DiagRuntimeBehavior(Loc, LHS.get(),
8136                            S.PDiag(diag::warn_shift_lhs_negative)
8137                              << LHS.get()->getSourceRange());
8138      return;
8139    }
8140  
8141    llvm::APInt ResultBits =
8142        static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8143    if (LeftBits.uge(ResultBits))
8144      return;
8145    llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8146    Result = Result.shl(Right);
8147  
8148    // Print the bit representation of the signed integer as an unsigned
8149    // hexadecimal number.
8150    SmallString<40> HexResult;
8151    Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8152  
8153    // If we are only missing a sign bit, this is less likely to result in actual
8154    // bugs -- if the result is cast back to an unsigned type, it will have the
8155    // expected value. Thus we place this behind a different warning that can be
8156    // turned off separately if needed.
8157    if (LeftBits == ResultBits - 1) {
8158      S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8159          << HexResult << LHSType
8160          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8161      return;
8162    }
8163  
8164    S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8165      << HexResult.str() << Result.getMinSignedBits() << LHSType
8166      << Left.getBitWidth() << LHS.get()->getSourceRange()
8167      << RHS.get()->getSourceRange();
8168  }
8169  
8170  /// \brief Return the resulting type when an OpenCL vector is shifted
8171  ///        by a scalar or vector shift amount.
checkOpenCLVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)8172  static QualType checkOpenCLVectorShift(Sema &S,
8173                                         ExprResult &LHS, ExprResult &RHS,
8174                                         SourceLocation Loc, bool IsCompAssign) {
8175    // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8176    if (!LHS.get()->getType()->isVectorType()) {
8177      S.Diag(Loc, diag::err_shift_rhs_only_vector)
8178        << RHS.get()->getType() << LHS.get()->getType()
8179        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8180      return QualType();
8181    }
8182  
8183    if (!IsCompAssign) {
8184      LHS = S.UsualUnaryConversions(LHS.get());
8185      if (LHS.isInvalid()) return QualType();
8186    }
8187  
8188    RHS = S.UsualUnaryConversions(RHS.get());
8189    if (RHS.isInvalid()) return QualType();
8190  
8191    QualType LHSType = LHS.get()->getType();
8192    const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8193    QualType LHSEleType = LHSVecTy->getElementType();
8194  
8195    // Note that RHS might not be a vector.
8196    QualType RHSType = RHS.get()->getType();
8197    const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8198    QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8199  
8200    // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8201    if (!LHSEleType->isIntegerType()) {
8202      S.Diag(Loc, diag::err_typecheck_expect_int)
8203        << LHS.get()->getType() << LHS.get()->getSourceRange();
8204      return QualType();
8205    }
8206  
8207    if (!RHSEleType->isIntegerType()) {
8208      S.Diag(Loc, diag::err_typecheck_expect_int)
8209        << RHS.get()->getType() << RHS.get()->getSourceRange();
8210      return QualType();
8211    }
8212  
8213    if (RHSVecTy) {
8214      // OpenCL v1.1 s6.3.j says that for vector types, the operators
8215      // are applied component-wise. So if RHS is a vector, then ensure
8216      // that the number of elements is the same as LHS...
8217      if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8218        S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8219          << LHS.get()->getType() << RHS.get()->getType()
8220          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8221        return QualType();
8222      }
8223    } else {
8224      // ...else expand RHS to match the number of elements in LHS.
8225      QualType VecTy =
8226        S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8227      RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8228    }
8229  
8230    return LHSType;
8231  }
8232  
8233  // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)8234  QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8235                                    SourceLocation Loc, BinaryOperatorKind Opc,
8236                                    bool IsCompAssign) {
8237    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8238  
8239    // Vector shifts promote their scalar inputs to vector type.
8240    if (LHS.get()->getType()->isVectorType() ||
8241        RHS.get()->getType()->isVectorType()) {
8242      if (LangOpts.OpenCL)
8243        return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8244      if (LangOpts.ZVector) {
8245        // The shift operators for the z vector extensions work basically
8246        // like OpenCL shifts, except that neither the LHS nor the RHS is
8247        // allowed to be a "vector bool".
8248        if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8249          if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8250            return InvalidOperands(Loc, LHS, RHS);
8251        if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8252          if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8253            return InvalidOperands(Loc, LHS, RHS);
8254        return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8255      }
8256      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8257                                 /*AllowBothBool*/true,
8258                                 /*AllowBoolConversions*/false);
8259    }
8260  
8261    // Shifts don't perform usual arithmetic conversions, they just do integer
8262    // promotions on each operand. C99 6.5.7p3
8263  
8264    // For the LHS, do usual unary conversions, but then reset them away
8265    // if this is a compound assignment.
8266    ExprResult OldLHS = LHS;
8267    LHS = UsualUnaryConversions(LHS.get());
8268    if (LHS.isInvalid())
8269      return QualType();
8270    QualType LHSType = LHS.get()->getType();
8271    if (IsCompAssign) LHS = OldLHS;
8272  
8273    // The RHS is simpler.
8274    RHS = UsualUnaryConversions(RHS.get());
8275    if (RHS.isInvalid())
8276      return QualType();
8277    QualType RHSType = RHS.get()->getType();
8278  
8279    // C99 6.5.7p2: Each of the operands shall have integer type.
8280    if (!LHSType->hasIntegerRepresentation() ||
8281        !RHSType->hasIntegerRepresentation())
8282      return InvalidOperands(Loc, LHS, RHS);
8283  
8284    // C++0x: Don't allow scoped enums. FIXME: Use something better than
8285    // hasIntegerRepresentation() above instead of this.
8286    if (isScopedEnumerationType(LHSType) ||
8287        isScopedEnumerationType(RHSType)) {
8288      return InvalidOperands(Loc, LHS, RHS);
8289    }
8290    // Sanity-check shift operands
8291    DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8292  
8293    // "The type of the result is that of the promoted left operand."
8294    return LHSType;
8295  }
8296  
IsWithinTemplateSpecialization(Decl * D)8297  static bool IsWithinTemplateSpecialization(Decl *D) {
8298    if (DeclContext *DC = D->getDeclContext()) {
8299      if (isa<ClassTemplateSpecializationDecl>(DC))
8300        return true;
8301      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8302        return FD->isFunctionTemplateSpecialization();
8303    }
8304    return false;
8305  }
8306  
8307  /// If two different enums are compared, raise a warning.
checkEnumComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)8308  static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8309                                  Expr *RHS) {
8310    QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8311    QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8312  
8313    const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8314    if (!LHSEnumType)
8315      return;
8316    const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8317    if (!RHSEnumType)
8318      return;
8319  
8320    // Ignore anonymous enums.
8321    if (!LHSEnumType->getDecl()->getIdentifier())
8322      return;
8323    if (!RHSEnumType->getDecl()->getIdentifier())
8324      return;
8325  
8326    if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8327      return;
8328  
8329    S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8330        << LHSStrippedType << RHSStrippedType
8331        << LHS->getSourceRange() << RHS->getSourceRange();
8332  }
8333  
8334  /// \brief Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8335  static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8336                                                ExprResult &LHS, ExprResult &RHS,
8337                                                bool IsError) {
8338    S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8339                        : diag::ext_typecheck_comparison_of_distinct_pointers)
8340      << LHS.get()->getType() << RHS.get()->getType()
8341      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8342  }
8343  
8344  /// \brief Returns false if the pointers are converted to a composite type,
8345  /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)8346  static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8347                                             ExprResult &LHS, ExprResult &RHS) {
8348    // C++ [expr.rel]p2:
8349    //   [...] Pointer conversions (4.10) and qualification
8350    //   conversions (4.4) are performed on pointer operands (or on
8351    //   a pointer operand and a null pointer constant) to bring
8352    //   them to their composite pointer type. [...]
8353    //
8354    // C++ [expr.eq]p1 uses the same notion for (in)equality
8355    // comparisons of pointers.
8356  
8357    // C++ [expr.eq]p2:
8358    //   In addition, pointers to members can be compared, or a pointer to
8359    //   member and a null pointer constant. Pointer to member conversions
8360    //   (4.11) and qualification conversions (4.4) are performed to bring
8361    //   them to a common type. If one operand is a null pointer constant,
8362    //   the common type is the type of the other operand. Otherwise, the
8363    //   common type is a pointer to member type similar (4.4) to the type
8364    //   of one of the operands, with a cv-qualification signature (4.4)
8365    //   that is the union of the cv-qualification signatures of the operand
8366    //   types.
8367  
8368    QualType LHSType = LHS.get()->getType();
8369    QualType RHSType = RHS.get()->getType();
8370    assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8371           (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8372  
8373    bool NonStandardCompositeType = false;
8374    bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8375    QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8376    if (T.isNull()) {
8377      diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8378      return true;
8379    }
8380  
8381    if (NonStandardCompositeType)
8382      S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8383        << LHSType << RHSType << T << LHS.get()->getSourceRange()
8384        << RHS.get()->getSourceRange();
8385  
8386    LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8387    RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8388    return false;
8389  }
8390  
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)8391  static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8392                                                      ExprResult &LHS,
8393                                                      ExprResult &RHS,
8394                                                      bool IsError) {
8395    S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8396                        : diag::ext_typecheck_comparison_of_fptr_to_void)
8397      << LHS.get()->getType() << RHS.get()->getType()
8398      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8399  }
8400  
isObjCObjectLiteral(ExprResult & E)8401  static bool isObjCObjectLiteral(ExprResult &E) {
8402    switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8403    case Stmt::ObjCArrayLiteralClass:
8404    case Stmt::ObjCDictionaryLiteralClass:
8405    case Stmt::ObjCStringLiteralClass:
8406    case Stmt::ObjCBoxedExprClass:
8407      return true;
8408    default:
8409      // Note that ObjCBoolLiteral is NOT an object literal!
8410      return false;
8411    }
8412  }
8413  
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)8414  static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8415    const ObjCObjectPointerType *Type =
8416      LHS->getType()->getAs<ObjCObjectPointerType>();
8417  
8418    // If this is not actually an Objective-C object, bail out.
8419    if (!Type)
8420      return false;
8421  
8422    // Get the LHS object's interface type.
8423    QualType InterfaceType = Type->getPointeeType();
8424  
8425    // If the RHS isn't an Objective-C object, bail out.
8426    if (!RHS->getType()->isObjCObjectPointerType())
8427      return false;
8428  
8429    // Try to find the -isEqual: method.
8430    Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8431    ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8432                                                        InterfaceType,
8433                                                        /*instance=*/true);
8434    if (!Method) {
8435      if (Type->isObjCIdType()) {
8436        // For 'id', just check the global pool.
8437        Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8438                                                    /*receiverId=*/true);
8439      } else {
8440        // Check protocols.
8441        Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8442                                               /*instance=*/true);
8443      }
8444    }
8445  
8446    if (!Method)
8447      return false;
8448  
8449    QualType T = Method->parameters()[0]->getType();
8450    if (!T->isObjCObjectPointerType())
8451      return false;
8452  
8453    QualType R = Method->getReturnType();
8454    if (!R->isScalarType())
8455      return false;
8456  
8457    return true;
8458  }
8459  
CheckLiteralKind(Expr * FromE)8460  Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8461    FromE = FromE->IgnoreParenImpCasts();
8462    switch (FromE->getStmtClass()) {
8463      default:
8464        break;
8465      case Stmt::ObjCStringLiteralClass:
8466        // "string literal"
8467        return LK_String;
8468      case Stmt::ObjCArrayLiteralClass:
8469        // "array literal"
8470        return LK_Array;
8471      case Stmt::ObjCDictionaryLiteralClass:
8472        // "dictionary literal"
8473        return LK_Dictionary;
8474      case Stmt::BlockExprClass:
8475        return LK_Block;
8476      case Stmt::ObjCBoxedExprClass: {
8477        Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8478        switch (Inner->getStmtClass()) {
8479          case Stmt::IntegerLiteralClass:
8480          case Stmt::FloatingLiteralClass:
8481          case Stmt::CharacterLiteralClass:
8482          case Stmt::ObjCBoolLiteralExprClass:
8483          case Stmt::CXXBoolLiteralExprClass:
8484            // "numeric literal"
8485            return LK_Numeric;
8486          case Stmt::ImplicitCastExprClass: {
8487            CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8488            // Boolean literals can be represented by implicit casts.
8489            if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8490              return LK_Numeric;
8491            break;
8492          }
8493          default:
8494            break;
8495        }
8496        return LK_Boxed;
8497      }
8498    }
8499    return LK_None;
8500  }
8501  
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)8502  static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8503                                            ExprResult &LHS, ExprResult &RHS,
8504                                            BinaryOperator::Opcode Opc){
8505    Expr *Literal;
8506    Expr *Other;
8507    if (isObjCObjectLiteral(LHS)) {
8508      Literal = LHS.get();
8509      Other = RHS.get();
8510    } else {
8511      Literal = RHS.get();
8512      Other = LHS.get();
8513    }
8514  
8515    // Don't warn on comparisons against nil.
8516    Other = Other->IgnoreParenCasts();
8517    if (Other->isNullPointerConstant(S.getASTContext(),
8518                                     Expr::NPC_ValueDependentIsNotNull))
8519      return;
8520  
8521    // This should be kept in sync with warn_objc_literal_comparison.
8522    // LK_String should always be after the other literals, since it has its own
8523    // warning flag.
8524    Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8525    assert(LiteralKind != Sema::LK_Block);
8526    if (LiteralKind == Sema::LK_None) {
8527      llvm_unreachable("Unknown Objective-C object literal kind");
8528    }
8529  
8530    if (LiteralKind == Sema::LK_String)
8531      S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8532        << Literal->getSourceRange();
8533    else
8534      S.Diag(Loc, diag::warn_objc_literal_comparison)
8535        << LiteralKind << Literal->getSourceRange();
8536  
8537    if (BinaryOperator::isEqualityOp(Opc) &&
8538        hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8539      SourceLocation Start = LHS.get()->getLocStart();
8540      SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8541      CharSourceRange OpRange =
8542        CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8543  
8544      S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8545        << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8546        << FixItHint::CreateReplacement(OpRange, " isEqual:")
8547        << FixItHint::CreateInsertion(End, "]");
8548    }
8549  }
8550  
diagnoseLogicalNotOnLHSofComparison(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)8551  static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8552                                                  ExprResult &RHS,
8553                                                  SourceLocation Loc,
8554                                                  BinaryOperatorKind Opc) {
8555    // Check that left hand side is !something.
8556    UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8557    if (!UO || UO->getOpcode() != UO_LNot) return;
8558  
8559    // Only check if the right hand side is non-bool arithmetic type.
8560    if (RHS.get()->isKnownToHaveBooleanValue()) return;
8561  
8562    // Make sure that the something in !something is not bool.
8563    Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8564    if (SubExpr->isKnownToHaveBooleanValue()) return;
8565  
8566    // Emit warning.
8567    S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8568        << Loc;
8569  
8570    // First note suggest !(x < y)
8571    SourceLocation FirstOpen = SubExpr->getLocStart();
8572    SourceLocation FirstClose = RHS.get()->getLocEnd();
8573    FirstClose = S.getLocForEndOfToken(FirstClose);
8574    if (FirstClose.isInvalid())
8575      FirstOpen = SourceLocation();
8576    S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8577        << FixItHint::CreateInsertion(FirstOpen, "(")
8578        << FixItHint::CreateInsertion(FirstClose, ")");
8579  
8580    // Second note suggests (!x) < y
8581    SourceLocation SecondOpen = LHS.get()->getLocStart();
8582    SourceLocation SecondClose = LHS.get()->getLocEnd();
8583    SecondClose = S.getLocForEndOfToken(SecondClose);
8584    if (SecondClose.isInvalid())
8585      SecondOpen = SourceLocation();
8586    S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8587        << FixItHint::CreateInsertion(SecondOpen, "(")
8588        << FixItHint::CreateInsertion(SecondClose, ")");
8589  }
8590  
8591  // Get the decl for a simple expression: a reference to a variable,
8592  // an implicit C++ field reference, or an implicit ObjC ivar reference.
getCompareDecl(Expr * E)8593  static ValueDecl *getCompareDecl(Expr *E) {
8594    if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8595      return DR->getDecl();
8596    if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8597      if (Ivar->isFreeIvar())
8598        return Ivar->getDecl();
8599    }
8600    if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8601      if (Mem->isImplicitAccess())
8602        return Mem->getMemberDecl();
8603    }
8604    return nullptr;
8605  }
8606  
8607  // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsRelational)8608  QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8609                                      SourceLocation Loc, BinaryOperatorKind Opc,
8610                                      bool IsRelational) {
8611    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8612  
8613    // Handle vector comparisons separately.
8614    if (LHS.get()->getType()->isVectorType() ||
8615        RHS.get()->getType()->isVectorType())
8616      return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8617  
8618    QualType LHSType = LHS.get()->getType();
8619    QualType RHSType = RHS.get()->getType();
8620  
8621    Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8622    Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8623  
8624    checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8625    diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
8626  
8627    if (!LHSType->hasFloatingRepresentation() &&
8628        !(LHSType->isBlockPointerType() && IsRelational) &&
8629        !LHS.get()->getLocStart().isMacroID() &&
8630        !RHS.get()->getLocStart().isMacroID() &&
8631        ActiveTemplateInstantiations.empty()) {
8632      // For non-floating point types, check for self-comparisons of the form
8633      // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8634      // often indicate logic errors in the program.
8635      //
8636      // NOTE: Don't warn about comparison expressions resulting from macro
8637      // expansion. Also don't warn about comparisons which are only self
8638      // comparisons within a template specialization. The warnings should catch
8639      // obvious cases in the definition of the template anyways. The idea is to
8640      // warn when the typed comparison operator will always evaluate to the same
8641      // result.
8642      ValueDecl *DL = getCompareDecl(LHSStripped);
8643      ValueDecl *DR = getCompareDecl(RHSStripped);
8644      if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8645        DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8646                            << 0 // self-
8647                            << (Opc == BO_EQ
8648                                || Opc == BO_LE
8649                                || Opc == BO_GE));
8650      } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8651                 !DL->getType()->isReferenceType() &&
8652                 !DR->getType()->isReferenceType()) {
8653          // what is it always going to eval to?
8654          char always_evals_to;
8655          switch(Opc) {
8656          case BO_EQ: // e.g. array1 == array2
8657            always_evals_to = 0; // false
8658            break;
8659          case BO_NE: // e.g. array1 != array2
8660            always_evals_to = 1; // true
8661            break;
8662          default:
8663            // best we can say is 'a constant'
8664            always_evals_to = 2; // e.g. array1 <= array2
8665            break;
8666          }
8667          DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8668                              << 1 // array
8669                              << always_evals_to);
8670      }
8671  
8672      if (isa<CastExpr>(LHSStripped))
8673        LHSStripped = LHSStripped->IgnoreParenCasts();
8674      if (isa<CastExpr>(RHSStripped))
8675        RHSStripped = RHSStripped->IgnoreParenCasts();
8676  
8677      // Warn about comparisons against a string constant (unless the other
8678      // operand is null), the user probably wants strcmp.
8679      Expr *literalString = nullptr;
8680      Expr *literalStringStripped = nullptr;
8681      if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8682          !RHSStripped->isNullPointerConstant(Context,
8683                                              Expr::NPC_ValueDependentIsNull)) {
8684        literalString = LHS.get();
8685        literalStringStripped = LHSStripped;
8686      } else if ((isa<StringLiteral>(RHSStripped) ||
8687                  isa<ObjCEncodeExpr>(RHSStripped)) &&
8688                 !LHSStripped->isNullPointerConstant(Context,
8689                                              Expr::NPC_ValueDependentIsNull)) {
8690        literalString = RHS.get();
8691        literalStringStripped = RHSStripped;
8692      }
8693  
8694      if (literalString) {
8695        DiagRuntimeBehavior(Loc, nullptr,
8696          PDiag(diag::warn_stringcompare)
8697            << isa<ObjCEncodeExpr>(literalStringStripped)
8698            << literalString->getSourceRange());
8699      }
8700    }
8701  
8702    // C99 6.5.8p3 / C99 6.5.9p4
8703    UsualArithmeticConversions(LHS, RHS);
8704    if (LHS.isInvalid() || RHS.isInvalid())
8705      return QualType();
8706  
8707    LHSType = LHS.get()->getType();
8708    RHSType = RHS.get()->getType();
8709  
8710    // The result of comparisons is 'bool' in C++, 'int' in C.
8711    QualType ResultTy = Context.getLogicalOperationType();
8712  
8713    if (IsRelational) {
8714      if (LHSType->isRealType() && RHSType->isRealType())
8715        return ResultTy;
8716    } else {
8717      // Check for comparisons of floating point operands using != and ==.
8718      if (LHSType->hasFloatingRepresentation())
8719        CheckFloatComparison(Loc, LHS.get(), RHS.get());
8720  
8721      if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8722        return ResultTy;
8723    }
8724  
8725    const Expr::NullPointerConstantKind LHSNullKind =
8726        LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8727    const Expr::NullPointerConstantKind RHSNullKind =
8728        RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8729    bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8730    bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8731  
8732    if (!IsRelational && LHSIsNull != RHSIsNull) {
8733      bool IsEquality = Opc == BO_EQ;
8734      if (RHSIsNull)
8735        DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8736                                     RHS.get()->getSourceRange());
8737      else
8738        DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8739                                     LHS.get()->getSourceRange());
8740    }
8741  
8742    // All of the following pointer-related warnings are GCC extensions, except
8743    // when handling null pointer constants.
8744    if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8745      QualType LCanPointeeTy =
8746        LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8747      QualType RCanPointeeTy =
8748        RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8749  
8750      if (getLangOpts().CPlusPlus) {
8751        if (LCanPointeeTy == RCanPointeeTy)
8752          return ResultTy;
8753        if (!IsRelational &&
8754            (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8755          // Valid unless comparison between non-null pointer and function pointer
8756          // This is a gcc extension compatibility comparison.
8757          // In a SFINAE context, we treat this as a hard error to maintain
8758          // conformance with the C++ standard.
8759          if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8760              && !LHSIsNull && !RHSIsNull) {
8761            diagnoseFunctionPointerToVoidComparison(
8762                *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8763  
8764            if (isSFINAEContext())
8765              return QualType();
8766  
8767            RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8768            return ResultTy;
8769          }
8770        }
8771  
8772        if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8773          return QualType();
8774        else
8775          return ResultTy;
8776      }
8777      // C99 6.5.9p2 and C99 6.5.8p2
8778      if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8779                                     RCanPointeeTy.getUnqualifiedType())) {
8780        // Valid unless a relational comparison of function pointers
8781        if (IsRelational && LCanPointeeTy->isFunctionType()) {
8782          Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8783            << LHSType << RHSType << LHS.get()->getSourceRange()
8784            << RHS.get()->getSourceRange();
8785        }
8786      } else if (!IsRelational &&
8787                 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8788        // Valid unless comparison between non-null pointer and function pointer
8789        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8790            && !LHSIsNull && !RHSIsNull)
8791          diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8792                                                  /*isError*/false);
8793      } else {
8794        // Invalid
8795        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8796      }
8797      if (LCanPointeeTy != RCanPointeeTy) {
8798        // Treat NULL constant as a special case in OpenCL.
8799        if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
8800          const PointerType *LHSPtr = LHSType->getAs<PointerType>();
8801          if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8802            Diag(Loc,
8803                 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8804                << LHSType << RHSType << 0 /* comparison */
8805                << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8806          }
8807        }
8808        unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8809        unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8810        CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8811                                                 : CK_BitCast;
8812        if (LHSIsNull && !RHSIsNull)
8813          LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8814        else
8815          RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8816      }
8817      return ResultTy;
8818    }
8819  
8820    if (getLangOpts().CPlusPlus) {
8821      // Comparison of nullptr_t with itself.
8822      if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8823        return ResultTy;
8824  
8825      // Comparison of pointers with null pointer constants and equality
8826      // comparisons of member pointers to null pointer constants.
8827      if (RHSIsNull &&
8828          ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8829           (!IsRelational &&
8830            (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8831        RHS = ImpCastExprToType(RHS.get(), LHSType,
8832                          LHSType->isMemberPointerType()
8833                            ? CK_NullToMemberPointer
8834                            : CK_NullToPointer);
8835        return ResultTy;
8836      }
8837      if (LHSIsNull &&
8838          ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8839           (!IsRelational &&
8840            (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8841        LHS = ImpCastExprToType(LHS.get(), RHSType,
8842                          RHSType->isMemberPointerType()
8843                            ? CK_NullToMemberPointer
8844                            : CK_NullToPointer);
8845        return ResultTy;
8846      }
8847  
8848      // Comparison of member pointers.
8849      if (!IsRelational &&
8850          LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8851        if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8852          return QualType();
8853        else
8854          return ResultTy;
8855      }
8856  
8857      // Handle scoped enumeration types specifically, since they don't promote
8858      // to integers.
8859      if (LHS.get()->getType()->isEnumeralType() &&
8860          Context.hasSameUnqualifiedType(LHS.get()->getType(),
8861                                         RHS.get()->getType()))
8862        return ResultTy;
8863    }
8864  
8865    // Handle block pointer types.
8866    if (!IsRelational && LHSType->isBlockPointerType() &&
8867        RHSType->isBlockPointerType()) {
8868      QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8869      QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8870  
8871      if (!LHSIsNull && !RHSIsNull &&
8872          !Context.typesAreCompatible(lpointee, rpointee)) {
8873        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8874          << LHSType << RHSType << LHS.get()->getSourceRange()
8875          << RHS.get()->getSourceRange();
8876      }
8877      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8878      return ResultTy;
8879    }
8880  
8881    // Allow block pointers to be compared with null pointer constants.
8882    if (!IsRelational
8883        && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8884            || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8885      if (!LHSIsNull && !RHSIsNull) {
8886        if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8887               ->getPointeeType()->isVoidType())
8888              || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8889                  ->getPointeeType()->isVoidType())))
8890          Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8891            << LHSType << RHSType << LHS.get()->getSourceRange()
8892            << RHS.get()->getSourceRange();
8893      }
8894      if (LHSIsNull && !RHSIsNull)
8895        LHS = ImpCastExprToType(LHS.get(), RHSType,
8896                                RHSType->isPointerType() ? CK_BitCast
8897                                  : CK_AnyPointerToBlockPointerCast);
8898      else
8899        RHS = ImpCastExprToType(RHS.get(), LHSType,
8900                                LHSType->isPointerType() ? CK_BitCast
8901                                  : CK_AnyPointerToBlockPointerCast);
8902      return ResultTy;
8903    }
8904  
8905    if (LHSType->isObjCObjectPointerType() ||
8906        RHSType->isObjCObjectPointerType()) {
8907      const PointerType *LPT = LHSType->getAs<PointerType>();
8908      const PointerType *RPT = RHSType->getAs<PointerType>();
8909      if (LPT || RPT) {
8910        bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8911        bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8912  
8913        if (!LPtrToVoid && !RPtrToVoid &&
8914            !Context.typesAreCompatible(LHSType, RHSType)) {
8915          diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8916                                            /*isError*/false);
8917        }
8918        if (LHSIsNull && !RHSIsNull) {
8919          Expr *E = LHS.get();
8920          if (getLangOpts().ObjCAutoRefCount)
8921            CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8922          LHS = ImpCastExprToType(E, RHSType,
8923                                  RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8924        }
8925        else {
8926          Expr *E = RHS.get();
8927          if (getLangOpts().ObjCAutoRefCount)
8928            CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8929                                   Opc);
8930          RHS = ImpCastExprToType(E, LHSType,
8931                                  LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8932        }
8933        return ResultTy;
8934      }
8935      if (LHSType->isObjCObjectPointerType() &&
8936          RHSType->isObjCObjectPointerType()) {
8937        if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8938          diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8939                                            /*isError*/false);
8940        if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8941          diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8942  
8943        if (LHSIsNull && !RHSIsNull)
8944          LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8945        else
8946          RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8947        return ResultTy;
8948      }
8949    }
8950    if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8951        (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8952      unsigned DiagID = 0;
8953      bool isError = false;
8954      if (LangOpts.DebuggerSupport) {
8955        // Under a debugger, allow the comparison of pointers to integers,
8956        // since users tend to want to compare addresses.
8957      } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8958          (RHSIsNull && RHSType->isIntegerType())) {
8959        if (IsRelational && !getLangOpts().CPlusPlus)
8960          DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8961      } else if (IsRelational && !getLangOpts().CPlusPlus)
8962        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8963      else if (getLangOpts().CPlusPlus) {
8964        DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8965        isError = true;
8966      } else
8967        DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8968  
8969      if (DiagID) {
8970        Diag(Loc, DiagID)
8971          << LHSType << RHSType << LHS.get()->getSourceRange()
8972          << RHS.get()->getSourceRange();
8973        if (isError)
8974          return QualType();
8975      }
8976  
8977      if (LHSType->isIntegerType())
8978        LHS = ImpCastExprToType(LHS.get(), RHSType,
8979                          LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8980      else
8981        RHS = ImpCastExprToType(RHS.get(), LHSType,
8982                          RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8983      return ResultTy;
8984    }
8985  
8986    // Handle block pointers.
8987    if (!IsRelational && RHSIsNull
8988        && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8989      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8990      return ResultTy;
8991    }
8992    if (!IsRelational && LHSIsNull
8993        && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8994      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8995      return ResultTy;
8996    }
8997  
8998    return InvalidOperands(Loc, LHS, RHS);
8999  }
9000  
9001  
9002  // Return a signed type that is of identical size and number of elements.
9003  // For floating point vectors, return an integer type of identical size
9004  // and number of elements.
GetSignedVectorType(QualType V)9005  QualType Sema::GetSignedVectorType(QualType V) {
9006    const VectorType *VTy = V->getAs<VectorType>();
9007    unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9008    if (TypeSize == Context.getTypeSize(Context.CharTy))
9009      return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9010    else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9011      return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9012    else if (TypeSize == Context.getTypeSize(Context.IntTy))
9013      return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9014    else if (TypeSize == Context.getTypeSize(Context.LongTy))
9015      return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9016    assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9017           "Unhandled vector element size in vector compare");
9018    return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9019  }
9020  
9021  /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9022  /// operates on extended vector types.  Instead of producing an IntTy result,
9023  /// like a scalar comparison, a vector comparison produces a vector of integer
9024  /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsRelational)9025  QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9026                                            SourceLocation Loc,
9027                                            bool IsRelational) {
9028    // Check to make sure we're operating on vectors of the same type and width,
9029    // Allowing one side to be a scalar of element type.
9030    QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9031                                /*AllowBothBool*/true,
9032                                /*AllowBoolConversions*/getLangOpts().ZVector);
9033    if (vType.isNull())
9034      return vType;
9035  
9036    QualType LHSType = LHS.get()->getType();
9037  
9038    // If AltiVec, the comparison results in a numeric type, i.e.
9039    // bool for C++, int for C
9040    if (getLangOpts().AltiVec &&
9041        vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9042      return Context.getLogicalOperationType();
9043  
9044    // For non-floating point types, check for self-comparisons of the form
9045    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9046    // often indicate logic errors in the program.
9047    if (!LHSType->hasFloatingRepresentation() &&
9048        ActiveTemplateInstantiations.empty()) {
9049      if (DeclRefExpr* DRL
9050            = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9051        if (DeclRefExpr* DRR
9052              = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9053          if (DRL->getDecl() == DRR->getDecl())
9054            DiagRuntimeBehavior(Loc, nullptr,
9055                                PDiag(diag::warn_comparison_always)
9056                                  << 0 // self-
9057                                  << 2 // "a constant"
9058                                );
9059    }
9060  
9061    // Check for comparisons of floating point operands using != and ==.
9062    if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9063      assert (RHS.get()->getType()->hasFloatingRepresentation());
9064      CheckFloatComparison(Loc, LHS.get(), RHS.get());
9065    }
9066  
9067    // Return a signed type for the vector.
9068    return GetSignedVectorType(LHSType);
9069  }
9070  
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)9071  QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9072                                            SourceLocation Loc) {
9073    // Ensure that either both operands are of the same vector type, or
9074    // one operand is of a vector type and the other is of its element type.
9075    QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9076                                         /*AllowBothBool*/true,
9077                                         /*AllowBoolConversions*/false);
9078    if (vType.isNull())
9079      return InvalidOperands(Loc, LHS, RHS);
9080    if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9081        vType->hasFloatingRepresentation())
9082      return InvalidOperands(Loc, LHS, RHS);
9083  
9084    return GetSignedVectorType(LHS.get()->getType());
9085  }
9086  
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)9087  inline QualType Sema::CheckBitwiseOperands(
9088    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9089    checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9090  
9091    if (LHS.get()->getType()->isVectorType() ||
9092        RHS.get()->getType()->isVectorType()) {
9093      if (LHS.get()->getType()->hasIntegerRepresentation() &&
9094          RHS.get()->getType()->hasIntegerRepresentation())
9095        return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9096                          /*AllowBothBool*/true,
9097                          /*AllowBoolConversions*/getLangOpts().ZVector);
9098      return InvalidOperands(Loc, LHS, RHS);
9099    }
9100  
9101    ExprResult LHSResult = LHS, RHSResult = RHS;
9102    QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9103                                                   IsCompAssign);
9104    if (LHSResult.isInvalid() || RHSResult.isInvalid())
9105      return QualType();
9106    LHS = LHSResult.get();
9107    RHS = RHSResult.get();
9108  
9109    if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9110      return compType;
9111    return InvalidOperands(Loc, LHS, RHS);
9112  }
9113  
9114  // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)9115  inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9116                                             SourceLocation Loc,
9117                                             BinaryOperatorKind Opc) {
9118    // Check vector operands differently.
9119    if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9120      return CheckVectorLogicalOperands(LHS, RHS, Loc);
9121  
9122    // Diagnose cases where the user write a logical and/or but probably meant a
9123    // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9124    // is a constant.
9125    if (LHS.get()->getType()->isIntegerType() &&
9126        !LHS.get()->getType()->isBooleanType() &&
9127        RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9128        // Don't warn in macros or template instantiations.
9129        !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9130      // If the RHS can be constant folded, and if it constant folds to something
9131      // that isn't 0 or 1 (which indicate a potential logical operation that
9132      // happened to fold to true/false) then warn.
9133      // Parens on the RHS are ignored.
9134      llvm::APSInt Result;
9135      if (RHS.get()->EvaluateAsInt(Result, Context))
9136        if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9137             !RHS.get()->getExprLoc().isMacroID()) ||
9138            (Result != 0 && Result != 1)) {
9139          Diag(Loc, diag::warn_logical_instead_of_bitwise)
9140            << RHS.get()->getSourceRange()
9141            << (Opc == BO_LAnd ? "&&" : "||");
9142          // Suggest replacing the logical operator with the bitwise version
9143          Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9144              << (Opc == BO_LAnd ? "&" : "|")
9145              << FixItHint::CreateReplacement(SourceRange(
9146                                                   Loc, getLocForEndOfToken(Loc)),
9147                                              Opc == BO_LAnd ? "&" : "|");
9148          if (Opc == BO_LAnd)
9149            // Suggest replacing "Foo() && kNonZero" with "Foo()"
9150            Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9151                << FixItHint::CreateRemoval(
9152                    SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9153                                RHS.get()->getLocEnd()));
9154        }
9155    }
9156  
9157    if (!Context.getLangOpts().CPlusPlus) {
9158      // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9159      // not operate on the built-in scalar and vector float types.
9160      if (Context.getLangOpts().OpenCL &&
9161          Context.getLangOpts().OpenCLVersion < 120) {
9162        if (LHS.get()->getType()->isFloatingType() ||
9163            RHS.get()->getType()->isFloatingType())
9164          return InvalidOperands(Loc, LHS, RHS);
9165      }
9166  
9167      LHS = UsualUnaryConversions(LHS.get());
9168      if (LHS.isInvalid())
9169        return QualType();
9170  
9171      RHS = UsualUnaryConversions(RHS.get());
9172      if (RHS.isInvalid())
9173        return QualType();
9174  
9175      if (!LHS.get()->getType()->isScalarType() ||
9176          !RHS.get()->getType()->isScalarType())
9177        return InvalidOperands(Loc, LHS, RHS);
9178  
9179      return Context.IntTy;
9180    }
9181  
9182    // The following is safe because we only use this method for
9183    // non-overloadable operands.
9184  
9185    // C++ [expr.log.and]p1
9186    // C++ [expr.log.or]p1
9187    // The operands are both contextually converted to type bool.
9188    ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9189    if (LHSRes.isInvalid())
9190      return InvalidOperands(Loc, LHS, RHS);
9191    LHS = LHSRes;
9192  
9193    ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9194    if (RHSRes.isInvalid())
9195      return InvalidOperands(Loc, LHS, RHS);
9196    RHS = RHSRes;
9197  
9198    // C++ [expr.log.and]p2
9199    // C++ [expr.log.or]p2
9200    // The result is a bool.
9201    return Context.BoolTy;
9202  }
9203  
IsReadonlyMessage(Expr * E,Sema & S)9204  static bool IsReadonlyMessage(Expr *E, Sema &S) {
9205    const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9206    if (!ME) return false;
9207    if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9208    ObjCMessageExpr *Base =
9209      dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9210    if (!Base) return false;
9211    return Base->getMethodDecl() != nullptr;
9212  }
9213  
9214  /// Is the given expression (which must be 'const') a reference to a
9215  /// variable which was originally non-const, but which has become
9216  /// 'const' due to being captured within a block?
9217  enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)9218  static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9219    assert(E->isLValue() && E->getType().isConstQualified());
9220    E = E->IgnoreParens();
9221  
9222    // Must be a reference to a declaration from an enclosing scope.
9223    DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9224    if (!DRE) return NCCK_None;
9225    if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9226  
9227    // The declaration must be a variable which is not declared 'const'.
9228    VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9229    if (!var) return NCCK_None;
9230    if (var->getType().isConstQualified()) return NCCK_None;
9231    assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9232  
9233    // Decide whether the first capture was for a block or a lambda.
9234    DeclContext *DC = S.CurContext, *Prev = nullptr;
9235    while (DC != var->getDeclContext()) {
9236      Prev = DC;
9237      DC = DC->getParent();
9238    }
9239    // Unless we have an init-capture, we've gone one step too far.
9240    if (!var->isInitCapture())
9241      DC = Prev;
9242    return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9243  }
9244  
IsTypeModifiable(QualType Ty,bool IsDereference)9245  static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9246    Ty = Ty.getNonReferenceType();
9247    if (IsDereference && Ty->isPointerType())
9248      Ty = Ty->getPointeeType();
9249    return !Ty.isConstQualified();
9250  }
9251  
9252  /// Emit the "read-only variable not assignable" error and print notes to give
9253  /// more information about why the variable is not assignable, such as pointing
9254  /// to the declaration of a const variable, showing that a method is const, or
9255  /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)9256  static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9257                                      SourceLocation Loc) {
9258    // Update err_typecheck_assign_const and note_typecheck_assign_const
9259    // when this enum is changed.
9260    enum {
9261      ConstFunction,
9262      ConstVariable,
9263      ConstMember,
9264      ConstMethod,
9265      ConstUnknown,  // Keep as last element
9266    };
9267  
9268    SourceRange ExprRange = E->getSourceRange();
9269  
9270    // Only emit one error on the first const found.  All other consts will emit
9271    // a note to the error.
9272    bool DiagnosticEmitted = false;
9273  
9274    // Track if the current expression is the result of a derefence, and if the
9275    // next checked expression is the result of a derefence.
9276    bool IsDereference = false;
9277    bool NextIsDereference = false;
9278  
9279    // Loop to process MemberExpr chains.
9280    while (true) {
9281      IsDereference = NextIsDereference;
9282      NextIsDereference = false;
9283  
9284      E = E->IgnoreParenImpCasts();
9285      if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9286        NextIsDereference = ME->isArrow();
9287        const ValueDecl *VD = ME->getMemberDecl();
9288        if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9289          // Mutable fields can be modified even if the class is const.
9290          if (Field->isMutable()) {
9291            assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9292            break;
9293          }
9294  
9295          if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9296            if (!DiagnosticEmitted) {
9297              S.Diag(Loc, diag::err_typecheck_assign_const)
9298                  << ExprRange << ConstMember << false /*static*/ << Field
9299                  << Field->getType();
9300              DiagnosticEmitted = true;
9301            }
9302            S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9303                << ConstMember << false /*static*/ << Field << Field->getType()
9304                << Field->getSourceRange();
9305          }
9306          E = ME->getBase();
9307          continue;
9308        } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9309          if (VDecl->getType().isConstQualified()) {
9310            if (!DiagnosticEmitted) {
9311              S.Diag(Loc, diag::err_typecheck_assign_const)
9312                  << ExprRange << ConstMember << true /*static*/ << VDecl
9313                  << VDecl->getType();
9314              DiagnosticEmitted = true;
9315            }
9316            S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9317                << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9318                << VDecl->getSourceRange();
9319          }
9320          // Static fields do not inherit constness from parents.
9321          break;
9322        }
9323        break;
9324      } // End MemberExpr
9325      break;
9326    }
9327  
9328    if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9329      // Function calls
9330      const FunctionDecl *FD = CE->getDirectCallee();
9331      if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9332        if (!DiagnosticEmitted) {
9333          S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9334                                                        << ConstFunction << FD;
9335          DiagnosticEmitted = true;
9336        }
9337        S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9338               diag::note_typecheck_assign_const)
9339            << ConstFunction << FD << FD->getReturnType()
9340            << FD->getReturnTypeSourceRange();
9341      }
9342    } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9343      // Point to variable declaration.
9344      if (const ValueDecl *VD = DRE->getDecl()) {
9345        if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9346          if (!DiagnosticEmitted) {
9347            S.Diag(Loc, diag::err_typecheck_assign_const)
9348                << ExprRange << ConstVariable << VD << VD->getType();
9349            DiagnosticEmitted = true;
9350          }
9351          S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9352              << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9353        }
9354      }
9355    } else if (isa<CXXThisExpr>(E)) {
9356      if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9357        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9358          if (MD->isConst()) {
9359            if (!DiagnosticEmitted) {
9360              S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9361                                                            << ConstMethod << MD;
9362              DiagnosticEmitted = true;
9363            }
9364            S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9365                << ConstMethod << MD << MD->getSourceRange();
9366          }
9367        }
9368      }
9369    }
9370  
9371    if (DiagnosticEmitted)
9372      return;
9373  
9374    // Can't determine a more specific message, so display the generic error.
9375    S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9376  }
9377  
9378  /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9379  /// emit an error and return true.  If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)9380  static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9381    assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9382    SourceLocation OrigLoc = Loc;
9383    Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9384                                                                &Loc);
9385    if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9386      IsLV = Expr::MLV_InvalidMessageExpression;
9387    if (IsLV == Expr::MLV_Valid)
9388      return false;
9389  
9390    unsigned DiagID = 0;
9391    bool NeedType = false;
9392    switch (IsLV) { // C99 6.5.16p2
9393    case Expr::MLV_ConstQualified:
9394      // Use a specialized diagnostic when we're assigning to an object
9395      // from an enclosing function or block.
9396      if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9397        if (NCCK == NCCK_Block)
9398          DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9399        else
9400          DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9401        break;
9402      }
9403  
9404      // In ARC, use some specialized diagnostics for occasions where we
9405      // infer 'const'.  These are always pseudo-strong variables.
9406      if (S.getLangOpts().ObjCAutoRefCount) {
9407        DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9408        if (declRef && isa<VarDecl>(declRef->getDecl())) {
9409          VarDecl *var = cast<VarDecl>(declRef->getDecl());
9410  
9411          // Use the normal diagnostic if it's pseudo-__strong but the
9412          // user actually wrote 'const'.
9413          if (var->isARCPseudoStrong() &&
9414              (!var->getTypeSourceInfo() ||
9415               !var->getTypeSourceInfo()->getType().isConstQualified())) {
9416            // There are two pseudo-strong cases:
9417            //  - self
9418            ObjCMethodDecl *method = S.getCurMethodDecl();
9419            if (method && var == method->getSelfDecl())
9420              DiagID = method->isClassMethod()
9421                ? diag::err_typecheck_arc_assign_self_class_method
9422                : diag::err_typecheck_arc_assign_self;
9423  
9424            //  - fast enumeration variables
9425            else
9426              DiagID = diag::err_typecheck_arr_assign_enumeration;
9427  
9428            SourceRange Assign;
9429            if (Loc != OrigLoc)
9430              Assign = SourceRange(OrigLoc, OrigLoc);
9431            S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9432            // We need to preserve the AST regardless, so migration tool
9433            // can do its job.
9434            return false;
9435          }
9436        }
9437      }
9438  
9439      // If none of the special cases above are triggered, then this is a
9440      // simple const assignment.
9441      if (DiagID == 0) {
9442        DiagnoseConstAssignment(S, E, Loc);
9443        return true;
9444      }
9445  
9446      break;
9447    case Expr::MLV_ConstAddrSpace:
9448      DiagnoseConstAssignment(S, E, Loc);
9449      return true;
9450    case Expr::MLV_ArrayType:
9451    case Expr::MLV_ArrayTemporary:
9452      DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9453      NeedType = true;
9454      break;
9455    case Expr::MLV_NotObjectType:
9456      DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9457      NeedType = true;
9458      break;
9459    case Expr::MLV_LValueCast:
9460      DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9461      break;
9462    case Expr::MLV_Valid:
9463      llvm_unreachable("did not take early return for MLV_Valid");
9464    case Expr::MLV_InvalidExpression:
9465    case Expr::MLV_MemberFunction:
9466    case Expr::MLV_ClassTemporary:
9467      DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9468      break;
9469    case Expr::MLV_IncompleteType:
9470    case Expr::MLV_IncompleteVoidType:
9471      return S.RequireCompleteType(Loc, E->getType(),
9472               diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9473    case Expr::MLV_DuplicateVectorComponents:
9474      DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9475      break;
9476    case Expr::MLV_NoSetterProperty:
9477      llvm_unreachable("readonly properties should be processed differently");
9478    case Expr::MLV_InvalidMessageExpression:
9479      DiagID = diag::error_readonly_message_assignment;
9480      break;
9481    case Expr::MLV_SubObjCPropertySetting:
9482      DiagID = diag::error_no_subobject_property_setting;
9483      break;
9484    }
9485  
9486    SourceRange Assign;
9487    if (Loc != OrigLoc)
9488      Assign = SourceRange(OrigLoc, OrigLoc);
9489    if (NeedType)
9490      S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9491    else
9492      S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9493    return true;
9494  }
9495  
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)9496  static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9497                                           SourceLocation Loc,
9498                                           Sema &Sema) {
9499    // C / C++ fields
9500    MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9501    MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9502    if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9503      if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9504        Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9505    }
9506  
9507    // Objective-C instance variables
9508    ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9509    ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9510    if (OL && OR && OL->getDecl() == OR->getDecl()) {
9511      DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9512      DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9513      if (RL && RR && RL->getDecl() == RR->getDecl())
9514        Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9515    }
9516  }
9517  
9518  // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)9519  QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9520                                         SourceLocation Loc,
9521                                         QualType CompoundType) {
9522    assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9523  
9524    // Verify that LHS is a modifiable lvalue, and emit error if not.
9525    if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9526      return QualType();
9527  
9528    QualType LHSType = LHSExpr->getType();
9529    QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9530                                               CompoundType;
9531    AssignConvertType ConvTy;
9532    if (CompoundType.isNull()) {
9533      Expr *RHSCheck = RHS.get();
9534  
9535      CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9536  
9537      QualType LHSTy(LHSType);
9538      ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9539      if (RHS.isInvalid())
9540        return QualType();
9541      // Special case of NSObject attributes on c-style pointer types.
9542      if (ConvTy == IncompatiblePointer &&
9543          ((Context.isObjCNSObjectType(LHSType) &&
9544            RHSType->isObjCObjectPointerType()) ||
9545           (Context.isObjCNSObjectType(RHSType) &&
9546            LHSType->isObjCObjectPointerType())))
9547        ConvTy = Compatible;
9548  
9549      if (ConvTy == Compatible &&
9550          LHSType->isObjCObjectType())
9551          Diag(Loc, diag::err_objc_object_assignment)
9552            << LHSType;
9553  
9554      // If the RHS is a unary plus or minus, check to see if they = and + are
9555      // right next to each other.  If so, the user may have typo'd "x =+ 4"
9556      // instead of "x += 4".
9557      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9558        RHSCheck = ICE->getSubExpr();
9559      if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9560        if ((UO->getOpcode() == UO_Plus ||
9561             UO->getOpcode() == UO_Minus) &&
9562            Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9563            // Only if the two operators are exactly adjacent.
9564            Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9565            // And there is a space or other character before the subexpr of the
9566            // unary +/-.  We don't want to warn on "x=-1".
9567            Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9568            UO->getSubExpr()->getLocStart().isFileID()) {
9569          Diag(Loc, diag::warn_not_compound_assign)
9570            << (UO->getOpcode() == UO_Plus ? "+" : "-")
9571            << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9572        }
9573      }
9574  
9575      if (ConvTy == Compatible) {
9576        if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9577          // Warn about retain cycles where a block captures the LHS, but
9578          // not if the LHS is a simple variable into which the block is
9579          // being stored...unless that variable can be captured by reference!
9580          const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9581          const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9582          if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9583            checkRetainCycles(LHSExpr, RHS.get());
9584  
9585          // It is safe to assign a weak reference into a strong variable.
9586          // Although this code can still have problems:
9587          //   id x = self.weakProp;
9588          //   id y = self.weakProp;
9589          // we do not warn to warn spuriously when 'x' and 'y' are on separate
9590          // paths through the function. This should be revisited if
9591          // -Wrepeated-use-of-weak is made flow-sensitive.
9592          if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9593                               RHS.get()->getLocStart()))
9594            getCurFunction()->markSafeWeakUse(RHS.get());
9595  
9596        } else if (getLangOpts().ObjCAutoRefCount) {
9597          checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9598        }
9599      }
9600    } else {
9601      // Compound assignment "x += y"
9602      ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9603    }
9604  
9605    if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9606                                 RHS.get(), AA_Assigning))
9607      return QualType();
9608  
9609    CheckForNullPointerDereference(*this, LHSExpr);
9610  
9611    // C99 6.5.16p3: The type of an assignment expression is the type of the
9612    // left operand unless the left operand has qualified type, in which case
9613    // it is the unqualified version of the type of the left operand.
9614    // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9615    // is converted to the type of the assignment expression (above).
9616    // C++ 5.17p1: the type of the assignment expression is that of its left
9617    // operand.
9618    return (getLangOpts().CPlusPlus
9619            ? LHSType : LHSType.getUnqualifiedType());
9620  }
9621  
9622  // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)9623  static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9624                                     SourceLocation Loc) {
9625    LHS = S.CheckPlaceholderExpr(LHS.get());
9626    RHS = S.CheckPlaceholderExpr(RHS.get());
9627    if (LHS.isInvalid() || RHS.isInvalid())
9628      return QualType();
9629  
9630    // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9631    // operands, but not unary promotions.
9632    // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9633  
9634    // So we treat the LHS as a ignored value, and in C++ we allow the
9635    // containing site to determine what should be done with the RHS.
9636    LHS = S.IgnoredValueConversions(LHS.get());
9637    if (LHS.isInvalid())
9638      return QualType();
9639  
9640    S.DiagnoseUnusedExprResult(LHS.get());
9641  
9642    if (!S.getLangOpts().CPlusPlus) {
9643      RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9644      if (RHS.isInvalid())
9645        return QualType();
9646      if (!RHS.get()->getType()->isVoidType())
9647        S.RequireCompleteType(Loc, RHS.get()->getType(),
9648                              diag::err_incomplete_type);
9649    }
9650  
9651    return RHS.get()->getType();
9652  }
9653  
9654  /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9655  /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)9656  static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9657                                                 ExprValueKind &VK,
9658                                                 ExprObjectKind &OK,
9659                                                 SourceLocation OpLoc,
9660                                                 bool IsInc, bool IsPrefix) {
9661    if (Op->isTypeDependent())
9662      return S.Context.DependentTy;
9663  
9664    QualType ResType = Op->getType();
9665    // Atomic types can be used for increment / decrement where the non-atomic
9666    // versions can, so ignore the _Atomic() specifier for the purpose of
9667    // checking.
9668    if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9669      ResType = ResAtomicType->getValueType();
9670  
9671    assert(!ResType.isNull() && "no type for increment/decrement expression");
9672  
9673    if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9674      // Decrement of bool is not allowed.
9675      if (!IsInc) {
9676        S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9677        return QualType();
9678      }
9679      // Increment of bool sets it to true, but is deprecated.
9680      S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
9681                                                : diag::warn_increment_bool)
9682        << Op->getSourceRange();
9683    } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9684      // Error on enum increments and decrements in C++ mode
9685      S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9686      return QualType();
9687    } else if (ResType->isRealType()) {
9688      // OK!
9689    } else if (ResType->isPointerType()) {
9690      // C99 6.5.2.4p2, 6.5.6p2
9691      if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9692        return QualType();
9693    } else if (ResType->isObjCObjectPointerType()) {
9694      // On modern runtimes, ObjC pointer arithmetic is forbidden.
9695      // Otherwise, we just need a complete type.
9696      if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9697          checkArithmeticOnObjCPointer(S, OpLoc, Op))
9698        return QualType();
9699    } else if (ResType->isAnyComplexType()) {
9700      // C99 does not support ++/-- on complex types, we allow as an extension.
9701      S.Diag(OpLoc, diag::ext_integer_increment_complex)
9702        << ResType << Op->getSourceRange();
9703    } else if (ResType->isPlaceholderType()) {
9704      ExprResult PR = S.CheckPlaceholderExpr(Op);
9705      if (PR.isInvalid()) return QualType();
9706      return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9707                                            IsInc, IsPrefix);
9708    } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9709      // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9710    } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
9711               (ResType->getAs<VectorType>()->getVectorKind() !=
9712                VectorType::AltiVecBool)) {
9713      // The z vector extensions allow ++ and -- for non-bool vectors.
9714    } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9715              ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9716      // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9717    } else {
9718      S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9719        << ResType << int(IsInc) << Op->getSourceRange();
9720      return QualType();
9721    }
9722    // At this point, we know we have a real, complex or pointer type.
9723    // Now make sure the operand is a modifiable lvalue.
9724    if (CheckForModifiableLvalue(Op, OpLoc, S))
9725      return QualType();
9726    // In C++, a prefix increment is the same type as the operand. Otherwise
9727    // (in C or with postfix), the increment is the unqualified type of the
9728    // operand.
9729    if (IsPrefix && S.getLangOpts().CPlusPlus) {
9730      VK = VK_LValue;
9731      OK = Op->getObjectKind();
9732      return ResType;
9733    } else {
9734      VK = VK_RValue;
9735      return ResType.getUnqualifiedType();
9736    }
9737  }
9738  
9739  
9740  /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9741  /// This routine allows us to typecheck complex/recursive expressions
9742  /// where the declaration is needed for type checking. We only need to
9743  /// handle cases when the expression references a function designator
9744  /// or is an lvalue. Here are some examples:
9745  ///  - &(x) => x
9746  ///  - &*****f => f for f a function designator.
9747  ///  - &s.xx => s
9748  ///  - &s.zz[1].yy -> s, if zz is an array
9749  ///  - *(x + 1) -> x, if x is an array
9750  ///  - &"123"[2] -> 0
9751  ///  - & __real__ x -> x
getPrimaryDecl(Expr * E)9752  static ValueDecl *getPrimaryDecl(Expr *E) {
9753    switch (E->getStmtClass()) {
9754    case Stmt::DeclRefExprClass:
9755      return cast<DeclRefExpr>(E)->getDecl();
9756    case Stmt::MemberExprClass:
9757      // If this is an arrow operator, the address is an offset from
9758      // the base's value, so the object the base refers to is
9759      // irrelevant.
9760      if (cast<MemberExpr>(E)->isArrow())
9761        return nullptr;
9762      // Otherwise, the expression refers to a part of the base
9763      return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9764    case Stmt::ArraySubscriptExprClass: {
9765      // FIXME: This code shouldn't be necessary!  We should catch the implicit
9766      // promotion of register arrays earlier.
9767      Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9768      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9769        if (ICE->getSubExpr()->getType()->isArrayType())
9770          return getPrimaryDecl(ICE->getSubExpr());
9771      }
9772      return nullptr;
9773    }
9774    case Stmt::UnaryOperatorClass: {
9775      UnaryOperator *UO = cast<UnaryOperator>(E);
9776  
9777      switch(UO->getOpcode()) {
9778      case UO_Real:
9779      case UO_Imag:
9780      case UO_Extension:
9781        return getPrimaryDecl(UO->getSubExpr());
9782      default:
9783        return nullptr;
9784      }
9785    }
9786    case Stmt::ParenExprClass:
9787      return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9788    case Stmt::ImplicitCastExprClass:
9789      // If the result of an implicit cast is an l-value, we care about
9790      // the sub-expression; otherwise, the result here doesn't matter.
9791      return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9792    default:
9793      return nullptr;
9794    }
9795  }
9796  
9797  namespace {
9798    enum {
9799      AO_Bit_Field = 0,
9800      AO_Vector_Element = 1,
9801      AO_Property_Expansion = 2,
9802      AO_Register_Variable = 3,
9803      AO_No_Error = 4
9804    };
9805  }
9806  /// \brief Diagnose invalid operand for address of operations.
9807  ///
9808  /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)9809  static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9810                                           Expr *E, unsigned Type) {
9811    S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9812  }
9813  
9814  /// CheckAddressOfOperand - The operand of & must be either a function
9815  /// designator or an lvalue designating an object. If it is an lvalue, the
9816  /// object cannot be declared with storage class register or be a bit field.
9817  /// Note: The usual conversions are *not* applied to the operand of the &
9818  /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9819  /// In C++, the operand might be an overloaded function name, in which case
9820  /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)9821  QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9822    if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9823      if (PTy->getKind() == BuiltinType::Overload) {
9824        Expr *E = OrigOp.get()->IgnoreParens();
9825        if (!isa<OverloadExpr>(E)) {
9826          assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9827          Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9828            << OrigOp.get()->getSourceRange();
9829          return QualType();
9830        }
9831  
9832        OverloadExpr *Ovl = cast<OverloadExpr>(E);
9833        if (isa<UnresolvedMemberExpr>(Ovl))
9834          if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9835            Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9836              << OrigOp.get()->getSourceRange();
9837            return QualType();
9838          }
9839  
9840        return Context.OverloadTy;
9841      }
9842  
9843      if (PTy->getKind() == BuiltinType::UnknownAny)
9844        return Context.UnknownAnyTy;
9845  
9846      if (PTy->getKind() == BuiltinType::BoundMember) {
9847        Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9848          << OrigOp.get()->getSourceRange();
9849        return QualType();
9850      }
9851  
9852      OrigOp = CheckPlaceholderExpr(OrigOp.get());
9853      if (OrigOp.isInvalid()) return QualType();
9854    }
9855  
9856    if (OrigOp.get()->isTypeDependent())
9857      return Context.DependentTy;
9858  
9859    assert(!OrigOp.get()->getType()->isPlaceholderType());
9860  
9861    // Make sure to ignore parentheses in subsequent checks
9862    Expr *op = OrigOp.get()->IgnoreParens();
9863  
9864    // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9865    if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9866      Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9867      return QualType();
9868    }
9869  
9870    if (getLangOpts().C99) {
9871      // Implement C99-only parts of addressof rules.
9872      if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9873        if (uOp->getOpcode() == UO_Deref)
9874          // Per C99 6.5.3.2, the address of a deref always returns a valid result
9875          // (assuming the deref expression is valid).
9876          return uOp->getSubExpr()->getType();
9877      }
9878      // Technically, there should be a check for array subscript
9879      // expressions here, but the result of one is always an lvalue anyway.
9880    }
9881    ValueDecl *dcl = getPrimaryDecl(op);
9882  
9883    if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
9884      if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9885                                             op->getLocStart()))
9886        return QualType();
9887  
9888    Expr::LValueClassification lval = op->ClassifyLValue(Context);
9889    unsigned AddressOfError = AO_No_Error;
9890  
9891    if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9892      bool sfinae = (bool)isSFINAEContext();
9893      Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9894                                    : diag::ext_typecheck_addrof_temporary)
9895        << op->getType() << op->getSourceRange();
9896      if (sfinae)
9897        return QualType();
9898      // Materialize the temporary as an lvalue so that we can take its address.
9899      OrigOp = op = new (Context)
9900          MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9901    } else if (isa<ObjCSelectorExpr>(op)) {
9902      return Context.getPointerType(op->getType());
9903    } else if (lval == Expr::LV_MemberFunction) {
9904      // If it's an instance method, make a member pointer.
9905      // The expression must have exactly the form &A::foo.
9906  
9907      // If the underlying expression isn't a decl ref, give up.
9908      if (!isa<DeclRefExpr>(op)) {
9909        Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9910          << OrigOp.get()->getSourceRange();
9911        return QualType();
9912      }
9913      DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9914      CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9915  
9916      // The id-expression was parenthesized.
9917      if (OrigOp.get() != DRE) {
9918        Diag(OpLoc, diag::err_parens_pointer_member_function)
9919          << OrigOp.get()->getSourceRange();
9920  
9921      // The method was named without a qualifier.
9922      } else if (!DRE->getQualifier()) {
9923        if (MD->getParent()->getName().empty())
9924          Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9925            << op->getSourceRange();
9926        else {
9927          SmallString<32> Str;
9928          StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9929          Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9930            << op->getSourceRange()
9931            << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9932        }
9933      }
9934  
9935      // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9936      if (isa<CXXDestructorDecl>(MD))
9937        Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9938  
9939      QualType MPTy = Context.getMemberPointerType(
9940          op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9941      // Under the MS ABI, lock down the inheritance model now.
9942      if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9943        (void)isCompleteType(OpLoc, MPTy);
9944      return MPTy;
9945    } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9946      // C99 6.5.3.2p1
9947      // The operand must be either an l-value or a function designator
9948      if (!op->getType()->isFunctionType()) {
9949        // Use a special diagnostic for loads from property references.
9950        if (isa<PseudoObjectExpr>(op)) {
9951          AddressOfError = AO_Property_Expansion;
9952        } else {
9953          Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9954            << op->getType() << op->getSourceRange();
9955          return QualType();
9956        }
9957      }
9958    } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9959      // The operand cannot be a bit-field
9960      AddressOfError = AO_Bit_Field;
9961    } else if (op->getObjectKind() == OK_VectorComponent) {
9962      // The operand cannot be an element of a vector
9963      AddressOfError = AO_Vector_Element;
9964    } else if (dcl) { // C99 6.5.3.2p1
9965      // We have an lvalue with a decl. Make sure the decl is not declared
9966      // with the register storage-class specifier.
9967      if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9968        // in C++ it is not error to take address of a register
9969        // variable (c++03 7.1.1P3)
9970        if (vd->getStorageClass() == SC_Register &&
9971            !getLangOpts().CPlusPlus) {
9972          AddressOfError = AO_Register_Variable;
9973        }
9974      } else if (isa<MSPropertyDecl>(dcl)) {
9975        AddressOfError = AO_Property_Expansion;
9976      } else if (isa<FunctionTemplateDecl>(dcl)) {
9977        return Context.OverloadTy;
9978      } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9979        // Okay: we can take the address of a field.
9980        // Could be a pointer to member, though, if there is an explicit
9981        // scope qualifier for the class.
9982        if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9983          DeclContext *Ctx = dcl->getDeclContext();
9984          if (Ctx && Ctx->isRecord()) {
9985            if (dcl->getType()->isReferenceType()) {
9986              Diag(OpLoc,
9987                   diag::err_cannot_form_pointer_to_member_of_reference_type)
9988                << dcl->getDeclName() << dcl->getType();
9989              return QualType();
9990            }
9991  
9992            while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9993              Ctx = Ctx->getParent();
9994  
9995            QualType MPTy = Context.getMemberPointerType(
9996                op->getType(),
9997                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9998            // Under the MS ABI, lock down the inheritance model now.
9999            if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10000              (void)isCompleteType(OpLoc, MPTy);
10001            return MPTy;
10002          }
10003        }
10004      } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10005        llvm_unreachable("Unknown/unexpected decl type");
10006    }
10007  
10008    if (AddressOfError != AO_No_Error) {
10009      diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10010      return QualType();
10011    }
10012  
10013    if (lval == Expr::LV_IncompleteVoidType) {
10014      // Taking the address of a void variable is technically illegal, but we
10015      // allow it in cases which are otherwise valid.
10016      // Example: "extern void x; void* y = &x;".
10017      Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10018    }
10019  
10020    // If the operand has type "type", the result has type "pointer to type".
10021    if (op->getType()->isObjCObjectType())
10022      return Context.getObjCObjectPointerType(op->getType());
10023    return Context.getPointerType(op->getType());
10024  }
10025  
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)10026  static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10027    const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10028    if (!DRE)
10029      return;
10030    const Decl *D = DRE->getDecl();
10031    if (!D)
10032      return;
10033    const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10034    if (!Param)
10035      return;
10036    if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10037      if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10038        return;
10039    if (FunctionScopeInfo *FD = S.getCurFunction())
10040      if (!FD->ModifiedNonNullParams.count(Param))
10041        FD->ModifiedNonNullParams.insert(Param);
10042  }
10043  
10044  /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)10045  static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10046                                          SourceLocation OpLoc) {
10047    if (Op->isTypeDependent())
10048      return S.Context.DependentTy;
10049  
10050    ExprResult ConvResult = S.UsualUnaryConversions(Op);
10051    if (ConvResult.isInvalid())
10052      return QualType();
10053    Op = ConvResult.get();
10054    QualType OpTy = Op->getType();
10055    QualType Result;
10056  
10057    if (isa<CXXReinterpretCastExpr>(Op)) {
10058      QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10059      S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10060                                       Op->getSourceRange());
10061    }
10062  
10063    if (const PointerType *PT = OpTy->getAs<PointerType>())
10064      Result = PT->getPointeeType();
10065    else if (const ObjCObjectPointerType *OPT =
10066               OpTy->getAs<ObjCObjectPointerType>())
10067      Result = OPT->getPointeeType();
10068    else {
10069      ExprResult PR = S.CheckPlaceholderExpr(Op);
10070      if (PR.isInvalid()) return QualType();
10071      if (PR.get() != Op)
10072        return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10073    }
10074  
10075    if (Result.isNull()) {
10076      S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10077        << OpTy << Op->getSourceRange();
10078      return QualType();
10079    }
10080  
10081    // Note that per both C89 and C99, indirection is always legal, even if Result
10082    // is an incomplete type or void.  It would be possible to warn about
10083    // dereferencing a void pointer, but it's completely well-defined, and such a
10084    // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10085    // for pointers to 'void' but is fine for any other pointer type:
10086    //
10087    // C++ [expr.unary.op]p1:
10088    //   [...] the expression to which [the unary * operator] is applied shall
10089    //   be a pointer to an object type, or a pointer to a function type
10090    if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10091      S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10092        << OpTy << Op->getSourceRange();
10093  
10094    // Dereferences are usually l-values...
10095    VK = VK_LValue;
10096  
10097    // ...except that certain expressions are never l-values in C.
10098    if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10099      VK = VK_RValue;
10100  
10101    return Result;
10102  }
10103  
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)10104  BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10105    BinaryOperatorKind Opc;
10106    switch (Kind) {
10107    default: llvm_unreachable("Unknown binop!");
10108    case tok::periodstar:           Opc = BO_PtrMemD; break;
10109    case tok::arrowstar:            Opc = BO_PtrMemI; break;
10110    case tok::star:                 Opc = BO_Mul; break;
10111    case tok::slash:                Opc = BO_Div; break;
10112    case tok::percent:              Opc = BO_Rem; break;
10113    case tok::plus:                 Opc = BO_Add; break;
10114    case tok::minus:                Opc = BO_Sub; break;
10115    case tok::lessless:             Opc = BO_Shl; break;
10116    case tok::greatergreater:       Opc = BO_Shr; break;
10117    case tok::lessequal:            Opc = BO_LE; break;
10118    case tok::less:                 Opc = BO_LT; break;
10119    case tok::greaterequal:         Opc = BO_GE; break;
10120    case tok::greater:              Opc = BO_GT; break;
10121    case tok::exclaimequal:         Opc = BO_NE; break;
10122    case tok::equalequal:           Opc = BO_EQ; break;
10123    case tok::amp:                  Opc = BO_And; break;
10124    case tok::caret:                Opc = BO_Xor; break;
10125    case tok::pipe:                 Opc = BO_Or; break;
10126    case tok::ampamp:               Opc = BO_LAnd; break;
10127    case tok::pipepipe:             Opc = BO_LOr; break;
10128    case tok::equal:                Opc = BO_Assign; break;
10129    case tok::starequal:            Opc = BO_MulAssign; break;
10130    case tok::slashequal:           Opc = BO_DivAssign; break;
10131    case tok::percentequal:         Opc = BO_RemAssign; break;
10132    case tok::plusequal:            Opc = BO_AddAssign; break;
10133    case tok::minusequal:           Opc = BO_SubAssign; break;
10134    case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10135    case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10136    case tok::ampequal:             Opc = BO_AndAssign; break;
10137    case tok::caretequal:           Opc = BO_XorAssign; break;
10138    case tok::pipeequal:            Opc = BO_OrAssign; break;
10139    case tok::comma:                Opc = BO_Comma; break;
10140    }
10141    return Opc;
10142  }
10143  
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)10144  static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10145    tok::TokenKind Kind) {
10146    UnaryOperatorKind Opc;
10147    switch (Kind) {
10148    default: llvm_unreachable("Unknown unary op!");
10149    case tok::plusplus:     Opc = UO_PreInc; break;
10150    case tok::minusminus:   Opc = UO_PreDec; break;
10151    case tok::amp:          Opc = UO_AddrOf; break;
10152    case tok::star:         Opc = UO_Deref; break;
10153    case tok::plus:         Opc = UO_Plus; break;
10154    case tok::minus:        Opc = UO_Minus; break;
10155    case tok::tilde:        Opc = UO_Not; break;
10156    case tok::exclaim:      Opc = UO_LNot; break;
10157    case tok::kw___real:    Opc = UO_Real; break;
10158    case tok::kw___imag:    Opc = UO_Imag; break;
10159    case tok::kw___extension__: Opc = UO_Extension; break;
10160    }
10161    return Opc;
10162  }
10163  
10164  /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10165  /// This warning is only emitted for builtin assignment operations. It is also
10166  /// suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc)10167  static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10168                                     SourceLocation OpLoc) {
10169    if (!S.ActiveTemplateInstantiations.empty())
10170      return;
10171    if (OpLoc.isInvalid() || OpLoc.isMacroID())
10172      return;
10173    LHSExpr = LHSExpr->IgnoreParenImpCasts();
10174    RHSExpr = RHSExpr->IgnoreParenImpCasts();
10175    const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10176    const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10177    if (!LHSDeclRef || !RHSDeclRef ||
10178        LHSDeclRef->getLocation().isMacroID() ||
10179        RHSDeclRef->getLocation().isMacroID())
10180      return;
10181    const ValueDecl *LHSDecl =
10182      cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10183    const ValueDecl *RHSDecl =
10184      cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10185    if (LHSDecl != RHSDecl)
10186      return;
10187    if (LHSDecl->getType().isVolatileQualified())
10188      return;
10189    if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10190      if (RefTy->getPointeeType().isVolatileQualified())
10191        return;
10192  
10193    S.Diag(OpLoc, diag::warn_self_assignment)
10194        << LHSDeclRef->getType()
10195        << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10196  }
10197  
10198  /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10199  /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)10200  static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10201                                            SourceLocation OpLoc) {
10202    if (!S.getLangOpts().ObjC1)
10203      return;
10204  
10205    const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10206    const Expr *LHS = L.get();
10207    const Expr *RHS = R.get();
10208  
10209    if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10210      ObjCPointerExpr = LHS;
10211      OtherExpr = RHS;
10212    }
10213    else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10214      ObjCPointerExpr = RHS;
10215      OtherExpr = LHS;
10216    }
10217  
10218    // This warning is deliberately made very specific to reduce false
10219    // positives with logic that uses '&' for hashing.  This logic mainly
10220    // looks for code trying to introspect into tagged pointers, which
10221    // code should generally never do.
10222    if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10223      unsigned Diag = diag::warn_objc_pointer_masking;
10224      // Determine if we are introspecting the result of performSelectorXXX.
10225      const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10226      // Special case messages to -performSelector and friends, which
10227      // can return non-pointer values boxed in a pointer value.
10228      // Some clients may wish to silence warnings in this subcase.
10229      if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10230        Selector S = ME->getSelector();
10231        StringRef SelArg0 = S.getNameForSlot(0);
10232        if (SelArg0.startswith("performSelector"))
10233          Diag = diag::warn_objc_pointer_masking_performSelector;
10234      }
10235  
10236      S.Diag(OpLoc, Diag)
10237        << ObjCPointerExpr->getSourceRange();
10238    }
10239  }
10240  
getDeclFromExpr(Expr * E)10241  static NamedDecl *getDeclFromExpr(Expr *E) {
10242    if (!E)
10243      return nullptr;
10244    if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10245      return DRE->getDecl();
10246    if (auto *ME = dyn_cast<MemberExpr>(E))
10247      return ME->getMemberDecl();
10248    if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10249      return IRE->getDecl();
10250    return nullptr;
10251  }
10252  
10253  /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10254  /// operator @p Opc at location @c TokLoc. This routine only supports
10255  /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)10256  ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10257                                      BinaryOperatorKind Opc,
10258                                      Expr *LHSExpr, Expr *RHSExpr) {
10259    if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10260      // The syntax only allows initializer lists on the RHS of assignment,
10261      // so we don't need to worry about accepting invalid code for
10262      // non-assignment operators.
10263      // C++11 5.17p9:
10264      //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10265      //   of x = {} is x = T().
10266      InitializationKind Kind =
10267          InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10268      InitializedEntity Entity =
10269          InitializedEntity::InitializeTemporary(LHSExpr->getType());
10270      InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10271      ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10272      if (Init.isInvalid())
10273        return Init;
10274      RHSExpr = Init.get();
10275    }
10276  
10277    ExprResult LHS = LHSExpr, RHS = RHSExpr;
10278    QualType ResultTy;     // Result type of the binary operator.
10279    // The following two variables are used for compound assignment operators
10280    QualType CompLHSTy;    // Type of LHS after promotions for computation
10281    QualType CompResultTy; // Type of computation result
10282    ExprValueKind VK = VK_RValue;
10283    ExprObjectKind OK = OK_Ordinary;
10284  
10285    if (!getLangOpts().CPlusPlus) {
10286      // C cannot handle TypoExpr nodes on either side of a binop because it
10287      // doesn't handle dependent types properly, so make sure any TypoExprs have
10288      // been dealt with before checking the operands.
10289      LHS = CorrectDelayedTyposInExpr(LHSExpr);
10290      RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10291        if (Opc != BO_Assign)
10292          return ExprResult(E);
10293        // Avoid correcting the RHS to the same Expr as the LHS.
10294        Decl *D = getDeclFromExpr(E);
10295        return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10296      });
10297      if (!LHS.isUsable() || !RHS.isUsable())
10298        return ExprError();
10299    }
10300  
10301    if (getLangOpts().OpenCL) {
10302      // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10303      // the ATOMIC_VAR_INIT macro.
10304      if (LHSExpr->getType()->isAtomicType() ||
10305          RHSExpr->getType()->isAtomicType()) {
10306        SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10307        if (BO_Assign == Opc)
10308          Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10309        else
10310          ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10311        return ExprError();
10312      }
10313    }
10314  
10315    switch (Opc) {
10316    case BO_Assign:
10317      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10318      if (getLangOpts().CPlusPlus &&
10319          LHS.get()->getObjectKind() != OK_ObjCProperty) {
10320        VK = LHS.get()->getValueKind();
10321        OK = LHS.get()->getObjectKind();
10322      }
10323      if (!ResultTy.isNull()) {
10324        DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10325        DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10326      }
10327      RecordModifiableNonNullParam(*this, LHS.get());
10328      break;
10329    case BO_PtrMemD:
10330    case BO_PtrMemI:
10331      ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10332                                              Opc == BO_PtrMemI);
10333      break;
10334    case BO_Mul:
10335    case BO_Div:
10336      ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10337                                             Opc == BO_Div);
10338      break;
10339    case BO_Rem:
10340      ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10341      break;
10342    case BO_Add:
10343      ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10344      break;
10345    case BO_Sub:
10346      ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10347      break;
10348    case BO_Shl:
10349    case BO_Shr:
10350      ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10351      break;
10352    case BO_LE:
10353    case BO_LT:
10354    case BO_GE:
10355    case BO_GT:
10356      ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10357      break;
10358    case BO_EQ:
10359    case BO_NE:
10360      ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10361      break;
10362    case BO_And:
10363      checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10364    case BO_Xor:
10365    case BO_Or:
10366      ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10367      break;
10368    case BO_LAnd:
10369    case BO_LOr:
10370      ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10371      break;
10372    case BO_MulAssign:
10373    case BO_DivAssign:
10374      CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10375                                                 Opc == BO_DivAssign);
10376      CompLHSTy = CompResultTy;
10377      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10378        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10379      break;
10380    case BO_RemAssign:
10381      CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10382      CompLHSTy = CompResultTy;
10383      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10384        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10385      break;
10386    case BO_AddAssign:
10387      CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10388      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10389        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10390      break;
10391    case BO_SubAssign:
10392      CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10393      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10394        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10395      break;
10396    case BO_ShlAssign:
10397    case BO_ShrAssign:
10398      CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10399      CompLHSTy = CompResultTy;
10400      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10401        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10402      break;
10403    case BO_AndAssign:
10404    case BO_OrAssign: // fallthrough
10405      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10406    case BO_XorAssign:
10407      CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10408      CompLHSTy = CompResultTy;
10409      if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10410        ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10411      break;
10412    case BO_Comma:
10413      ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10414      if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10415        VK = RHS.get()->getValueKind();
10416        OK = RHS.get()->getObjectKind();
10417      }
10418      break;
10419    }
10420    if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10421      return ExprError();
10422  
10423    // Check for array bounds violations for both sides of the BinaryOperator
10424    CheckArrayAccess(LHS.get());
10425    CheckArrayAccess(RHS.get());
10426  
10427    if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10428      NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10429                                                   &Context.Idents.get("object_setClass"),
10430                                                   SourceLocation(), LookupOrdinaryName);
10431      if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10432        SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10433        Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10434        FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10435        FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10436        FixItHint::CreateInsertion(RHSLocEnd, ")");
10437      }
10438      else
10439        Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10440    }
10441    else if (const ObjCIvarRefExpr *OIRE =
10442             dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10443      DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10444  
10445    if (CompResultTy.isNull())
10446      return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10447                                          OK, OpLoc, FPFeatures.fp_contract);
10448    if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10449        OK_ObjCProperty) {
10450      VK = VK_LValue;
10451      OK = LHS.get()->getObjectKind();
10452    }
10453    return new (Context) CompoundAssignOperator(
10454        LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10455        OpLoc, FPFeatures.fp_contract);
10456  }
10457  
10458  /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10459  /// operators are mixed in a way that suggests that the programmer forgot that
10460  /// comparison operators have higher precedence. The most typical example of
10461  /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10462  static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10463                                        SourceLocation OpLoc, Expr *LHSExpr,
10464                                        Expr *RHSExpr) {
10465    BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10466    BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10467  
10468    // Check that one of the sides is a comparison operator and the other isn't.
10469    bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10470    bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10471    if (isLeftComp == isRightComp)
10472      return;
10473  
10474    // Bitwise operations are sometimes used as eager logical ops.
10475    // Don't diagnose this.
10476    bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10477    bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10478    if (isLeftBitwise || isRightBitwise)
10479      return;
10480  
10481    SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10482                                                     OpLoc)
10483                                       : SourceRange(OpLoc, RHSExpr->getLocEnd());
10484    StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10485    SourceRange ParensRange = isLeftComp ?
10486        SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10487      : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10488  
10489    Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10490      << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10491    SuggestParentheses(Self, OpLoc,
10492      Self.PDiag(diag::note_precedence_silence) << OpStr,
10493      (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10494    SuggestParentheses(Self, OpLoc,
10495      Self.PDiag(diag::note_precedence_bitwise_first)
10496        << BinaryOperator::getOpcodeStr(Opc),
10497      ParensRange);
10498  }
10499  
10500  /// \brief It accepts a '&&' expr that is inside a '||' one.
10501  /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10502  /// in parentheses.
10503  static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)10504  EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10505                                         BinaryOperator *Bop) {
10506    assert(Bop->getOpcode() == BO_LAnd);
10507    Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10508        << Bop->getSourceRange() << OpLoc;
10509    SuggestParentheses(Self, Bop->getOperatorLoc(),
10510      Self.PDiag(diag::note_precedence_silence)
10511        << Bop->getOpcodeStr(),
10512      Bop->getSourceRange());
10513  }
10514  
10515  /// \brief Returns true if the given expression can be evaluated as a constant
10516  /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)10517  static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10518    bool Res;
10519    return !E->isValueDependent() &&
10520           E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10521  }
10522  
10523  /// \brief Returns true if the given expression can be evaluated as a constant
10524  /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)10525  static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10526    bool Res;
10527    return !E->isValueDependent() &&
10528           E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10529  }
10530  
10531  /// \brief Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10532  static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10533                                               Expr *LHSExpr, Expr *RHSExpr) {
10534    if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10535      if (Bop->getOpcode() == BO_LAnd) {
10536        // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10537        if (EvaluatesAsFalse(S, RHSExpr))
10538          return;
10539        // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10540        if (!EvaluatesAsTrue(S, Bop->getLHS()))
10541          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10542      } else if (Bop->getOpcode() == BO_LOr) {
10543        if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10544          // If it's "a || b && 1 || c" we didn't warn earlier for
10545          // "a || b && 1", but warn now.
10546          if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10547            return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10548        }
10549      }
10550    }
10551  }
10552  
10553  /// \brief Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10554  static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10555                                               Expr *LHSExpr, Expr *RHSExpr) {
10556    if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10557      if (Bop->getOpcode() == BO_LAnd) {
10558        // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10559        if (EvaluatesAsFalse(S, LHSExpr))
10560          return;
10561        // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10562        if (!EvaluatesAsTrue(S, Bop->getRHS()))
10563          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10564      }
10565    }
10566  }
10567  
10568  /// \brief Look for bitwise op in the left or right hand of a bitwise op with
10569  /// lower precedence and emit a diagnostic together with a fixit hint that wraps
10570  /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)10571  static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
10572                                           SourceLocation OpLoc, Expr *SubExpr) {
10573    if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10574      if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
10575        S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
10576          << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
10577          << Bop->getSourceRange() << OpLoc;
10578        SuggestParentheses(S, Bop->getOperatorLoc(),
10579          S.PDiag(diag::note_precedence_silence)
10580            << Bop->getOpcodeStr(),
10581          Bop->getSourceRange());
10582      }
10583    }
10584  }
10585  
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)10586  static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10587                                      Expr *SubExpr, StringRef Shift) {
10588    if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10589      if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10590        StringRef Op = Bop->getOpcodeStr();
10591        S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10592            << Bop->getSourceRange() << OpLoc << Shift << Op;
10593        SuggestParentheses(S, Bop->getOperatorLoc(),
10594            S.PDiag(diag::note_precedence_silence) << Op,
10595            Bop->getSourceRange());
10596      }
10597    }
10598  }
10599  
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10600  static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10601                                   Expr *LHSExpr, Expr *RHSExpr) {
10602    CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10603    if (!OCE)
10604      return;
10605  
10606    FunctionDecl *FD = OCE->getDirectCallee();
10607    if (!FD || !FD->isOverloadedOperator())
10608      return;
10609  
10610    OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10611    if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10612      return;
10613  
10614    S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10615        << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10616        << (Kind == OO_LessLess);
10617    SuggestParentheses(S, OCE->getOperatorLoc(),
10618                       S.PDiag(diag::note_precedence_silence)
10619                           << (Kind == OO_LessLess ? "<<" : ">>"),
10620                       OCE->getSourceRange());
10621    SuggestParentheses(S, OpLoc,
10622                       S.PDiag(diag::note_evaluate_comparison_first),
10623                       SourceRange(OCE->getArg(1)->getLocStart(),
10624                                   RHSExpr->getLocEnd()));
10625  }
10626  
10627  /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10628  /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10629  static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10630                                      SourceLocation OpLoc, Expr *LHSExpr,
10631                                      Expr *RHSExpr){
10632    // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10633    if (BinaryOperator::isBitwiseOp(Opc))
10634      DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10635  
10636    // Diagnose "arg1 & arg2 | arg3"
10637    if ((Opc == BO_Or || Opc == BO_Xor) &&
10638        !OpLoc.isMacroID()/* Don't warn in macros. */) {
10639      DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
10640      DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
10641    }
10642  
10643    // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10644    // We don't warn for 'assert(a || b && "bad")' since this is safe.
10645    if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10646      DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10647      DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10648    }
10649  
10650    if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10651        || Opc == BO_Shr) {
10652      StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10653      DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10654      DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10655    }
10656  
10657    // Warn on overloaded shift operators and comparisons, such as:
10658    // cout << 5 == 4;
10659    if (BinaryOperator::isComparisonOp(Opc))
10660      DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10661  }
10662  
10663  // Binary Operators.  'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)10664  ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10665                              tok::TokenKind Kind,
10666                              Expr *LHSExpr, Expr *RHSExpr) {
10667    BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10668    assert(LHSExpr && "ActOnBinOp(): missing left expression");
10669    assert(RHSExpr && "ActOnBinOp(): missing right expression");
10670  
10671    // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10672    DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10673  
10674    return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10675  }
10676  
10677  /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)10678  static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10679                                         BinaryOperatorKind Opc,
10680                                         Expr *LHS, Expr *RHS) {
10681    // Find all of the overloaded operators visible from this
10682    // point. We perform both an operator-name lookup from the local
10683    // scope and an argument-dependent lookup based on the types of
10684    // the arguments.
10685    UnresolvedSet<16> Functions;
10686    OverloadedOperatorKind OverOp
10687      = BinaryOperator::getOverloadedOperator(Opc);
10688    if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10689      S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10690                                     RHS->getType(), Functions);
10691  
10692    // Build the (potentially-overloaded, potentially-dependent)
10693    // binary operation.
10694    return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10695  }
10696  
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)10697  ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10698                              BinaryOperatorKind Opc,
10699                              Expr *LHSExpr, Expr *RHSExpr) {
10700    // We want to end up calling one of checkPseudoObjectAssignment
10701    // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10702    // both expressions are overloadable or either is type-dependent),
10703    // or CreateBuiltinBinOp (in any other case).  We also want to get
10704    // any placeholder types out of the way.
10705  
10706    // Handle pseudo-objects in the LHS.
10707    if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10708      // Assignments with a pseudo-object l-value need special analysis.
10709      if (pty->getKind() == BuiltinType::PseudoObject &&
10710          BinaryOperator::isAssignmentOp(Opc))
10711        return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10712  
10713      // Don't resolve overloads if the other type is overloadable.
10714      if (pty->getKind() == BuiltinType::Overload) {
10715        // We can't actually test that if we still have a placeholder,
10716        // though.  Fortunately, none of the exceptions we see in that
10717        // code below are valid when the LHS is an overload set.  Note
10718        // that an overload set can be dependently-typed, but it never
10719        // instantiates to having an overloadable type.
10720        ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10721        if (resolvedRHS.isInvalid()) return ExprError();
10722        RHSExpr = resolvedRHS.get();
10723  
10724        if (RHSExpr->isTypeDependent() ||
10725            RHSExpr->getType()->isOverloadableType())
10726          return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10727      }
10728  
10729      ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10730      if (LHS.isInvalid()) return ExprError();
10731      LHSExpr = LHS.get();
10732    }
10733  
10734    // Handle pseudo-objects in the RHS.
10735    if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10736      // An overload in the RHS can potentially be resolved by the type
10737      // being assigned to.
10738      if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10739        if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10740          return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10741  
10742        if (LHSExpr->getType()->isOverloadableType())
10743          return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10744  
10745        return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10746      }
10747  
10748      // Don't resolve overloads if the other type is overloadable.
10749      if (pty->getKind() == BuiltinType::Overload &&
10750          LHSExpr->getType()->isOverloadableType())
10751        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10752  
10753      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10754      if (!resolvedRHS.isUsable()) return ExprError();
10755      RHSExpr = resolvedRHS.get();
10756    }
10757  
10758    if (getLangOpts().CPlusPlus) {
10759      // If either expression is type-dependent, always build an
10760      // overloaded op.
10761      if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10762        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10763  
10764      // Otherwise, build an overloaded op if either expression has an
10765      // overloadable type.
10766      if (LHSExpr->getType()->isOverloadableType() ||
10767          RHSExpr->getType()->isOverloadableType())
10768        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10769    }
10770  
10771    // Build a built-in binary operation.
10772    return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10773  }
10774  
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)10775  ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10776                                        UnaryOperatorKind Opc,
10777                                        Expr *InputExpr) {
10778    ExprResult Input = InputExpr;
10779    ExprValueKind VK = VK_RValue;
10780    ExprObjectKind OK = OK_Ordinary;
10781    QualType resultType;
10782    if (getLangOpts().OpenCL) {
10783      // The only legal unary operation for atomics is '&'.
10784      if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
10785        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10786                         << InputExpr->getType()
10787                         << Input.get()->getSourceRange());
10788      }
10789    }
10790    switch (Opc) {
10791    case UO_PreInc:
10792    case UO_PreDec:
10793    case UO_PostInc:
10794    case UO_PostDec:
10795      resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10796                                                  OpLoc,
10797                                                  Opc == UO_PreInc ||
10798                                                  Opc == UO_PostInc,
10799                                                  Opc == UO_PreInc ||
10800                                                  Opc == UO_PreDec);
10801      break;
10802    case UO_AddrOf:
10803      resultType = CheckAddressOfOperand(Input, OpLoc);
10804      RecordModifiableNonNullParam(*this, InputExpr);
10805      break;
10806    case UO_Deref: {
10807      Input = DefaultFunctionArrayLvalueConversion(Input.get());
10808      if (Input.isInvalid()) return ExprError();
10809      resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10810      break;
10811    }
10812    case UO_Plus:
10813    case UO_Minus:
10814      Input = UsualUnaryConversions(Input.get());
10815      if (Input.isInvalid()) return ExprError();
10816      resultType = Input.get()->getType();
10817      if (resultType->isDependentType())
10818        break;
10819      if (resultType->isArithmeticType()) // C99 6.5.3.3p1
10820        break;
10821      else if (resultType->isVectorType() &&
10822               // The z vector extensions don't allow + or - with bool vectors.
10823               (!Context.getLangOpts().ZVector ||
10824                resultType->getAs<VectorType>()->getVectorKind() !=
10825                VectorType::AltiVecBool))
10826        break;
10827      else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
10828               Opc == UO_Plus &&
10829               resultType->isPointerType())
10830        break;
10831  
10832      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10833        << resultType << Input.get()->getSourceRange());
10834  
10835    case UO_Not: // bitwise complement
10836      Input = UsualUnaryConversions(Input.get());
10837      if (Input.isInvalid())
10838        return ExprError();
10839      resultType = Input.get()->getType();
10840      if (resultType->isDependentType())
10841        break;
10842      // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10843      if (resultType->isComplexType() || resultType->isComplexIntegerType())
10844        // C99 does not support '~' for complex conjugation.
10845        Diag(OpLoc, diag::ext_integer_complement_complex)
10846            << resultType << Input.get()->getSourceRange();
10847      else if (resultType->hasIntegerRepresentation())
10848        break;
10849      else if (resultType->isExtVectorType()) {
10850        if (Context.getLangOpts().OpenCL) {
10851          // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10852          // on vector float types.
10853          QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10854          if (!T->isIntegerType())
10855            return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10856                             << resultType << Input.get()->getSourceRange());
10857        }
10858        break;
10859      } else {
10860        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10861                         << resultType << Input.get()->getSourceRange());
10862      }
10863      break;
10864  
10865    case UO_LNot: // logical negation
10866      // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10867      Input = DefaultFunctionArrayLvalueConversion(Input.get());
10868      if (Input.isInvalid()) return ExprError();
10869      resultType = Input.get()->getType();
10870  
10871      // Though we still have to promote half FP to float...
10872      if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10873        Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10874        resultType = Context.FloatTy;
10875      }
10876  
10877      if (resultType->isDependentType())
10878        break;
10879      if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10880        // C99 6.5.3.3p1: ok, fallthrough;
10881        if (Context.getLangOpts().CPlusPlus) {
10882          // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10883          // operand contextually converted to bool.
10884          Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10885                                    ScalarTypeToBooleanCastKind(resultType));
10886        } else if (Context.getLangOpts().OpenCL &&
10887                   Context.getLangOpts().OpenCLVersion < 120) {
10888          // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10889          // operate on scalar float types.
10890          if (!resultType->isIntegerType())
10891            return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10892                             << resultType << Input.get()->getSourceRange());
10893        }
10894      } else if (resultType->isExtVectorType()) {
10895        if (Context.getLangOpts().OpenCL &&
10896            Context.getLangOpts().OpenCLVersion < 120) {
10897          // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10898          // operate on vector float types.
10899          QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10900          if (!T->isIntegerType())
10901            return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10902                             << resultType << Input.get()->getSourceRange());
10903        }
10904        // Vector logical not returns the signed variant of the operand type.
10905        resultType = GetSignedVectorType(resultType);
10906        break;
10907      } else {
10908        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10909          << resultType << Input.get()->getSourceRange());
10910      }
10911  
10912      // LNot always has type int. C99 6.5.3.3p5.
10913      // In C++, it's bool. C++ 5.3.1p8
10914      resultType = Context.getLogicalOperationType();
10915      break;
10916    case UO_Real:
10917    case UO_Imag:
10918      resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10919      // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10920      // complex l-values to ordinary l-values and all other values to r-values.
10921      if (Input.isInvalid()) return ExprError();
10922      if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10923        if (Input.get()->getValueKind() != VK_RValue &&
10924            Input.get()->getObjectKind() == OK_Ordinary)
10925          VK = Input.get()->getValueKind();
10926      } else if (!getLangOpts().CPlusPlus) {
10927        // In C, a volatile scalar is read by __imag. In C++, it is not.
10928        Input = DefaultLvalueConversion(Input.get());
10929      }
10930      break;
10931    case UO_Extension:
10932    case UO_Coawait:
10933      resultType = Input.get()->getType();
10934      VK = Input.get()->getValueKind();
10935      OK = Input.get()->getObjectKind();
10936      break;
10937    }
10938    if (resultType.isNull() || Input.isInvalid())
10939      return ExprError();
10940  
10941    // Check for array bounds violations in the operand of the UnaryOperator,
10942    // except for the '*' and '&' operators that have to be handled specially
10943    // by CheckArrayAccess (as there are special cases like &array[arraysize]
10944    // that are explicitly defined as valid by the standard).
10945    if (Opc != UO_AddrOf && Opc != UO_Deref)
10946      CheckArrayAccess(Input.get());
10947  
10948    return new (Context)
10949        UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10950  }
10951  
10952  /// \brief Determine whether the given expression is a qualified member
10953  /// access expression, of a form that could be turned into a pointer to member
10954  /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)10955  static bool isQualifiedMemberAccess(Expr *E) {
10956    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10957      if (!DRE->getQualifier())
10958        return false;
10959  
10960      ValueDecl *VD = DRE->getDecl();
10961      if (!VD->isCXXClassMember())
10962        return false;
10963  
10964      if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10965        return true;
10966      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10967        return Method->isInstance();
10968  
10969      return false;
10970    }
10971  
10972    if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10973      if (!ULE->getQualifier())
10974        return false;
10975  
10976      for (NamedDecl *D : ULE->decls()) {
10977        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
10978          if (Method->isInstance())
10979            return true;
10980        } else {
10981          // Overload set does not contain methods.
10982          break;
10983        }
10984      }
10985  
10986      return false;
10987    }
10988  
10989    return false;
10990  }
10991  
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)10992  ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10993                                UnaryOperatorKind Opc, Expr *Input) {
10994    // First things first: handle placeholders so that the
10995    // overloaded-operator check considers the right type.
10996    if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10997      // Increment and decrement of pseudo-object references.
10998      if (pty->getKind() == BuiltinType::PseudoObject &&
10999          UnaryOperator::isIncrementDecrementOp(Opc))
11000        return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11001  
11002      // extension is always a builtin operator.
11003      if (Opc == UO_Extension)
11004        return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11005  
11006      // & gets special logic for several kinds of placeholder.
11007      // The builtin code knows what to do.
11008      if (Opc == UO_AddrOf &&
11009          (pty->getKind() == BuiltinType::Overload ||
11010           pty->getKind() == BuiltinType::UnknownAny ||
11011           pty->getKind() == BuiltinType::BoundMember))
11012        return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11013  
11014      // Anything else needs to be handled now.
11015      ExprResult Result = CheckPlaceholderExpr(Input);
11016      if (Result.isInvalid()) return ExprError();
11017      Input = Result.get();
11018    }
11019  
11020    if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11021        UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11022        !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11023      // Find all of the overloaded operators visible from this
11024      // point. We perform both an operator-name lookup from the local
11025      // scope and an argument-dependent lookup based on the types of
11026      // the arguments.
11027      UnresolvedSet<16> Functions;
11028      OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11029      if (S && OverOp != OO_None)
11030        LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11031                                     Functions);
11032  
11033      return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11034    }
11035  
11036    return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11037  }
11038  
11039  // Unary Operators.  'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)11040  ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11041                                tok::TokenKind Op, Expr *Input) {
11042    return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11043  }
11044  
11045  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)11046  ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11047                                  LabelDecl *TheDecl) {
11048    TheDecl->markUsed(Context);
11049    // Create the AST node.  The address of a label always has type 'void*'.
11050    return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11051                                       Context.getPointerType(Context.VoidTy));
11052  }
11053  
11054  /// Given the last statement in a statement-expression, check whether
11055  /// the result is a producing expression (like a call to an
11056  /// ns_returns_retained function) and, if so, rebuild it to hoist the
11057  /// release out of the full-expression.  Otherwise, return null.
11058  /// Cannot fail.
maybeRebuildARCConsumingStmt(Stmt * Statement)11059  static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11060    // Should always be wrapped with one of these.
11061    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11062    if (!cleanups) return nullptr;
11063  
11064    ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11065    if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11066      return nullptr;
11067  
11068    // Splice out the cast.  This shouldn't modify any interesting
11069    // features of the statement.
11070    Expr *producer = cast->getSubExpr();
11071    assert(producer->getType() == cast->getType());
11072    assert(producer->getValueKind() == cast->getValueKind());
11073    cleanups->setSubExpr(producer);
11074    return cleanups;
11075  }
11076  
ActOnStartStmtExpr()11077  void Sema::ActOnStartStmtExpr() {
11078    PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11079  }
11080  
ActOnStmtExprError()11081  void Sema::ActOnStmtExprError() {
11082    // Note that function is also called by TreeTransform when leaving a
11083    // StmtExpr scope without rebuilding anything.
11084  
11085    DiscardCleanupsInEvaluationContext();
11086    PopExpressionEvaluationContext();
11087  }
11088  
11089  ExprResult
ActOnStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)11090  Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11091                      SourceLocation RPLoc) { // "({..})"
11092    assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11093    CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11094  
11095    if (hasAnyUnrecoverableErrorsInThisFunction())
11096      DiscardCleanupsInEvaluationContext();
11097    assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11098    PopExpressionEvaluationContext();
11099  
11100    // FIXME: there are a variety of strange constraints to enforce here, for
11101    // example, it is not possible to goto into a stmt expression apparently.
11102    // More semantic analysis is needed.
11103  
11104    // If there are sub-stmts in the compound stmt, take the type of the last one
11105    // as the type of the stmtexpr.
11106    QualType Ty = Context.VoidTy;
11107    bool StmtExprMayBindToTemp = false;
11108    if (!Compound->body_empty()) {
11109      Stmt *LastStmt = Compound->body_back();
11110      LabelStmt *LastLabelStmt = nullptr;
11111      // If LastStmt is a label, skip down through into the body.
11112      while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11113        LastLabelStmt = Label;
11114        LastStmt = Label->getSubStmt();
11115      }
11116  
11117      if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11118        // Do function/array conversion on the last expression, but not
11119        // lvalue-to-rvalue.  However, initialize an unqualified type.
11120        ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11121        if (LastExpr.isInvalid())
11122          return ExprError();
11123        Ty = LastExpr.get()->getType().getUnqualifiedType();
11124  
11125        if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11126          // In ARC, if the final expression ends in a consume, splice
11127          // the consume out and bind it later.  In the alternate case
11128          // (when dealing with a retainable type), the result
11129          // initialization will create a produce.  In both cases the
11130          // result will be +1, and we'll need to balance that out with
11131          // a bind.
11132          if (Expr *rebuiltLastStmt
11133                = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11134            LastExpr = rebuiltLastStmt;
11135          } else {
11136            LastExpr = PerformCopyInitialization(
11137                              InitializedEntity::InitializeResult(LPLoc,
11138                                                                  Ty,
11139                                                                  false),
11140                                                     SourceLocation(),
11141                                                 LastExpr);
11142          }
11143  
11144          if (LastExpr.isInvalid())
11145            return ExprError();
11146          if (LastExpr.get() != nullptr) {
11147            if (!LastLabelStmt)
11148              Compound->setLastStmt(LastExpr.get());
11149            else
11150              LastLabelStmt->setSubStmt(LastExpr.get());
11151            StmtExprMayBindToTemp = true;
11152          }
11153        }
11154      }
11155    }
11156  
11157    // FIXME: Check that expression type is complete/non-abstract; statement
11158    // expressions are not lvalues.
11159    Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11160    if (StmtExprMayBindToTemp)
11161      return MaybeBindToTemporary(ResStmtExpr);
11162    return ResStmtExpr;
11163  }
11164  
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11165  ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11166                                        TypeSourceInfo *TInfo,
11167                                        ArrayRef<OffsetOfComponent> Components,
11168                                        SourceLocation RParenLoc) {
11169    QualType ArgTy = TInfo->getType();
11170    bool Dependent = ArgTy->isDependentType();
11171    SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11172  
11173    // We must have at least one component that refers to the type, and the first
11174    // one is known to be a field designator.  Verify that the ArgTy represents
11175    // a struct/union/class.
11176    if (!Dependent && !ArgTy->isRecordType())
11177      return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11178                         << ArgTy << TypeRange);
11179  
11180    // Type must be complete per C99 7.17p3 because a declaring a variable
11181    // with an incomplete type would be ill-formed.
11182    if (!Dependent
11183        && RequireCompleteType(BuiltinLoc, ArgTy,
11184                               diag::err_offsetof_incomplete_type, TypeRange))
11185      return ExprError();
11186  
11187    // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11188    // GCC extension, diagnose them.
11189    // FIXME: This diagnostic isn't actually visible because the location is in
11190    // a system header!
11191    if (Components.size() != 1)
11192      Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11193        << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11194  
11195    bool DidWarnAboutNonPOD = false;
11196    QualType CurrentType = ArgTy;
11197    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
11198    SmallVector<OffsetOfNode, 4> Comps;
11199    SmallVector<Expr*, 4> Exprs;
11200    for (const OffsetOfComponent &OC : Components) {
11201      if (OC.isBrackets) {
11202        // Offset of an array sub-field.  TODO: Should we allow vector elements?
11203        if (!CurrentType->isDependentType()) {
11204          const ArrayType *AT = Context.getAsArrayType(CurrentType);
11205          if(!AT)
11206            return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11207                             << CurrentType);
11208          CurrentType = AT->getElementType();
11209        } else
11210          CurrentType = Context.DependentTy;
11211  
11212        ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11213        if (IdxRval.isInvalid())
11214          return ExprError();
11215        Expr *Idx = IdxRval.get();
11216  
11217        // The expression must be an integral expression.
11218        // FIXME: An integral constant expression?
11219        if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11220            !Idx->getType()->isIntegerType())
11221          return ExprError(Diag(Idx->getLocStart(),
11222                                diag::err_typecheck_subscript_not_integer)
11223                           << Idx->getSourceRange());
11224  
11225        // Record this array index.
11226        Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11227        Exprs.push_back(Idx);
11228        continue;
11229      }
11230  
11231      // Offset of a field.
11232      if (CurrentType->isDependentType()) {
11233        // We have the offset of a field, but we can't look into the dependent
11234        // type. Just record the identifier of the field.
11235        Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11236        CurrentType = Context.DependentTy;
11237        continue;
11238      }
11239  
11240      // We need to have a complete type to look into.
11241      if (RequireCompleteType(OC.LocStart, CurrentType,
11242                              diag::err_offsetof_incomplete_type))
11243        return ExprError();
11244  
11245      // Look for the designated field.
11246      const RecordType *RC = CurrentType->getAs<RecordType>();
11247      if (!RC)
11248        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11249                         << CurrentType);
11250      RecordDecl *RD = RC->getDecl();
11251  
11252      // C++ [lib.support.types]p5:
11253      //   The macro offsetof accepts a restricted set of type arguments in this
11254      //   International Standard. type shall be a POD structure or a POD union
11255      //   (clause 9).
11256      // C++11 [support.types]p4:
11257      //   If type is not a standard-layout class (Clause 9), the results are
11258      //   undefined.
11259      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11260        bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11261        unsigned DiagID =
11262          LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11263                              : diag::ext_offsetof_non_pod_type;
11264  
11265        if (!IsSafe && !DidWarnAboutNonPOD &&
11266            DiagRuntimeBehavior(BuiltinLoc, nullptr,
11267                                PDiag(DiagID)
11268                                << SourceRange(Components[0].LocStart, OC.LocEnd)
11269                                << CurrentType))
11270          DidWarnAboutNonPOD = true;
11271      }
11272  
11273      // Look for the field.
11274      LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11275      LookupQualifiedName(R, RD);
11276      FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11277      IndirectFieldDecl *IndirectMemberDecl = nullptr;
11278      if (!MemberDecl) {
11279        if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11280          MemberDecl = IndirectMemberDecl->getAnonField();
11281      }
11282  
11283      if (!MemberDecl)
11284        return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11285                         << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11286                                                                OC.LocEnd));
11287  
11288      // C99 7.17p3:
11289      //   (If the specified member is a bit-field, the behavior is undefined.)
11290      //
11291      // We diagnose this as an error.
11292      if (MemberDecl->isBitField()) {
11293        Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11294          << MemberDecl->getDeclName()
11295          << SourceRange(BuiltinLoc, RParenLoc);
11296        Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11297        return ExprError();
11298      }
11299  
11300      RecordDecl *Parent = MemberDecl->getParent();
11301      if (IndirectMemberDecl)
11302        Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11303  
11304      // If the member was found in a base class, introduce OffsetOfNodes for
11305      // the base class indirections.
11306      CXXBasePaths Paths;
11307      if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11308                        Paths)) {
11309        if (Paths.getDetectedVirtual()) {
11310          Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11311            << MemberDecl->getDeclName()
11312            << SourceRange(BuiltinLoc, RParenLoc);
11313          return ExprError();
11314        }
11315  
11316        CXXBasePath &Path = Paths.front();
11317        for (const CXXBasePathElement &B : Path)
11318          Comps.push_back(OffsetOfNode(B.Base));
11319      }
11320  
11321      if (IndirectMemberDecl) {
11322        for (auto *FI : IndirectMemberDecl->chain()) {
11323          assert(isa<FieldDecl>(FI));
11324          Comps.push_back(OffsetOfNode(OC.LocStart,
11325                                       cast<FieldDecl>(FI), OC.LocEnd));
11326        }
11327      } else
11328        Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11329  
11330      CurrentType = MemberDecl->getType().getNonReferenceType();
11331    }
11332  
11333    return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11334                                Comps, Exprs, RParenLoc);
11335  }
11336  
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)11337  ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11338                                        SourceLocation BuiltinLoc,
11339                                        SourceLocation TypeLoc,
11340                                        ParsedType ParsedArgTy,
11341                                        ArrayRef<OffsetOfComponent> Components,
11342                                        SourceLocation RParenLoc) {
11343  
11344    TypeSourceInfo *ArgTInfo;
11345    QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11346    if (ArgTy.isNull())
11347      return ExprError();
11348  
11349    if (!ArgTInfo)
11350      ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11351  
11352    return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11353  }
11354  
11355  
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)11356  ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11357                                   Expr *CondExpr,
11358                                   Expr *LHSExpr, Expr *RHSExpr,
11359                                   SourceLocation RPLoc) {
11360    assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11361  
11362    ExprValueKind VK = VK_RValue;
11363    ExprObjectKind OK = OK_Ordinary;
11364    QualType resType;
11365    bool ValueDependent = false;
11366    bool CondIsTrue = false;
11367    if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11368      resType = Context.DependentTy;
11369      ValueDependent = true;
11370    } else {
11371      // The conditional expression is required to be a constant expression.
11372      llvm::APSInt condEval(32);
11373      ExprResult CondICE
11374        = VerifyIntegerConstantExpression(CondExpr, &condEval,
11375            diag::err_typecheck_choose_expr_requires_constant, false);
11376      if (CondICE.isInvalid())
11377        return ExprError();
11378      CondExpr = CondICE.get();
11379      CondIsTrue = condEval.getZExtValue();
11380  
11381      // If the condition is > zero, then the AST type is the same as the LSHExpr.
11382      Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11383  
11384      resType = ActiveExpr->getType();
11385      ValueDependent = ActiveExpr->isValueDependent();
11386      VK = ActiveExpr->getValueKind();
11387      OK = ActiveExpr->getObjectKind();
11388    }
11389  
11390    return new (Context)
11391        ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11392                   CondIsTrue, resType->isDependentType(), ValueDependent);
11393  }
11394  
11395  //===----------------------------------------------------------------------===//
11396  // Clang Extensions.
11397  //===----------------------------------------------------------------------===//
11398  
11399  /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)11400  void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11401    BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11402  
11403    if (LangOpts.CPlusPlus) {
11404      Decl *ManglingContextDecl;
11405      if (MangleNumberingContext *MCtx =
11406              getCurrentMangleNumberContext(Block->getDeclContext(),
11407                                            ManglingContextDecl)) {
11408        unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11409        Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11410      }
11411    }
11412  
11413    PushBlockScope(CurScope, Block);
11414    CurContext->addDecl(Block);
11415    if (CurScope)
11416      PushDeclContext(CurScope, Block);
11417    else
11418      CurContext = Block;
11419  
11420    getCurBlock()->HasImplicitReturnType = true;
11421  
11422    // Enter a new evaluation context to insulate the block from any
11423    // cleanups from the enclosing full-expression.
11424    PushExpressionEvaluationContext(PotentiallyEvaluated);
11425  }
11426  
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)11427  void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11428                                 Scope *CurScope) {
11429    assert(ParamInfo.getIdentifier() == nullptr &&
11430           "block-id should have no identifier!");
11431    assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11432    BlockScopeInfo *CurBlock = getCurBlock();
11433  
11434    TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11435    QualType T = Sig->getType();
11436  
11437    // FIXME: We should allow unexpanded parameter packs here, but that would,
11438    // in turn, make the block expression contain unexpanded parameter packs.
11439    if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11440      // Drop the parameters.
11441      FunctionProtoType::ExtProtoInfo EPI;
11442      EPI.HasTrailingReturn = false;
11443      EPI.TypeQuals |= DeclSpec::TQ_const;
11444      T = Context.getFunctionType(Context.DependentTy, None, EPI);
11445      Sig = Context.getTrivialTypeSourceInfo(T);
11446    }
11447  
11448    // GetTypeForDeclarator always produces a function type for a block
11449    // literal signature.  Furthermore, it is always a FunctionProtoType
11450    // unless the function was written with a typedef.
11451    assert(T->isFunctionType() &&
11452           "GetTypeForDeclarator made a non-function block signature");
11453  
11454    // Look for an explicit signature in that function type.
11455    FunctionProtoTypeLoc ExplicitSignature;
11456  
11457    TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11458    if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11459  
11460      // Check whether that explicit signature was synthesized by
11461      // GetTypeForDeclarator.  If so, don't save that as part of the
11462      // written signature.
11463      if (ExplicitSignature.getLocalRangeBegin() ==
11464          ExplicitSignature.getLocalRangeEnd()) {
11465        // This would be much cheaper if we stored TypeLocs instead of
11466        // TypeSourceInfos.
11467        TypeLoc Result = ExplicitSignature.getReturnLoc();
11468        unsigned Size = Result.getFullDataSize();
11469        Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11470        Sig->getTypeLoc().initializeFullCopy(Result, Size);
11471  
11472        ExplicitSignature = FunctionProtoTypeLoc();
11473      }
11474    }
11475  
11476    CurBlock->TheDecl->setSignatureAsWritten(Sig);
11477    CurBlock->FunctionType = T;
11478  
11479    const FunctionType *Fn = T->getAs<FunctionType>();
11480    QualType RetTy = Fn->getReturnType();
11481    bool isVariadic =
11482      (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11483  
11484    CurBlock->TheDecl->setIsVariadic(isVariadic);
11485  
11486    // Context.DependentTy is used as a placeholder for a missing block
11487    // return type.  TODO:  what should we do with declarators like:
11488    //   ^ * { ... }
11489    // If the answer is "apply template argument deduction"....
11490    if (RetTy != Context.DependentTy) {
11491      CurBlock->ReturnType = RetTy;
11492      CurBlock->TheDecl->setBlockMissingReturnType(false);
11493      CurBlock->HasImplicitReturnType = false;
11494    }
11495  
11496    // Push block parameters from the declarator if we had them.
11497    SmallVector<ParmVarDecl*, 8> Params;
11498    if (ExplicitSignature) {
11499      for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11500        ParmVarDecl *Param = ExplicitSignature.getParam(I);
11501        if (Param->getIdentifier() == nullptr &&
11502            !Param->isImplicit() &&
11503            !Param->isInvalidDecl() &&
11504            !getLangOpts().CPlusPlus)
11505          Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11506        Params.push_back(Param);
11507      }
11508  
11509    // Fake up parameter variables if we have a typedef, like
11510    //   ^ fntype { ... }
11511    } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11512      for (const auto &I : Fn->param_types()) {
11513        ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11514            CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11515        Params.push_back(Param);
11516      }
11517    }
11518  
11519    // Set the parameters on the block decl.
11520    if (!Params.empty()) {
11521      CurBlock->TheDecl->setParams(Params);
11522      CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11523                               CurBlock->TheDecl->param_end(),
11524                               /*CheckParameterNames=*/false);
11525    }
11526  
11527    // Finally we can process decl attributes.
11528    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11529  
11530    // Put the parameter variables in scope.
11531    for (auto AI : CurBlock->TheDecl->params()) {
11532      AI->setOwningFunction(CurBlock->TheDecl);
11533  
11534      // If this has an identifier, add it to the scope stack.
11535      if (AI->getIdentifier()) {
11536        CheckShadow(CurBlock->TheScope, AI);
11537  
11538        PushOnScopeChains(AI, CurBlock->TheScope);
11539      }
11540    }
11541  }
11542  
11543  /// ActOnBlockError - If there is an error parsing a block, this callback
11544  /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)11545  void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11546    // Leave the expression-evaluation context.
11547    DiscardCleanupsInEvaluationContext();
11548    PopExpressionEvaluationContext();
11549  
11550    // Pop off CurBlock, handle nested blocks.
11551    PopDeclContext();
11552    PopFunctionScopeInfo();
11553  }
11554  
11555  /// ActOnBlockStmtExpr - This is called when the body of a block statement
11556  /// literal was successfully completed.  ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)11557  ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11558                                      Stmt *Body, Scope *CurScope) {
11559    // If blocks are disabled, emit an error.
11560    if (!LangOpts.Blocks)
11561      Diag(CaretLoc, diag::err_blocks_disable);
11562  
11563    // Leave the expression-evaluation context.
11564    if (hasAnyUnrecoverableErrorsInThisFunction())
11565      DiscardCleanupsInEvaluationContext();
11566    assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11567    PopExpressionEvaluationContext();
11568  
11569    BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11570  
11571    if (BSI->HasImplicitReturnType)
11572      deduceClosureReturnType(*BSI);
11573  
11574    PopDeclContext();
11575  
11576    QualType RetTy = Context.VoidTy;
11577    if (!BSI->ReturnType.isNull())
11578      RetTy = BSI->ReturnType;
11579  
11580    bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11581    QualType BlockTy;
11582  
11583    // Set the captured variables on the block.
11584    // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11585    SmallVector<BlockDecl::Capture, 4> Captures;
11586    for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
11587      if (Cap.isThisCapture())
11588        continue;
11589      BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11590                                Cap.isNested(), Cap.getInitExpr());
11591      Captures.push_back(NewCap);
11592    }
11593    BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
11594  
11595    // If the user wrote a function type in some form, try to use that.
11596    if (!BSI->FunctionType.isNull()) {
11597      const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11598  
11599      FunctionType::ExtInfo Ext = FTy->getExtInfo();
11600      if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11601  
11602      // Turn protoless block types into nullary block types.
11603      if (isa<FunctionNoProtoType>(FTy)) {
11604        FunctionProtoType::ExtProtoInfo EPI;
11605        EPI.ExtInfo = Ext;
11606        BlockTy = Context.getFunctionType(RetTy, None, EPI);
11607  
11608      // Otherwise, if we don't need to change anything about the function type,
11609      // preserve its sugar structure.
11610      } else if (FTy->getReturnType() == RetTy &&
11611                 (!NoReturn || FTy->getNoReturnAttr())) {
11612        BlockTy = BSI->FunctionType;
11613  
11614      // Otherwise, make the minimal modifications to the function type.
11615      } else {
11616        const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11617        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11618        EPI.TypeQuals = 0; // FIXME: silently?
11619        EPI.ExtInfo = Ext;
11620        BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11621      }
11622  
11623    // If we don't have a function type, just build one from nothing.
11624    } else {
11625      FunctionProtoType::ExtProtoInfo EPI;
11626      EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11627      BlockTy = Context.getFunctionType(RetTy, None, EPI);
11628    }
11629  
11630    DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11631                             BSI->TheDecl->param_end());
11632    BlockTy = Context.getBlockPointerType(BlockTy);
11633  
11634    // If needed, diagnose invalid gotos and switches in the block.
11635    if (getCurFunction()->NeedsScopeChecking() &&
11636        !PP.isCodeCompletionEnabled())
11637      DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11638  
11639    BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11640  
11641    // Try to apply the named return value optimization. We have to check again
11642    // if we can do this, though, because blocks keep return statements around
11643    // to deduce an implicit return type.
11644    if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11645        !BSI->TheDecl->isDependentContext())
11646      computeNRVO(Body, BSI);
11647  
11648    BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11649    AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11650    PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11651  
11652    // If the block isn't obviously global, i.e. it captures anything at
11653    // all, then we need to do a few things in the surrounding context:
11654    if (Result->getBlockDecl()->hasCaptures()) {
11655      // First, this expression has a new cleanup object.
11656      ExprCleanupObjects.push_back(Result->getBlockDecl());
11657      ExprNeedsCleanups = true;
11658  
11659      // It also gets a branch-protected scope if any of the captured
11660      // variables needs destruction.
11661      for (const auto &CI : Result->getBlockDecl()->captures()) {
11662        const VarDecl *var = CI.getVariable();
11663        if (var->getType().isDestructedType() != QualType::DK_none) {
11664          getCurFunction()->setHasBranchProtectedScope();
11665          break;
11666        }
11667      }
11668    }
11669  
11670    return Result;
11671  }
11672  
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)11673  ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11674                                          Expr *E, ParsedType Ty,
11675                                          SourceLocation RPLoc) {
11676    TypeSourceInfo *TInfo;
11677    GetTypeFromParser(Ty, &TInfo);
11678    return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11679  }
11680  
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)11681  ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11682                                  Expr *E, TypeSourceInfo *TInfo,
11683                                  SourceLocation RPLoc) {
11684    Expr *OrigExpr = E;
11685    bool IsMS = false;
11686  
11687    // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
11688    // as Microsoft ABI on an actual Microsoft platform, where
11689    // __builtin_ms_va_list and __builtin_va_list are the same.)
11690    if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
11691        Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
11692      QualType MSVaListType = Context.getBuiltinMSVaListType();
11693      if (Context.hasSameType(MSVaListType, E->getType())) {
11694        if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
11695          return ExprError();
11696        IsMS = true;
11697      }
11698    }
11699  
11700    // Get the va_list type
11701    QualType VaListType = Context.getBuiltinVaListType();
11702    if (!IsMS) {
11703      if (VaListType->isArrayType()) {
11704        // Deal with implicit array decay; for example, on x86-64,
11705        // va_list is an array, but it's supposed to decay to
11706        // a pointer for va_arg.
11707        VaListType = Context.getArrayDecayedType(VaListType);
11708        // Make sure the input expression also decays appropriately.
11709        ExprResult Result = UsualUnaryConversions(E);
11710        if (Result.isInvalid())
11711          return ExprError();
11712        E = Result.get();
11713      } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11714        // If va_list is a record type and we are compiling in C++ mode,
11715        // check the argument using reference binding.
11716        InitializedEntity Entity = InitializedEntity::InitializeParameter(
11717            Context, Context.getLValueReferenceType(VaListType), false);
11718        ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11719        if (Init.isInvalid())
11720          return ExprError();
11721        E = Init.getAs<Expr>();
11722      } else {
11723        // Otherwise, the va_list argument must be an l-value because
11724        // it is modified by va_arg.
11725        if (!E->isTypeDependent() &&
11726            CheckForModifiableLvalue(E, BuiltinLoc, *this))
11727          return ExprError();
11728      }
11729    }
11730  
11731    if (!IsMS && !E->isTypeDependent() &&
11732        !Context.hasSameType(VaListType, E->getType()))
11733      return ExprError(Diag(E->getLocStart(),
11734                           diag::err_first_argument_to_va_arg_not_of_type_va_list)
11735        << OrigExpr->getType() << E->getSourceRange());
11736  
11737    if (!TInfo->getType()->isDependentType()) {
11738      if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11739                              diag::err_second_parameter_to_va_arg_incomplete,
11740                              TInfo->getTypeLoc()))
11741        return ExprError();
11742  
11743      if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11744                                 TInfo->getType(),
11745                                 diag::err_second_parameter_to_va_arg_abstract,
11746                                 TInfo->getTypeLoc()))
11747        return ExprError();
11748  
11749      if (!TInfo->getType().isPODType(Context)) {
11750        Diag(TInfo->getTypeLoc().getBeginLoc(),
11751             TInfo->getType()->isObjCLifetimeType()
11752               ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11753               : diag::warn_second_parameter_to_va_arg_not_pod)
11754          << TInfo->getType()
11755          << TInfo->getTypeLoc().getSourceRange();
11756      }
11757  
11758      // Check for va_arg where arguments of the given type will be promoted
11759      // (i.e. this va_arg is guaranteed to have undefined behavior).
11760      QualType PromoteType;
11761      if (TInfo->getType()->isPromotableIntegerType()) {
11762        PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11763        if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11764          PromoteType = QualType();
11765      }
11766      if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11767        PromoteType = Context.DoubleTy;
11768      if (!PromoteType.isNull())
11769        DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11770                    PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11771                            << TInfo->getType()
11772                            << PromoteType
11773                            << TInfo->getTypeLoc().getSourceRange());
11774    }
11775  
11776    QualType T = TInfo->getType().getNonLValueExprType(Context);
11777    return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
11778  }
11779  
ActOnGNUNullExpr(SourceLocation TokenLoc)11780  ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11781    // The type of __null will be int or long, depending on the size of
11782    // pointers on the target.
11783    QualType Ty;
11784    unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11785    if (pw == Context.getTargetInfo().getIntWidth())
11786      Ty = Context.IntTy;
11787    else if (pw == Context.getTargetInfo().getLongWidth())
11788      Ty = Context.LongTy;
11789    else if (pw == Context.getTargetInfo().getLongLongWidth())
11790      Ty = Context.LongLongTy;
11791    else {
11792      llvm_unreachable("I don't know size of pointer!");
11793    }
11794  
11795    return new (Context) GNUNullExpr(Ty, TokenLoc);
11796  }
11797  
11798  bool
ConversionToObjCStringLiteralCheck(QualType DstType,Expr * & Exp)11799  Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11800    if (!getLangOpts().ObjC1)
11801      return false;
11802  
11803    const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11804    if (!PT)
11805      return false;
11806  
11807    if (!PT->isObjCIdType()) {
11808      // Check if the destination is the 'NSString' interface.
11809      const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11810      if (!ID || !ID->getIdentifier()->isStr("NSString"))
11811        return false;
11812    }
11813  
11814    // Ignore any parens, implicit casts (should only be
11815    // array-to-pointer decays), and not-so-opaque values.  The last is
11816    // important for making this trigger for property assignments.
11817    Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11818    if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11819      if (OV->getSourceExpr())
11820        SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11821  
11822    StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
11823    if (!SL || !SL->isAscii())
11824      return false;
11825    Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11826      << FixItHint::CreateInsertion(SL->getLocStart(), "@");
11827    Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
11828    return true;
11829  }
11830  
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)11831  static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
11832                                                const Expr *SrcExpr) {
11833    if (!DstType->isFunctionPointerType() ||
11834        !SrcExpr->getType()->isFunctionType())
11835      return false;
11836  
11837    auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
11838    if (!DRE)
11839      return false;
11840  
11841    auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11842    if (!FD)
11843      return false;
11844  
11845    return !S.checkAddressOfFunctionIsAvailable(FD,
11846                                                /*Complain=*/true,
11847                                                SrcExpr->getLocStart());
11848  }
11849  
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)11850  bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11851                                      SourceLocation Loc,
11852                                      QualType DstType, QualType SrcType,
11853                                      Expr *SrcExpr, AssignmentAction Action,
11854                                      bool *Complained) {
11855    if (Complained)
11856      *Complained = false;
11857  
11858    // Decode the result (notice that AST's are still created for extensions).
11859    bool CheckInferredResultType = false;
11860    bool isInvalid = false;
11861    unsigned DiagKind = 0;
11862    FixItHint Hint;
11863    ConversionFixItGenerator ConvHints;
11864    bool MayHaveConvFixit = false;
11865    bool MayHaveFunctionDiff = false;
11866    const ObjCInterfaceDecl *IFace = nullptr;
11867    const ObjCProtocolDecl *PDecl = nullptr;
11868  
11869    switch (ConvTy) {
11870    case Compatible:
11871        DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11872        return false;
11873  
11874    case PointerToInt:
11875      DiagKind = diag::ext_typecheck_convert_pointer_int;
11876      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11877      MayHaveConvFixit = true;
11878      break;
11879    case IntToPointer:
11880      DiagKind = diag::ext_typecheck_convert_int_pointer;
11881      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11882      MayHaveConvFixit = true;
11883      break;
11884    case IncompatiblePointer:
11885        DiagKind =
11886          (Action == AA_Passing_CFAudited ?
11887            diag::err_arc_typecheck_convert_incompatible_pointer :
11888            diag::ext_typecheck_convert_incompatible_pointer);
11889      CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11890        SrcType->isObjCObjectPointerType();
11891      if (Hint.isNull() && !CheckInferredResultType) {
11892        ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11893      }
11894      else if (CheckInferredResultType) {
11895        SrcType = SrcType.getUnqualifiedType();
11896        DstType = DstType.getUnqualifiedType();
11897      }
11898      MayHaveConvFixit = true;
11899      break;
11900    case IncompatiblePointerSign:
11901      DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11902      break;
11903    case FunctionVoidPointer:
11904      DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11905      break;
11906    case IncompatiblePointerDiscardsQualifiers: {
11907      // Perform array-to-pointer decay if necessary.
11908      if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11909  
11910      Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11911      Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11912      if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11913        DiagKind = diag::err_typecheck_incompatible_address_space;
11914        break;
11915  
11916  
11917      } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11918        DiagKind = diag::err_typecheck_incompatible_ownership;
11919        break;
11920      }
11921  
11922      llvm_unreachable("unknown error case for discarding qualifiers!");
11923      // fallthrough
11924    }
11925    case CompatiblePointerDiscardsQualifiers:
11926      // If the qualifiers lost were because we were applying the
11927      // (deprecated) C++ conversion from a string literal to a char*
11928      // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11929      // Ideally, this check would be performed in
11930      // checkPointerTypesForAssignment. However, that would require a
11931      // bit of refactoring (so that the second argument is an
11932      // expression, rather than a type), which should be done as part
11933      // of a larger effort to fix checkPointerTypesForAssignment for
11934      // C++ semantics.
11935      if (getLangOpts().CPlusPlus &&
11936          IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11937        return false;
11938      DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11939      break;
11940    case IncompatibleNestedPointerQualifiers:
11941      DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11942      break;
11943    case IntToBlockPointer:
11944      DiagKind = diag::err_int_to_block_pointer;
11945      break;
11946    case IncompatibleBlockPointer:
11947      DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11948      break;
11949    case IncompatibleObjCQualifiedId: {
11950      if (SrcType->isObjCQualifiedIdType()) {
11951        const ObjCObjectPointerType *srcOPT =
11952                  SrcType->getAs<ObjCObjectPointerType>();
11953        for (auto *srcProto : srcOPT->quals()) {
11954          PDecl = srcProto;
11955          break;
11956        }
11957        if (const ObjCInterfaceType *IFaceT =
11958              DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11959          IFace = IFaceT->getDecl();
11960      }
11961      else if (DstType->isObjCQualifiedIdType()) {
11962        const ObjCObjectPointerType *dstOPT =
11963          DstType->getAs<ObjCObjectPointerType>();
11964        for (auto *dstProto : dstOPT->quals()) {
11965          PDecl = dstProto;
11966          break;
11967        }
11968        if (const ObjCInterfaceType *IFaceT =
11969              SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11970          IFace = IFaceT->getDecl();
11971      }
11972      DiagKind = diag::warn_incompatible_qualified_id;
11973      break;
11974    }
11975    case IncompatibleVectors:
11976      DiagKind = diag::warn_incompatible_vectors;
11977      break;
11978    case IncompatibleObjCWeakRef:
11979      DiagKind = diag::err_arc_weak_unavailable_assign;
11980      break;
11981    case Incompatible:
11982      if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
11983        if (Complained)
11984          *Complained = true;
11985        return true;
11986      }
11987  
11988      DiagKind = diag::err_typecheck_convert_incompatible;
11989      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11990      MayHaveConvFixit = true;
11991      isInvalid = true;
11992      MayHaveFunctionDiff = true;
11993      break;
11994    }
11995  
11996    QualType FirstType, SecondType;
11997    switch (Action) {
11998    case AA_Assigning:
11999    case AA_Initializing:
12000      // The destination type comes first.
12001      FirstType = DstType;
12002      SecondType = SrcType;
12003      break;
12004  
12005    case AA_Returning:
12006    case AA_Passing:
12007    case AA_Passing_CFAudited:
12008    case AA_Converting:
12009    case AA_Sending:
12010    case AA_Casting:
12011      // The source type comes first.
12012      FirstType = SrcType;
12013      SecondType = DstType;
12014      break;
12015    }
12016  
12017    PartialDiagnostic FDiag = PDiag(DiagKind);
12018    if (Action == AA_Passing_CFAudited)
12019      FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12020    else
12021      FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12022  
12023    // If we can fix the conversion, suggest the FixIts.
12024    assert(ConvHints.isNull() || Hint.isNull());
12025    if (!ConvHints.isNull()) {
12026      for (FixItHint &H : ConvHints.Hints)
12027        FDiag << H;
12028    } else {
12029      FDiag << Hint;
12030    }
12031    if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12032  
12033    if (MayHaveFunctionDiff)
12034      HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12035  
12036    Diag(Loc, FDiag);
12037    if (DiagKind == diag::warn_incompatible_qualified_id &&
12038        PDecl && IFace && !IFace->hasDefinition())
12039        Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12040          << IFace->getName() << PDecl->getName();
12041  
12042    if (SecondType == Context.OverloadTy)
12043      NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12044                                FirstType, /*TakingAddress=*/true);
12045  
12046    if (CheckInferredResultType)
12047      EmitRelatedResultTypeNote(SrcExpr);
12048  
12049    if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12050      EmitRelatedResultTypeNoteForReturn(DstType);
12051  
12052    if (Complained)
12053      *Complained = true;
12054    return isInvalid;
12055  }
12056  
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result)12057  ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12058                                                   llvm::APSInt *Result) {
12059    class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12060    public:
12061      void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12062        S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12063      }
12064    } Diagnoser;
12065  
12066    return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12067  }
12068  
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,bool AllowFold)12069  ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12070                                                   llvm::APSInt *Result,
12071                                                   unsigned DiagID,
12072                                                   bool AllowFold) {
12073    class IDDiagnoser : public VerifyICEDiagnoser {
12074      unsigned DiagID;
12075  
12076    public:
12077      IDDiagnoser(unsigned DiagID)
12078        : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12079  
12080      void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12081        S.Diag(Loc, DiagID) << SR;
12082      }
12083    } Diagnoser(DiagID);
12084  
12085    return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12086  }
12087  
diagnoseFold(Sema & S,SourceLocation Loc,SourceRange SR)12088  void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12089                                              SourceRange SR) {
12090    S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12091  }
12092  
12093  ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,bool AllowFold)12094  Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12095                                        VerifyICEDiagnoser &Diagnoser,
12096                                        bool AllowFold) {
12097    SourceLocation DiagLoc = E->getLocStart();
12098  
12099    if (getLangOpts().CPlusPlus11) {
12100      // C++11 [expr.const]p5:
12101      //   If an expression of literal class type is used in a context where an
12102      //   integral constant expression is required, then that class type shall
12103      //   have a single non-explicit conversion function to an integral or
12104      //   unscoped enumeration type
12105      ExprResult Converted;
12106      class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12107      public:
12108        CXX11ConvertDiagnoser(bool Silent)
12109            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12110                                  Silent, true) {}
12111  
12112        SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12113                                             QualType T) override {
12114          return S.Diag(Loc, diag::err_ice_not_integral) << T;
12115        }
12116  
12117        SemaDiagnosticBuilder diagnoseIncomplete(
12118            Sema &S, SourceLocation Loc, QualType T) override {
12119          return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12120        }
12121  
12122        SemaDiagnosticBuilder diagnoseExplicitConv(
12123            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12124          return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12125        }
12126  
12127        SemaDiagnosticBuilder noteExplicitConv(
12128            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12129          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12130                   << ConvTy->isEnumeralType() << ConvTy;
12131        }
12132  
12133        SemaDiagnosticBuilder diagnoseAmbiguous(
12134            Sema &S, SourceLocation Loc, QualType T) override {
12135          return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12136        }
12137  
12138        SemaDiagnosticBuilder noteAmbiguous(
12139            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12140          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12141                   << ConvTy->isEnumeralType() << ConvTy;
12142        }
12143  
12144        SemaDiagnosticBuilder diagnoseConversion(
12145            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12146          llvm_unreachable("conversion functions are permitted");
12147        }
12148      } ConvertDiagnoser(Diagnoser.Suppress);
12149  
12150      Converted = PerformContextualImplicitConversion(DiagLoc, E,
12151                                                      ConvertDiagnoser);
12152      if (Converted.isInvalid())
12153        return Converted;
12154      E = Converted.get();
12155      if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12156        return ExprError();
12157    } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12158      // An ICE must be of integral or unscoped enumeration type.
12159      if (!Diagnoser.Suppress)
12160        Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12161      return ExprError();
12162    }
12163  
12164    // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12165    // in the non-ICE case.
12166    if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12167      if (Result)
12168        *Result = E->EvaluateKnownConstInt(Context);
12169      return E;
12170    }
12171  
12172    Expr::EvalResult EvalResult;
12173    SmallVector<PartialDiagnosticAt, 8> Notes;
12174    EvalResult.Diag = &Notes;
12175  
12176    // Try to evaluate the expression, and produce diagnostics explaining why it's
12177    // not a constant expression as a side-effect.
12178    bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12179                  EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12180  
12181    // In C++11, we can rely on diagnostics being produced for any expression
12182    // which is not a constant expression. If no diagnostics were produced, then
12183    // this is a constant expression.
12184    if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12185      if (Result)
12186        *Result = EvalResult.Val.getInt();
12187      return E;
12188    }
12189  
12190    // If our only note is the usual "invalid subexpression" note, just point
12191    // the caret at its location rather than producing an essentially
12192    // redundant note.
12193    if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12194          diag::note_invalid_subexpr_in_const_expr) {
12195      DiagLoc = Notes[0].first;
12196      Notes.clear();
12197    }
12198  
12199    if (!Folded || !AllowFold) {
12200      if (!Diagnoser.Suppress) {
12201        Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12202        for (const PartialDiagnosticAt &Note : Notes)
12203          Diag(Note.first, Note.second);
12204      }
12205  
12206      return ExprError();
12207    }
12208  
12209    Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12210    for (const PartialDiagnosticAt &Note : Notes)
12211      Diag(Note.first, Note.second);
12212  
12213    if (Result)
12214      *Result = EvalResult.Val.getInt();
12215    return E;
12216  }
12217  
12218  namespace {
12219    // Handle the case where we conclude a expression which we speculatively
12220    // considered to be unevaluated is actually evaluated.
12221    class TransformToPE : public TreeTransform<TransformToPE> {
12222      typedef TreeTransform<TransformToPE> BaseTransform;
12223  
12224    public:
TransformToPE(Sema & SemaRef)12225      TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12226  
12227      // Make sure we redo semantic analysis
AlwaysRebuild()12228      bool AlwaysRebuild() { return true; }
12229  
12230      // Make sure we handle LabelStmts correctly.
12231      // FIXME: This does the right thing, but maybe we need a more general
12232      // fix to TreeTransform?
TransformLabelStmt(LabelStmt * S)12233      StmtResult TransformLabelStmt(LabelStmt *S) {
12234        S->getDecl()->setStmt(nullptr);
12235        return BaseTransform::TransformLabelStmt(S);
12236      }
12237  
12238      // We need to special-case DeclRefExprs referring to FieldDecls which
12239      // are not part of a member pointer formation; normal TreeTransforming
12240      // doesn't catch this case because of the way we represent them in the AST.
12241      // FIXME: This is a bit ugly; is it really the best way to handle this
12242      // case?
12243      //
12244      // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)12245      ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12246        if (isa<FieldDecl>(E->getDecl()) &&
12247            !SemaRef.isUnevaluatedContext())
12248          return SemaRef.Diag(E->getLocation(),
12249                              diag::err_invalid_non_static_member_use)
12250              << E->getDecl() << E->getSourceRange();
12251  
12252        return BaseTransform::TransformDeclRefExpr(E);
12253      }
12254  
12255      // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)12256      ExprResult TransformUnaryOperator(UnaryOperator *E) {
12257        if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12258          return E;
12259  
12260        return BaseTransform::TransformUnaryOperator(E);
12261      }
12262  
TransformLambdaExpr(LambdaExpr * E)12263      ExprResult TransformLambdaExpr(LambdaExpr *E) {
12264        // Lambdas never need to be transformed.
12265        return E;
12266      }
12267    };
12268  }
12269  
TransformToPotentiallyEvaluated(Expr * E)12270  ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12271    assert(isUnevaluatedContext() &&
12272           "Should only transform unevaluated expressions");
12273    ExprEvalContexts.back().Context =
12274        ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12275    if (isUnevaluatedContext())
12276      return E;
12277    return TransformToPE(*this).TransformExpr(E);
12278  }
12279  
12280  void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,bool IsDecltype)12281  Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12282                                        Decl *LambdaContextDecl,
12283                                        bool IsDecltype) {
12284    ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12285                                  ExprNeedsCleanups, LambdaContextDecl,
12286                                  IsDecltype);
12287    ExprNeedsCleanups = false;
12288    if (!MaybeODRUseExprs.empty())
12289      std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12290  }
12291  
12292  void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,bool IsDecltype)12293  Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12294                                        ReuseLambdaContextDecl_t,
12295                                        bool IsDecltype) {
12296    Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12297    PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12298  }
12299  
PopExpressionEvaluationContext()12300  void Sema::PopExpressionEvaluationContext() {
12301    ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12302    unsigned NumTypos = Rec.NumTypos;
12303  
12304    if (!Rec.Lambdas.empty()) {
12305      if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12306        unsigned D;
12307        if (Rec.isUnevaluated()) {
12308          // C++11 [expr.prim.lambda]p2:
12309          //   A lambda-expression shall not appear in an unevaluated operand
12310          //   (Clause 5).
12311          D = diag::err_lambda_unevaluated_operand;
12312        } else {
12313          // C++1y [expr.const]p2:
12314          //   A conditional-expression e is a core constant expression unless the
12315          //   evaluation of e, following the rules of the abstract machine, would
12316          //   evaluate [...] a lambda-expression.
12317          D = diag::err_lambda_in_constant_expression;
12318        }
12319        for (const auto *L : Rec.Lambdas)
12320          Diag(L->getLocStart(), D);
12321      } else {
12322        // Mark the capture expressions odr-used. This was deferred
12323        // during lambda expression creation.
12324        for (auto *Lambda : Rec.Lambdas) {
12325          for (auto *C : Lambda->capture_inits())
12326            MarkDeclarationsReferencedInExpr(C);
12327        }
12328      }
12329    }
12330  
12331    // When are coming out of an unevaluated context, clear out any
12332    // temporaries that we may have created as part of the evaluation of
12333    // the expression in that context: they aren't relevant because they
12334    // will never be constructed.
12335    if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12336      ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12337                               ExprCleanupObjects.end());
12338      ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12339      CleanupVarDeclMarking();
12340      std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12341    // Otherwise, merge the contexts together.
12342    } else {
12343      ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12344      MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12345                              Rec.SavedMaybeODRUseExprs.end());
12346    }
12347  
12348    // Pop the current expression evaluation context off the stack.
12349    ExprEvalContexts.pop_back();
12350  
12351    if (!ExprEvalContexts.empty())
12352      ExprEvalContexts.back().NumTypos += NumTypos;
12353    else
12354      assert(NumTypos == 0 && "There are outstanding typos after popping the "
12355                              "last ExpressionEvaluationContextRecord");
12356  }
12357  
DiscardCleanupsInEvaluationContext()12358  void Sema::DiscardCleanupsInEvaluationContext() {
12359    ExprCleanupObjects.erase(
12360           ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12361           ExprCleanupObjects.end());
12362    ExprNeedsCleanups = false;
12363    MaybeODRUseExprs.clear();
12364  }
12365  
HandleExprEvaluationContextForTypeof(Expr * E)12366  ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12367    if (!E->getType()->isVariablyModifiedType())
12368      return E;
12369    return TransformToPotentiallyEvaluated(E);
12370  }
12371  
IsPotentiallyEvaluatedContext(Sema & SemaRef)12372  static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12373    // Do not mark anything as "used" within a dependent context; wait for
12374    // an instantiation.
12375    if (SemaRef.CurContext->isDependentContext())
12376      return false;
12377  
12378    switch (SemaRef.ExprEvalContexts.back().Context) {
12379      case Sema::Unevaluated:
12380      case Sema::UnevaluatedAbstract:
12381        // We are in an expression that is not potentially evaluated; do nothing.
12382        // (Depending on how you read the standard, we actually do need to do
12383        // something here for null pointer constants, but the standard's
12384        // definition of a null pointer constant is completely crazy.)
12385        return false;
12386  
12387      case Sema::ConstantEvaluated:
12388      case Sema::PotentiallyEvaluated:
12389        // We are in a potentially evaluated expression (or a constant-expression
12390        // in C++03); we need to do implicit template instantiation, implicitly
12391        // define class members, and mark most declarations as used.
12392        return true;
12393  
12394      case Sema::PotentiallyEvaluatedIfUsed:
12395        // Referenced declarations will only be used if the construct in the
12396        // containing expression is used.
12397        return false;
12398    }
12399    llvm_unreachable("Invalid context");
12400  }
12401  
12402  /// \brief Mark a function referenced, and check whether it is odr-used
12403  /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool OdrUse)12404  void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12405                                    bool OdrUse) {
12406    assert(Func && "No function?");
12407  
12408    Func->setReferenced();
12409  
12410    // C++11 [basic.def.odr]p3:
12411    //   A function whose name appears as a potentially-evaluated expression is
12412    //   odr-used if it is the unique lookup result or the selected member of a
12413    //   set of overloaded functions [...].
12414    //
12415    // We (incorrectly) mark overload resolution as an unevaluated context, so we
12416    // can just check that here. Skip the rest of this function if we've already
12417    // marked the function as used.
12418    if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12419        !IsPotentiallyEvaluatedContext(*this)) {
12420      // C++11 [temp.inst]p3:
12421      //   Unless a function template specialization has been explicitly
12422      //   instantiated or explicitly specialized, the function template
12423      //   specialization is implicitly instantiated when the specialization is
12424      //   referenced in a context that requires a function definition to exist.
12425      //
12426      // We consider constexpr function templates to be referenced in a context
12427      // that requires a definition to exist whenever they are referenced.
12428      //
12429      // FIXME: This instantiates constexpr functions too frequently. If this is
12430      // really an unevaluated context (and we're not just in the definition of a
12431      // function template or overload resolution or other cases which we
12432      // incorrectly consider to be unevaluated contexts), and we're not in a
12433      // subexpression which we actually need to evaluate (for instance, a
12434      // template argument, array bound or an expression in a braced-init-list),
12435      // we are not permitted to instantiate this constexpr function definition.
12436      //
12437      // FIXME: This also implicitly defines special members too frequently. They
12438      // are only supposed to be implicitly defined if they are odr-used, but they
12439      // are not odr-used from constant expressions in unevaluated contexts.
12440      // However, they cannot be referenced if they are deleted, and they are
12441      // deleted whenever the implicit definition of the special member would
12442      // fail.
12443      if (!Func->isConstexpr() || Func->getBody())
12444        return;
12445      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12446      if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12447        return;
12448    }
12449  
12450    // Note that this declaration has been used.
12451    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12452      Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12453      if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12454        if (Constructor->isDefaultConstructor()) {
12455          if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12456            return;
12457          DefineImplicitDefaultConstructor(Loc, Constructor);
12458        } else if (Constructor->isCopyConstructor()) {
12459          DefineImplicitCopyConstructor(Loc, Constructor);
12460        } else if (Constructor->isMoveConstructor()) {
12461          DefineImplicitMoveConstructor(Loc, Constructor);
12462        }
12463      } else if (Constructor->getInheritedConstructor()) {
12464        DefineInheritingConstructor(Loc, Constructor);
12465      }
12466    } else if (CXXDestructorDecl *Destructor =
12467                   dyn_cast<CXXDestructorDecl>(Func)) {
12468      Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12469      if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12470        if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12471          return;
12472        DefineImplicitDestructor(Loc, Destructor);
12473      }
12474      if (Destructor->isVirtual() && getLangOpts().AppleKext)
12475        MarkVTableUsed(Loc, Destructor->getParent());
12476    } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12477      if (MethodDecl->isOverloadedOperator() &&
12478          MethodDecl->getOverloadedOperator() == OO_Equal) {
12479        MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12480        if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12481          if (MethodDecl->isCopyAssignmentOperator())
12482            DefineImplicitCopyAssignment(Loc, MethodDecl);
12483          else
12484            DefineImplicitMoveAssignment(Loc, MethodDecl);
12485        }
12486      } else if (isa<CXXConversionDecl>(MethodDecl) &&
12487                 MethodDecl->getParent()->isLambda()) {
12488        CXXConversionDecl *Conversion =
12489            cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12490        if (Conversion->isLambdaToBlockPointerConversion())
12491          DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12492        else
12493          DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12494      } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12495        MarkVTableUsed(Loc, MethodDecl->getParent());
12496    }
12497  
12498    // Recursive functions should be marked when used from another function.
12499    // FIXME: Is this really right?
12500    if (CurContext == Func) return;
12501  
12502    // Resolve the exception specification for any function which is
12503    // used: CodeGen will need it.
12504    const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12505    if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12506      ResolveExceptionSpec(Loc, FPT);
12507  
12508    if (!OdrUse) return;
12509  
12510    // Implicit instantiation of function templates and member functions of
12511    // class templates.
12512    if (Func->isImplicitlyInstantiable()) {
12513      bool AlreadyInstantiated = false;
12514      SourceLocation PointOfInstantiation = Loc;
12515      if (FunctionTemplateSpecializationInfo *SpecInfo
12516                                = Func->getTemplateSpecializationInfo()) {
12517        if (SpecInfo->getPointOfInstantiation().isInvalid())
12518          SpecInfo->setPointOfInstantiation(Loc);
12519        else if (SpecInfo->getTemplateSpecializationKind()
12520                   == TSK_ImplicitInstantiation) {
12521          AlreadyInstantiated = true;
12522          PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12523        }
12524      } else if (MemberSpecializationInfo *MSInfo
12525                                  = Func->getMemberSpecializationInfo()) {
12526        if (MSInfo->getPointOfInstantiation().isInvalid())
12527          MSInfo->setPointOfInstantiation(Loc);
12528        else if (MSInfo->getTemplateSpecializationKind()
12529                   == TSK_ImplicitInstantiation) {
12530          AlreadyInstantiated = true;
12531          PointOfInstantiation = MSInfo->getPointOfInstantiation();
12532        }
12533      }
12534  
12535      if (!AlreadyInstantiated || Func->isConstexpr()) {
12536        if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12537            cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12538            ActiveTemplateInstantiations.size())
12539          PendingLocalImplicitInstantiations.push_back(
12540              std::make_pair(Func, PointOfInstantiation));
12541        else if (Func->isConstexpr())
12542          // Do not defer instantiations of constexpr functions, to avoid the
12543          // expression evaluator needing to call back into Sema if it sees a
12544          // call to such a function.
12545          InstantiateFunctionDefinition(PointOfInstantiation, Func);
12546        else {
12547          PendingInstantiations.push_back(std::make_pair(Func,
12548                                                         PointOfInstantiation));
12549          // Notify the consumer that a function was implicitly instantiated.
12550          Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12551        }
12552      }
12553    } else {
12554      // Walk redefinitions, as some of them may be instantiable.
12555      for (auto i : Func->redecls()) {
12556        if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12557          MarkFunctionReferenced(Loc, i);
12558      }
12559    }
12560  
12561    // Keep track of used but undefined functions.
12562    if (!Func->isDefined()) {
12563      if (mightHaveNonExternalLinkage(Func))
12564        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12565      else if (Func->getMostRecentDecl()->isInlined() &&
12566               !LangOpts.GNUInline &&
12567               !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12568        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12569    }
12570  
12571    // Normally the most current decl is marked used while processing the use and
12572    // any subsequent decls are marked used by decl merging. This fails with
12573    // template instantiation since marking can happen at the end of the file
12574    // and, because of the two phase lookup, this function is called with at
12575    // decl in the middle of a decl chain. We loop to maintain the invariant
12576    // that once a decl is used, all decls after it are also used.
12577    for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12578      F->markUsed(Context);
12579      if (F == Func)
12580        break;
12581    }
12582  }
12583  
12584  static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,VarDecl * var,DeclContext * DC)12585  diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12586                                     VarDecl *var, DeclContext *DC) {
12587    DeclContext *VarDC = var->getDeclContext();
12588  
12589    //  If the parameter still belongs to the translation unit, then
12590    //  we're actually just using one parameter in the declaration of
12591    //  the next.
12592    if (isa<ParmVarDecl>(var) &&
12593        isa<TranslationUnitDecl>(VarDC))
12594      return;
12595  
12596    // For C code, don't diagnose about capture if we're not actually in code
12597    // right now; it's impossible to write a non-constant expression outside of
12598    // function context, so we'll get other (more useful) diagnostics later.
12599    //
12600    // For C++, things get a bit more nasty... it would be nice to suppress this
12601    // diagnostic for certain cases like using a local variable in an array bound
12602    // for a member of a local class, but the correct predicate is not obvious.
12603    if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12604      return;
12605  
12606    if (isa<CXXMethodDecl>(VarDC) &&
12607        cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12608      S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12609        << var->getIdentifier();
12610    } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12611      S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12612        << var->getIdentifier() << fn->getDeclName();
12613    } else if (isa<BlockDecl>(VarDC)) {
12614      S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12615        << var->getIdentifier();
12616    } else {
12617      // FIXME: Is there any other context where a local variable can be
12618      // declared?
12619      S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12620        << var->getIdentifier();
12621    }
12622  
12623    S.Diag(var->getLocation(), diag::note_entity_declared_at)
12624        << var->getIdentifier();
12625  
12626    // FIXME: Add additional diagnostic info about class etc. which prevents
12627    // capture.
12628  }
12629  
12630  
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)12631  static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12632                                        bool &SubCapturesAreNested,
12633                                        QualType &CaptureType,
12634                                        QualType &DeclRefType) {
12635     // Check whether we've already captured it.
12636    if (CSI->CaptureMap.count(Var)) {
12637      // If we found a capture, any subcaptures are nested.
12638      SubCapturesAreNested = true;
12639  
12640      // Retrieve the capture type for this variable.
12641      CaptureType = CSI->getCapture(Var).getCaptureType();
12642  
12643      // Compute the type of an expression that refers to this variable.
12644      DeclRefType = CaptureType.getNonReferenceType();
12645  
12646      // Similarly to mutable captures in lambda, all the OpenMP captures by copy
12647      // are mutable in the sense that user can change their value - they are
12648      // private instances of the captured declarations.
12649      const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12650      if (Cap.isCopyCapture() &&
12651          !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
12652          !(isa<CapturedRegionScopeInfo>(CSI) &&
12653            cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
12654        DeclRefType.addConst();
12655      return true;
12656    }
12657    return false;
12658  }
12659  
12660  // Only block literals, captured statements, and lambda expressions can
12661  // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)12662  static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12663                                   SourceLocation Loc,
12664                                   const bool Diagnose, Sema &S) {
12665    if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12666      return getLambdaAwareParentOfDeclContext(DC);
12667    else if (Var->hasLocalStorage()) {
12668      if (Diagnose)
12669         diagnoseUncapturableValueReference(S, Loc, Var, DC);
12670    }
12671    return nullptr;
12672  }
12673  
12674  // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12675  // certain types of variables (unnamed, variably modified types etc.)
12676  // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)12677  static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12678                                   SourceLocation Loc,
12679                                   const bool Diagnose, Sema &S) {
12680  
12681    bool IsBlock = isa<BlockScopeInfo>(CSI);
12682    bool IsLambda = isa<LambdaScopeInfo>(CSI);
12683  
12684    // Lambdas are not allowed to capture unnamed variables
12685    // (e.g. anonymous unions).
12686    // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12687    // assuming that's the intent.
12688    if (IsLambda && !Var->getDeclName()) {
12689      if (Diagnose) {
12690        S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12691        S.Diag(Var->getLocation(), diag::note_declared_at);
12692      }
12693      return false;
12694    }
12695  
12696    // Prohibit variably-modified types in blocks; they're difficult to deal with.
12697    if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12698      if (Diagnose) {
12699        S.Diag(Loc, diag::err_ref_vm_type);
12700        S.Diag(Var->getLocation(), diag::note_previous_decl)
12701          << Var->getDeclName();
12702      }
12703      return false;
12704    }
12705    // Prohibit structs with flexible array members too.
12706    // We cannot capture what is in the tail end of the struct.
12707    if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12708      if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12709        if (Diagnose) {
12710          if (IsBlock)
12711            S.Diag(Loc, diag::err_ref_flexarray_type);
12712          else
12713            S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12714              << Var->getDeclName();
12715          S.Diag(Var->getLocation(), diag::note_previous_decl)
12716            << Var->getDeclName();
12717        }
12718        return false;
12719      }
12720    }
12721    const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12722    // Lambdas and captured statements are not allowed to capture __block
12723    // variables; they don't support the expected semantics.
12724    if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12725      if (Diagnose) {
12726        S.Diag(Loc, diag::err_capture_block_variable)
12727          << Var->getDeclName() << !IsLambda;
12728        S.Diag(Var->getLocation(), diag::note_previous_decl)
12729          << Var->getDeclName();
12730      }
12731      return false;
12732    }
12733  
12734    return true;
12735  }
12736  
12737  // 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)12738  static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12739                                   SourceLocation Loc,
12740                                   const bool BuildAndDiagnose,
12741                                   QualType &CaptureType,
12742                                   QualType &DeclRefType,
12743                                   const bool Nested,
12744                                   Sema &S) {
12745    Expr *CopyExpr = nullptr;
12746    bool ByRef = false;
12747  
12748    // Blocks are not allowed to capture arrays.
12749    if (CaptureType->isArrayType()) {
12750      if (BuildAndDiagnose) {
12751        S.Diag(Loc, diag::err_ref_array_type);
12752        S.Diag(Var->getLocation(), diag::note_previous_decl)
12753        << Var->getDeclName();
12754      }
12755      return false;
12756    }
12757  
12758    // Forbid the block-capture of autoreleasing variables.
12759    if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12760      if (BuildAndDiagnose) {
12761        S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12762          << /*block*/ 0;
12763        S.Diag(Var->getLocation(), diag::note_previous_decl)
12764          << Var->getDeclName();
12765      }
12766      return false;
12767    }
12768    const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12769    if (HasBlocksAttr || CaptureType->isReferenceType()) {
12770      // Block capture by reference does not change the capture or
12771      // declaration reference types.
12772      ByRef = true;
12773    } else {
12774      // Block capture by copy introduces 'const'.
12775      CaptureType = CaptureType.getNonReferenceType().withConst();
12776      DeclRefType = CaptureType;
12777  
12778      if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12779        if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12780          // The capture logic needs the destructor, so make sure we mark it.
12781          // Usually this is unnecessary because most local variables have
12782          // their destructors marked at declaration time, but parameters are
12783          // an exception because it's technically only the call site that
12784          // actually requires the destructor.
12785          if (isa<ParmVarDecl>(Var))
12786            S.FinalizeVarWithDestructor(Var, Record);
12787  
12788          // Enter a new evaluation context to insulate the copy
12789          // full-expression.
12790          EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12791  
12792          // According to the blocks spec, the capture of a variable from
12793          // the stack requires a const copy constructor.  This is not true
12794          // of the copy/move done to move a __block variable to the heap.
12795          Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12796                                                    DeclRefType.withConst(),
12797                                                    VK_LValue, Loc);
12798  
12799          ExprResult Result
12800            = S.PerformCopyInitialization(
12801                InitializedEntity::InitializeBlock(Var->getLocation(),
12802                                                    CaptureType, false),
12803                Loc, DeclRef);
12804  
12805          // Build a full-expression copy expression if initialization
12806          // succeeded and used a non-trivial constructor.  Recover from
12807          // errors by pretending that the copy isn't necessary.
12808          if (!Result.isInvalid() &&
12809              !cast<CXXConstructExpr>(Result.get())->getConstructor()
12810                  ->isTrivial()) {
12811            Result = S.MaybeCreateExprWithCleanups(Result);
12812            CopyExpr = Result.get();
12813          }
12814        }
12815      }
12816    }
12817  
12818    // Actually capture the variable.
12819    if (BuildAndDiagnose)
12820      BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12821                      SourceLocation(), CaptureType, CopyExpr);
12822  
12823    return true;
12824  
12825  }
12826  
12827  
12828  /// \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)12829  static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12830                                      VarDecl *Var,
12831                                      SourceLocation Loc,
12832                                      const bool BuildAndDiagnose,
12833                                      QualType &CaptureType,
12834                                      QualType &DeclRefType,
12835                                      const bool RefersToCapturedVariable,
12836                                      Sema &S) {
12837  
12838    // By default, capture variables by reference.
12839    bool ByRef = true;
12840    // Using an LValue reference type is consistent with Lambdas (see below).
12841    if (S.getLangOpts().OpenMP) {
12842      ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
12843      if (S.IsOpenMPCapturedVar(Var))
12844        DeclRefType = DeclRefType.getUnqualifiedType();
12845    }
12846  
12847    if (ByRef)
12848      CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12849    else
12850      CaptureType = DeclRefType;
12851  
12852    Expr *CopyExpr = nullptr;
12853    if (BuildAndDiagnose) {
12854      // The current implementation assumes that all variables are captured
12855      // by references. Since there is no capture by copy, no expression
12856      // evaluation will be needed.
12857      RecordDecl *RD = RSI->TheRecordDecl;
12858  
12859      FieldDecl *Field
12860        = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
12861                            S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
12862                            nullptr, false, ICIS_NoInit);
12863      Field->setImplicit(true);
12864      Field->setAccess(AS_private);
12865      RD->addDecl(Field);
12866  
12867      CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12868                                              DeclRefType, VK_LValue, Loc);
12869      Var->setReferenced(true);
12870      Var->markUsed(S.Context);
12871    }
12872  
12873    // Actually capture the variable.
12874    if (BuildAndDiagnose)
12875      RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
12876                      SourceLocation(), CaptureType, CopyExpr);
12877  
12878  
12879    return true;
12880  }
12881  
12882  /// \brief Create a field within the lambda class for the variable
12883  /// being captured.
addAsFieldToClosureType(Sema & S,LambdaScopeInfo * LSI,VarDecl * Var,QualType FieldType,QualType DeclRefType,SourceLocation Loc,bool RefersToCapturedVariable)12884  static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
12885                                      QualType FieldType, QualType DeclRefType,
12886                                      SourceLocation Loc,
12887                                      bool RefersToCapturedVariable) {
12888    CXXRecordDecl *Lambda = LSI->Lambda;
12889  
12890    // Build the non-static data member.
12891    FieldDecl *Field
12892      = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12893                          S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12894                          nullptr, false, ICIS_NoInit);
12895    Field->setImplicit(true);
12896    Field->setAccess(AS_private);
12897    Lambda->addDecl(Field);
12898  }
12899  
12900  /// \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)12901  static bool captureInLambda(LambdaScopeInfo *LSI,
12902                              VarDecl *Var,
12903                              SourceLocation Loc,
12904                              const bool BuildAndDiagnose,
12905                              QualType &CaptureType,
12906                              QualType &DeclRefType,
12907                              const bool RefersToCapturedVariable,
12908                              const Sema::TryCaptureKind Kind,
12909                              SourceLocation EllipsisLoc,
12910                              const bool IsTopScope,
12911                              Sema &S) {
12912  
12913    // Determine whether we are capturing by reference or by value.
12914    bool ByRef = false;
12915    if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12916      ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12917    } else {
12918      ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12919    }
12920  
12921    // Compute the type of the field that will capture this variable.
12922    if (ByRef) {
12923      // C++11 [expr.prim.lambda]p15:
12924      //   An entity is captured by reference if it is implicitly or
12925      //   explicitly captured but not captured by copy. It is
12926      //   unspecified whether additional unnamed non-static data
12927      //   members are declared in the closure type for entities
12928      //   captured by reference.
12929      //
12930      // FIXME: It is not clear whether we want to build an lvalue reference
12931      // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12932      // to do the former, while EDG does the latter. Core issue 1249 will
12933      // clarify, but for now we follow GCC because it's a more permissive and
12934      // easily defensible position.
12935      CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12936    } else {
12937      // C++11 [expr.prim.lambda]p14:
12938      //   For each entity captured by copy, an unnamed non-static
12939      //   data member is declared in the closure type. The
12940      //   declaration order of these members is unspecified. The type
12941      //   of such a data member is the type of the corresponding
12942      //   captured entity if the entity is not a reference to an
12943      //   object, or the referenced type otherwise. [Note: If the
12944      //   captured entity is a reference to a function, the
12945      //   corresponding data member is also a reference to a
12946      //   function. - end note ]
12947      if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12948        if (!RefType->getPointeeType()->isFunctionType())
12949          CaptureType = RefType->getPointeeType();
12950      }
12951  
12952      // Forbid the lambda copy-capture of autoreleasing variables.
12953      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12954        if (BuildAndDiagnose) {
12955          S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12956          S.Diag(Var->getLocation(), diag::note_previous_decl)
12957            << Var->getDeclName();
12958        }
12959        return false;
12960      }
12961  
12962      // Make sure that by-copy captures are of a complete and non-abstract type.
12963      if (BuildAndDiagnose) {
12964        if (!CaptureType->isDependentType() &&
12965            S.RequireCompleteType(Loc, CaptureType,
12966                                  diag::err_capture_of_incomplete_type,
12967                                  Var->getDeclName()))
12968          return false;
12969  
12970        if (S.RequireNonAbstractType(Loc, CaptureType,
12971                                     diag::err_capture_of_abstract_type))
12972          return false;
12973      }
12974    }
12975  
12976    // Capture this variable in the lambda.
12977    if (BuildAndDiagnose)
12978      addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
12979                              RefersToCapturedVariable);
12980  
12981    // Compute the type of a reference to this captured variable.
12982    if (ByRef)
12983      DeclRefType = CaptureType.getNonReferenceType();
12984    else {
12985      // C++ [expr.prim.lambda]p5:
12986      //   The closure type for a lambda-expression has a public inline
12987      //   function call operator [...]. This function call operator is
12988      //   declared const (9.3.1) if and only if the lambda-expression’s
12989      //   parameter-declaration-clause is not followed by mutable.
12990      DeclRefType = CaptureType.getNonReferenceType();
12991      if (!LSI->Mutable && !CaptureType->isReferenceType())
12992        DeclRefType.addConst();
12993    }
12994  
12995    // Add the capture.
12996    if (BuildAndDiagnose)
12997      LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
12998                      Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
12999  
13000    return true;
13001  }
13002  
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)13003  bool Sema::tryCaptureVariable(
13004      VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13005      SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13006      QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13007    // An init-capture is notionally from the context surrounding its
13008    // declaration, but its parent DC is the lambda class.
13009    DeclContext *VarDC = Var->getDeclContext();
13010    if (Var->isInitCapture())
13011      VarDC = VarDC->getParent();
13012  
13013    DeclContext *DC = CurContext;
13014    const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13015        ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13016    // We need to sync up the Declaration Context with the
13017    // FunctionScopeIndexToStopAt
13018    if (FunctionScopeIndexToStopAt) {
13019      unsigned FSIndex = FunctionScopes.size() - 1;
13020      while (FSIndex != MaxFunctionScopesIndex) {
13021        DC = getLambdaAwareParentOfDeclContext(DC);
13022        --FSIndex;
13023      }
13024    }
13025  
13026  
13027    // If the variable is declared in the current context, there is no need to
13028    // capture it.
13029    if (VarDC == DC) return true;
13030  
13031    // Capture global variables if it is required to use private copy of this
13032    // variable.
13033    bool IsGlobal = !Var->hasLocalStorage();
13034    if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
13035      return true;
13036  
13037    // Walk up the stack to determine whether we can capture the variable,
13038    // performing the "simple" checks that don't depend on type. We stop when
13039    // we've either hit the declared scope of the variable or find an existing
13040    // capture of that variable.  We start from the innermost capturing-entity
13041    // (the DC) and ensure that all intervening capturing-entities
13042    // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13043    // declcontext can either capture the variable or have already captured
13044    // the variable.
13045    CaptureType = Var->getType();
13046    DeclRefType = CaptureType.getNonReferenceType();
13047    bool Nested = false;
13048    bool Explicit = (Kind != TryCapture_Implicit);
13049    unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13050    unsigned OpenMPLevel = 0;
13051    do {
13052      // Only block literals, captured statements, and lambda expressions can
13053      // capture; other scopes don't work.
13054      DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13055                                                                ExprLoc,
13056                                                                BuildAndDiagnose,
13057                                                                *this);
13058      // We need to check for the parent *first* because, if we *have*
13059      // private-captured a global variable, we need to recursively capture it in
13060      // intermediate blocks, lambdas, etc.
13061      if (!ParentDC) {
13062        if (IsGlobal) {
13063          FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13064          break;
13065        }
13066        return true;
13067      }
13068  
13069      FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13070      CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13071  
13072  
13073      // Check whether we've already captured it.
13074      if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13075                                               DeclRefType))
13076        break;
13077      // If we are instantiating a generic lambda call operator body,
13078      // we do not want to capture new variables.  What was captured
13079      // during either a lambdas transformation or initial parsing
13080      // should be used.
13081      if (isGenericLambdaCallOperatorSpecialization(DC)) {
13082        if (BuildAndDiagnose) {
13083          LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13084          if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13085            Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13086            Diag(Var->getLocation(), diag::note_previous_decl)
13087               << Var->getDeclName();
13088            Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13089          } else
13090            diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13091        }
13092        return true;
13093      }
13094      // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13095      // certain types of variables (unnamed, variably modified types etc.)
13096      // so check for eligibility.
13097      if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13098         return true;
13099  
13100      // Try to capture variable-length arrays types.
13101      if (Var->getType()->isVariablyModifiedType()) {
13102        // We're going to walk down into the type and look for VLA
13103        // expressions.
13104        QualType QTy = Var->getType();
13105        if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13106          QTy = PVD->getOriginalType();
13107        do {
13108          const Type *Ty = QTy.getTypePtr();
13109          switch (Ty->getTypeClass()) {
13110  #define TYPE(Class, Base)
13111  #define ABSTRACT_TYPE(Class, Base)
13112  #define NON_CANONICAL_TYPE(Class, Base)
13113  #define DEPENDENT_TYPE(Class, Base) case Type::Class:
13114  #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
13115  #include "clang/AST/TypeNodes.def"
13116            QTy = QualType();
13117            break;
13118          // These types are never variably-modified.
13119          case Type::Builtin:
13120          case Type::Complex:
13121          case Type::Vector:
13122          case Type::ExtVector:
13123          case Type::Record:
13124          case Type::Enum:
13125          case Type::Elaborated:
13126          case Type::TemplateSpecialization:
13127          case Type::ObjCObject:
13128          case Type::ObjCInterface:
13129          case Type::ObjCObjectPointer:
13130            llvm_unreachable("type class is never variably-modified!");
13131          case Type::Adjusted:
13132            QTy = cast<AdjustedType>(Ty)->getOriginalType();
13133            break;
13134          case Type::Decayed:
13135            QTy = cast<DecayedType>(Ty)->getPointeeType();
13136            break;
13137          case Type::Pointer:
13138            QTy = cast<PointerType>(Ty)->getPointeeType();
13139            break;
13140          case Type::BlockPointer:
13141            QTy = cast<BlockPointerType>(Ty)->getPointeeType();
13142            break;
13143          case Type::LValueReference:
13144          case Type::RValueReference:
13145            QTy = cast<ReferenceType>(Ty)->getPointeeType();
13146            break;
13147          case Type::MemberPointer:
13148            QTy = cast<MemberPointerType>(Ty)->getPointeeType();
13149            break;
13150          case Type::ConstantArray:
13151          case Type::IncompleteArray:
13152            // Losing element qualification here is fine.
13153            QTy = cast<ArrayType>(Ty)->getElementType();
13154            break;
13155          case Type::VariableArray: {
13156            // Losing element qualification here is fine.
13157            const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
13158  
13159            // Unknown size indication requires no size computation.
13160            // Otherwise, evaluate and record it.
13161            if (auto Size = VAT->getSizeExpr()) {
13162              if (!CSI->isVLATypeCaptured(VAT)) {
13163                RecordDecl *CapRecord = nullptr;
13164                if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
13165                  CapRecord = LSI->Lambda;
13166                } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13167                  CapRecord = CRSI->TheRecordDecl;
13168                }
13169                if (CapRecord) {
13170                  auto ExprLoc = Size->getExprLoc();
13171                  auto SizeType = Context.getSizeType();
13172                  // Build the non-static data member.
13173                  auto Field = FieldDecl::Create(
13174                      Context, CapRecord, ExprLoc, ExprLoc,
13175                      /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
13176                      /*BW*/ nullptr, /*Mutable*/ false,
13177                      /*InitStyle*/ ICIS_NoInit);
13178                  Field->setImplicit(true);
13179                  Field->setAccess(AS_private);
13180                  Field->setCapturedVLAType(VAT);
13181                  CapRecord->addDecl(Field);
13182  
13183                  CSI->addVLATypeCapture(ExprLoc, SizeType);
13184                }
13185              }
13186            }
13187            QTy = VAT->getElementType();
13188            break;
13189          }
13190          case Type::FunctionProto:
13191          case Type::FunctionNoProto:
13192            QTy = cast<FunctionType>(Ty)->getReturnType();
13193            break;
13194          case Type::Paren:
13195          case Type::TypeOf:
13196          case Type::UnaryTransform:
13197          case Type::Attributed:
13198          case Type::SubstTemplateTypeParm:
13199          case Type::PackExpansion:
13200            // Keep walking after single level desugaring.
13201            QTy = QTy.getSingleStepDesugaredType(getASTContext());
13202            break;
13203          case Type::Typedef:
13204            QTy = cast<TypedefType>(Ty)->desugar();
13205            break;
13206          case Type::Decltype:
13207            QTy = cast<DecltypeType>(Ty)->desugar();
13208            break;
13209          case Type::Auto:
13210            QTy = cast<AutoType>(Ty)->getDeducedType();
13211            break;
13212          case Type::TypeOfExpr:
13213            QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
13214            break;
13215          case Type::Atomic:
13216            QTy = cast<AtomicType>(Ty)->getValueType();
13217            break;
13218          }
13219        } while (!QTy.isNull() && QTy->isVariablyModifiedType());
13220      }
13221  
13222      if (getLangOpts().OpenMP) {
13223        if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13224          // OpenMP private variables should not be captured in outer scope, so
13225          // just break here. Similarly, global variables that are captured in a
13226          // target region should not be captured outside the scope of the region.
13227          if (RSI->CapRegionKind == CR_OpenMP) {
13228            auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
13229            // When we detect target captures we are looking from inside the
13230            // target region, therefore we need to propagate the capture from the
13231            // enclosing region. Therefore, the capture is not initially nested.
13232            if (isTargetCap)
13233              FunctionScopesIndex--;
13234  
13235            if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
13236              Nested = !isTargetCap;
13237              DeclRefType = DeclRefType.getUnqualifiedType();
13238              CaptureType = Context.getLValueReferenceType(DeclRefType);
13239              break;
13240            }
13241            ++OpenMPLevel;
13242          }
13243        }
13244      }
13245      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13246        // No capture-default, and this is not an explicit capture
13247        // so cannot capture this variable.
13248        if (BuildAndDiagnose) {
13249          Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13250          Diag(Var->getLocation(), diag::note_previous_decl)
13251            << Var->getDeclName();
13252          Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13253               diag::note_lambda_decl);
13254          // FIXME: If we error out because an outer lambda can not implicitly
13255          // capture a variable that an inner lambda explicitly captures, we
13256          // should have the inner lambda do the explicit capture - because
13257          // it makes for cleaner diagnostics later.  This would purely be done
13258          // so that the diagnostic does not misleadingly claim that a variable
13259          // can not be captured by a lambda implicitly even though it is captured
13260          // explicitly.  Suggestion:
13261          //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13262          //    at the function head
13263          //  - cache the StartingDeclContext - this must be a lambda
13264          //  - captureInLambda in the innermost lambda the variable.
13265        }
13266        return true;
13267      }
13268  
13269      FunctionScopesIndex--;
13270      DC = ParentDC;
13271      Explicit = false;
13272    } while (!VarDC->Equals(DC));
13273  
13274    // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13275    // computing the type of the capture at each step, checking type-specific
13276    // requirements, and adding captures if requested.
13277    // If the variable had already been captured previously, we start capturing
13278    // at the lambda nested within that one.
13279    for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13280         ++I) {
13281      CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13282  
13283      if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13284        if (!captureInBlock(BSI, Var, ExprLoc,
13285                            BuildAndDiagnose, CaptureType,
13286                            DeclRefType, Nested, *this))
13287          return true;
13288        Nested = true;
13289      } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13290        if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13291                                     BuildAndDiagnose, CaptureType,
13292                                     DeclRefType, Nested, *this))
13293          return true;
13294        Nested = true;
13295      } else {
13296        LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13297        if (!captureInLambda(LSI, Var, ExprLoc,
13298                             BuildAndDiagnose, CaptureType,
13299                             DeclRefType, Nested, Kind, EllipsisLoc,
13300                              /*IsTopScope*/I == N - 1, *this))
13301          return true;
13302        Nested = true;
13303      }
13304    }
13305    return false;
13306  }
13307  
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)13308  bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13309                                TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13310    QualType CaptureType;
13311    QualType DeclRefType;
13312    return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13313                              /*BuildAndDiagnose=*/true, CaptureType,
13314                              DeclRefType, nullptr);
13315  }
13316  
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)13317  bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13318    QualType CaptureType;
13319    QualType DeclRefType;
13320    return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13321                               /*BuildAndDiagnose=*/false, CaptureType,
13322                               DeclRefType, nullptr);
13323  }
13324  
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)13325  QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13326    QualType CaptureType;
13327    QualType DeclRefType;
13328  
13329    // Determine whether we can capture this variable.
13330    if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13331                           /*BuildAndDiagnose=*/false, CaptureType,
13332                           DeclRefType, nullptr))
13333      return QualType();
13334  
13335    return DeclRefType;
13336  }
13337  
13338  
13339  
13340  // If either the type of the variable or the initializer is dependent,
13341  // return false. Otherwise, determine whether the variable is a constant
13342  // expression. Use this if you need to know if a variable that might or
13343  // might not be dependent is truly a constant expression.
IsVariableNonDependentAndAConstantExpression(VarDecl * Var,ASTContext & Context)13344  static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13345      ASTContext &Context) {
13346  
13347    if (Var->getType()->isDependentType())
13348      return false;
13349    const VarDecl *DefVD = nullptr;
13350    Var->getAnyInitializer(DefVD);
13351    if (!DefVD)
13352      return false;
13353    EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13354    Expr *Init = cast<Expr>(Eval->Value);
13355    if (Init->isValueDependent())
13356      return false;
13357    return IsVariableAConstantExpression(Var, Context);
13358  }
13359  
13360  
UpdateMarkingForLValueToRValue(Expr * E)13361  void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13362    // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13363    // an object that satisfies the requirements for appearing in a
13364    // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13365    // is immediately applied."  This function handles the lvalue-to-rvalue
13366    // conversion part.
13367    MaybeODRUseExprs.erase(E->IgnoreParens());
13368  
13369    // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13370    // to a variable that is a constant expression, and if so, identify it as
13371    // a reference to a variable that does not involve an odr-use of that
13372    // variable.
13373    if (LambdaScopeInfo *LSI = getCurLambda()) {
13374      Expr *SansParensExpr = E->IgnoreParens();
13375      VarDecl *Var = nullptr;
13376      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13377        Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13378      else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13379        Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13380  
13381      if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13382        LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13383    }
13384  }
13385  
ActOnConstantExpression(ExprResult Res)13386  ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13387    Res = CorrectDelayedTyposInExpr(Res);
13388  
13389    if (!Res.isUsable())
13390      return Res;
13391  
13392    // If a constant-expression is a reference to a variable where we delay
13393    // deciding whether it is an odr-use, just assume we will apply the
13394    // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13395    // (a non-type template argument), we have special handling anyway.
13396    UpdateMarkingForLValueToRValue(Res.get());
13397    return Res;
13398  }
13399  
CleanupVarDeclMarking()13400  void Sema::CleanupVarDeclMarking() {
13401    for (Expr *E : MaybeODRUseExprs) {
13402      VarDecl *Var;
13403      SourceLocation Loc;
13404      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13405        Var = cast<VarDecl>(DRE->getDecl());
13406        Loc = DRE->getLocation();
13407      } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13408        Var = cast<VarDecl>(ME->getMemberDecl());
13409        Loc = ME->getMemberLoc();
13410      } else {
13411        llvm_unreachable("Unexpected expression");
13412      }
13413  
13414      MarkVarDeclODRUsed(Var, Loc, *this,
13415                         /*MaxFunctionScopeIndex Pointer*/ nullptr);
13416    }
13417  
13418    MaybeODRUseExprs.clear();
13419  }
13420  
13421  
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)13422  static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13423                                      VarDecl *Var, Expr *E) {
13424    assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13425           "Invalid Expr argument to DoMarkVarDeclReferenced");
13426    Var->setReferenced();
13427  
13428    TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13429    bool MarkODRUsed = true;
13430  
13431    // If the context is not potentially evaluated, this is not an odr-use and
13432    // does not trigger instantiation.
13433    if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13434      if (SemaRef.isUnevaluatedContext())
13435        return;
13436  
13437      // If we don't yet know whether this context is going to end up being an
13438      // evaluated context, and we're referencing a variable from an enclosing
13439      // scope, add a potential capture.
13440      //
13441      // FIXME: Is this necessary? These contexts are only used for default
13442      // arguments, where local variables can't be used.
13443      const bool RefersToEnclosingScope =
13444          (SemaRef.CurContext != Var->getDeclContext() &&
13445           Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13446      if (RefersToEnclosingScope) {
13447        if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13448          // If a variable could potentially be odr-used, defer marking it so
13449          // until we finish analyzing the full expression for any
13450          // lvalue-to-rvalue
13451          // or discarded value conversions that would obviate odr-use.
13452          // Add it to the list of potential captures that will be analyzed
13453          // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13454          // unless the variable is a reference that was initialized by a constant
13455          // expression (this will never need to be captured or odr-used).
13456          assert(E && "Capture variable should be used in an expression.");
13457          if (!Var->getType()->isReferenceType() ||
13458              !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13459            LSI->addPotentialCapture(E->IgnoreParens());
13460        }
13461      }
13462  
13463      if (!isTemplateInstantiation(TSK))
13464        return;
13465  
13466      // Instantiate, but do not mark as odr-used, variable templates.
13467      MarkODRUsed = false;
13468    }
13469  
13470    VarTemplateSpecializationDecl *VarSpec =
13471        dyn_cast<VarTemplateSpecializationDecl>(Var);
13472    assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13473           "Can't instantiate a partial template specialization.");
13474  
13475    // Perform implicit instantiation of static data members, static data member
13476    // templates of class templates, and variable template specializations. Delay
13477    // instantiations of variable templates, except for those that could be used
13478    // in a constant expression.
13479    if (isTemplateInstantiation(TSK)) {
13480      bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13481  
13482      if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13483        if (Var->getPointOfInstantiation().isInvalid()) {
13484          // This is a modification of an existing AST node. Notify listeners.
13485          if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13486            L->StaticDataMemberInstantiated(Var);
13487        } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13488          // Don't bother trying to instantiate it again, unless we might need
13489          // its initializer before we get to the end of the TU.
13490          TryInstantiating = false;
13491      }
13492  
13493      if (Var->getPointOfInstantiation().isInvalid())
13494        Var->setTemplateSpecializationKind(TSK, Loc);
13495  
13496      if (TryInstantiating) {
13497        SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13498        bool InstantiationDependent = false;
13499        bool IsNonDependent =
13500            VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13501                          VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13502                    : true;
13503  
13504        // Do not instantiate specializations that are still type-dependent.
13505        if (IsNonDependent) {
13506          if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13507            // Do not defer instantiations of variables which could be used in a
13508            // constant expression.
13509            SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13510          } else {
13511            SemaRef.PendingInstantiations
13512                .push_back(std::make_pair(Var, PointOfInstantiation));
13513          }
13514        }
13515      }
13516    }
13517  
13518    if(!MarkODRUsed) return;
13519  
13520    // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13521    // the requirements for appearing in a constant expression (5.19) and, if
13522    // it is an object, the lvalue-to-rvalue conversion (4.1)
13523    // is immediately applied."  We check the first part here, and
13524    // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13525    // Note that we use the C++11 definition everywhere because nothing in
13526    // C++03 depends on whether we get the C++03 version correct. The second
13527    // part does not apply to references, since they are not objects.
13528    if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13529      // A reference initialized by a constant expression can never be
13530      // odr-used, so simply ignore it.
13531      if (!Var->getType()->isReferenceType())
13532        SemaRef.MaybeODRUseExprs.insert(E);
13533    } else
13534      MarkVarDeclODRUsed(Var, Loc, SemaRef,
13535                         /*MaxFunctionScopeIndex ptr*/ nullptr);
13536  }
13537  
13538  /// \brief Mark a variable referenced, and check whether it is odr-used
13539  /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13540  /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)13541  void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13542    DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13543  }
13544  
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool OdrUse)13545  static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13546                                 Decl *D, Expr *E, bool OdrUse) {
13547    if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13548      DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13549      return;
13550    }
13551  
13552    SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13553  
13554    // If this is a call to a method via a cast, also mark the method in the
13555    // derived class used in case codegen can devirtualize the call.
13556    const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13557    if (!ME)
13558      return;
13559    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13560    if (!MD)
13561      return;
13562    // Only attempt to devirtualize if this is truly a virtual call.
13563    bool IsVirtualCall = MD->isVirtual() &&
13564                            ME->performsVirtualDispatch(SemaRef.getLangOpts());
13565    if (!IsVirtualCall)
13566      return;
13567    const Expr *Base = ME->getBase();
13568    const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13569    if (!MostDerivedClassDecl)
13570      return;
13571    CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13572    if (!DM || DM->isPure())
13573      return;
13574    SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13575  }
13576  
13577  /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
MarkDeclRefReferenced(DeclRefExpr * E)13578  void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13579    // TODO: update this with DR# once a defect report is filed.
13580    // C++11 defect. The address of a pure member should not be an ODR use, even
13581    // if it's a qualified reference.
13582    bool OdrUse = true;
13583    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13584      if (Method->isVirtual())
13585        OdrUse = false;
13586    MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13587  }
13588  
13589  /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)13590  void Sema::MarkMemberReferenced(MemberExpr *E) {
13591    // C++11 [basic.def.odr]p2:
13592    //   A non-overloaded function whose name appears as a potentially-evaluated
13593    //   expression or a member of a set of candidate functions, if selected by
13594    //   overload resolution when referred to from a potentially-evaluated
13595    //   expression, is odr-used, unless it is a pure virtual function and its
13596    //   name is not explicitly qualified.
13597    bool OdrUse = true;
13598    if (E->performsVirtualDispatch(getLangOpts())) {
13599      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13600        if (Method->isPure())
13601          OdrUse = false;
13602    }
13603    SourceLocation Loc = E->getMemberLoc().isValid() ?
13604                              E->getMemberLoc() : E->getLocStart();
13605    MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13606  }
13607  
13608  /// \brief Perform marking for a reference to an arbitrary declaration.  It
13609  /// marks the declaration referenced, and performs odr-use checking for
13610  /// functions and variables. This method should not be used when building a
13611  /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool OdrUse)13612  void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13613    if (OdrUse) {
13614      if (auto *VD = dyn_cast<VarDecl>(D)) {
13615        MarkVariableReferenced(Loc, VD);
13616        return;
13617      }
13618    }
13619    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13620      MarkFunctionReferenced(Loc, FD, OdrUse);
13621      return;
13622    }
13623    D->setReferenced();
13624  }
13625  
13626  namespace {
13627    // Mark all of the declarations referenced
13628    // FIXME: Not fully implemented yet! We need to have a better understanding
13629    // of when we're entering
13630    class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13631      Sema &S;
13632      SourceLocation Loc;
13633  
13634    public:
13635      typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13636  
MarkReferencedDecls(Sema & S,SourceLocation Loc)13637      MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13638  
13639      bool TraverseTemplateArgument(const TemplateArgument &Arg);
13640      bool TraverseRecordType(RecordType *T);
13641    };
13642  }
13643  
TraverseTemplateArgument(const TemplateArgument & Arg)13644  bool MarkReferencedDecls::TraverseTemplateArgument(
13645      const TemplateArgument &Arg) {
13646    if (Arg.getKind() == TemplateArgument::Declaration) {
13647      if (Decl *D = Arg.getAsDecl())
13648        S.MarkAnyDeclReferenced(Loc, D, true);
13649    }
13650  
13651    return Inherited::TraverseTemplateArgument(Arg);
13652  }
13653  
TraverseRecordType(RecordType * T)13654  bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13655    if (ClassTemplateSpecializationDecl *Spec
13656                    = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13657      const TemplateArgumentList &Args = Spec->getTemplateArgs();
13658      return TraverseTemplateArguments(Args.data(), Args.size());
13659    }
13660  
13661    return true;
13662  }
13663  
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)13664  void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13665    MarkReferencedDecls Marker(*this, Loc);
13666    Marker.TraverseType(Context.getCanonicalType(T));
13667  }
13668  
13669  namespace {
13670    /// \brief Helper class that marks all of the declarations referenced by
13671    /// potentially-evaluated subexpressions as "referenced".
13672    class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13673      Sema &S;
13674      bool SkipLocalVariables;
13675  
13676    public:
13677      typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13678  
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)13679      EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13680        : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13681  
VisitDeclRefExpr(DeclRefExpr * E)13682      void VisitDeclRefExpr(DeclRefExpr *E) {
13683        // If we were asked not to visit local variables, don't.
13684        if (SkipLocalVariables) {
13685          if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13686            if (VD->hasLocalStorage())
13687              return;
13688        }
13689  
13690        S.MarkDeclRefReferenced(E);
13691      }
13692  
VisitMemberExpr(MemberExpr * E)13693      void VisitMemberExpr(MemberExpr *E) {
13694        S.MarkMemberReferenced(E);
13695        Inherited::VisitMemberExpr(E);
13696      }
13697  
VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)13698      void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13699        S.MarkFunctionReferenced(E->getLocStart(),
13700              const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13701        Visit(E->getSubExpr());
13702      }
13703  
VisitCXXNewExpr(CXXNewExpr * E)13704      void VisitCXXNewExpr(CXXNewExpr *E) {
13705        if (E->getOperatorNew())
13706          S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13707        if (E->getOperatorDelete())
13708          S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13709        Inherited::VisitCXXNewExpr(E);
13710      }
13711  
VisitCXXDeleteExpr(CXXDeleteExpr * E)13712      void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13713        if (E->getOperatorDelete())
13714          S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13715        QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13716        if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13717          CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13718          S.MarkFunctionReferenced(E->getLocStart(),
13719                                      S.LookupDestructor(Record));
13720        }
13721  
13722        Inherited::VisitCXXDeleteExpr(E);
13723      }
13724  
VisitCXXConstructExpr(CXXConstructExpr * E)13725      void VisitCXXConstructExpr(CXXConstructExpr *E) {
13726        S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13727        Inherited::VisitCXXConstructExpr(E);
13728      }
13729  
VisitCXXDefaultArgExpr(CXXDefaultArgExpr * E)13730      void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13731        Visit(E->getExpr());
13732      }
13733  
VisitImplicitCastExpr(ImplicitCastExpr * E)13734      void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13735        Inherited::VisitImplicitCastExpr(E);
13736  
13737        if (E->getCastKind() == CK_LValueToRValue)
13738          S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13739      }
13740    };
13741  }
13742  
13743  /// \brief Mark any declarations that appear within this expression or any
13744  /// potentially-evaluated subexpressions as "referenced".
13745  ///
13746  /// \param SkipLocalVariables If true, don't mark local variables as
13747  /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)13748  void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13749                                              bool SkipLocalVariables) {
13750    EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13751  }
13752  
13753  /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13754  /// of the program being compiled.
13755  ///
13756  /// This routine emits the given diagnostic when the code currently being
13757  /// type-checked is "potentially evaluated", meaning that there is a
13758  /// possibility that the code will actually be executable. Code in sizeof()
13759  /// expressions, code used only during overload resolution, etc., are not
13760  /// potentially evaluated. This routine will suppress such diagnostics or,
13761  /// in the absolutely nutty case of potentially potentially evaluated
13762  /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13763  /// later.
13764  ///
13765  /// This routine should be used for all diagnostics that describe the run-time
13766  /// behavior of a program, such as passing a non-POD value through an ellipsis.
13767  /// Failure to do so will likely result in spurious diagnostics or failures
13768  /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)13769  bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13770                                 const PartialDiagnostic &PD) {
13771    switch (ExprEvalContexts.back().Context) {
13772    case Unevaluated:
13773    case UnevaluatedAbstract:
13774      // The argument will never be evaluated, so don't complain.
13775      break;
13776  
13777    case ConstantEvaluated:
13778      // Relevant diagnostics should be produced by constant evaluation.
13779      break;
13780  
13781    case PotentiallyEvaluated:
13782    case PotentiallyEvaluatedIfUsed:
13783      if (Statement && getCurFunctionOrMethodDecl()) {
13784        FunctionScopes.back()->PossiblyUnreachableDiags.
13785          push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13786      }
13787      else
13788        Diag(Loc, PD);
13789  
13790      return true;
13791    }
13792  
13793    return false;
13794  }
13795  
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)13796  bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13797                                 CallExpr *CE, FunctionDecl *FD) {
13798    if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13799      return false;
13800  
13801    // If we're inside a decltype's expression, don't check for a valid return
13802    // type or construct temporaries until we know whether this is the last call.
13803    if (ExprEvalContexts.back().IsDecltype) {
13804      ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13805      return false;
13806    }
13807  
13808    class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13809      FunctionDecl *FD;
13810      CallExpr *CE;
13811  
13812    public:
13813      CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13814        : FD(FD), CE(CE) { }
13815  
13816      void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13817        if (!FD) {
13818          S.Diag(Loc, diag::err_call_incomplete_return)
13819            << T << CE->getSourceRange();
13820          return;
13821        }
13822  
13823        S.Diag(Loc, diag::err_call_function_incomplete_return)
13824          << CE->getSourceRange() << FD->getDeclName() << T;
13825        S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13826            << FD->getDeclName();
13827      }
13828    } Diagnoser(FD, CE);
13829  
13830    if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13831      return true;
13832  
13833    return false;
13834  }
13835  
13836  // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13837  // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)13838  void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13839    SourceLocation Loc;
13840  
13841    unsigned diagnostic = diag::warn_condition_is_assignment;
13842    bool IsOrAssign = false;
13843  
13844    if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13845      if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13846        return;
13847  
13848      IsOrAssign = Op->getOpcode() == BO_OrAssign;
13849  
13850      // Greylist some idioms by putting them into a warning subcategory.
13851      if (ObjCMessageExpr *ME
13852            = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13853        Selector Sel = ME->getSelector();
13854  
13855        // self = [<foo> init...]
13856        if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13857          diagnostic = diag::warn_condition_is_idiomatic_assignment;
13858  
13859        // <foo> = [<bar> nextObject]
13860        else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13861          diagnostic = diag::warn_condition_is_idiomatic_assignment;
13862      }
13863  
13864      Loc = Op->getOperatorLoc();
13865    } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13866      if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13867        return;
13868  
13869      IsOrAssign = Op->getOperator() == OO_PipeEqual;
13870      Loc = Op->getOperatorLoc();
13871    } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13872      return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13873    else {
13874      // Not an assignment.
13875      return;
13876    }
13877  
13878    Diag(Loc, diagnostic) << E->getSourceRange();
13879  
13880    SourceLocation Open = E->getLocStart();
13881    SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
13882    Diag(Loc, diag::note_condition_assign_silence)
13883          << FixItHint::CreateInsertion(Open, "(")
13884          << FixItHint::CreateInsertion(Close, ")");
13885  
13886    if (IsOrAssign)
13887      Diag(Loc, diag::note_condition_or_assign_to_comparison)
13888        << FixItHint::CreateReplacement(Loc, "!=");
13889    else
13890      Diag(Loc, diag::note_condition_assign_to_comparison)
13891        << FixItHint::CreateReplacement(Loc, "==");
13892  }
13893  
13894  /// \brief Redundant parentheses over an equality comparison can indicate
13895  /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)13896  void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13897    // Don't warn if the parens came from a macro.
13898    SourceLocation parenLoc = ParenE->getLocStart();
13899    if (parenLoc.isInvalid() || parenLoc.isMacroID())
13900      return;
13901    // Don't warn for dependent expressions.
13902    if (ParenE->isTypeDependent())
13903      return;
13904  
13905    Expr *E = ParenE->IgnoreParens();
13906  
13907    if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13908      if (opE->getOpcode() == BO_EQ &&
13909          opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13910                                                             == Expr::MLV_Valid) {
13911        SourceLocation Loc = opE->getOperatorLoc();
13912  
13913        Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13914        SourceRange ParenERange = ParenE->getSourceRange();
13915        Diag(Loc, diag::note_equality_comparison_silence)
13916          << FixItHint::CreateRemoval(ParenERange.getBegin())
13917          << FixItHint::CreateRemoval(ParenERange.getEnd());
13918        Diag(Loc, diag::note_equality_comparison_to_assign)
13919          << FixItHint::CreateReplacement(Loc, "=");
13920      }
13921  }
13922  
CheckBooleanCondition(Expr * E,SourceLocation Loc)13923  ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13924    DiagnoseAssignmentAsCondition(E);
13925    if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13926      DiagnoseEqualityWithExtraParens(parenE);
13927  
13928    ExprResult result = CheckPlaceholderExpr(E);
13929    if (result.isInvalid()) return ExprError();
13930    E = result.get();
13931  
13932    if (!E->isTypeDependent()) {
13933      if (getLangOpts().CPlusPlus)
13934        return CheckCXXBooleanCondition(E); // C++ 6.4p4
13935  
13936      ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13937      if (ERes.isInvalid())
13938        return ExprError();
13939      E = ERes.get();
13940  
13941      QualType T = E->getType();
13942      if (!T->isScalarType()) { // C99 6.8.4.1p1
13943        Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13944          << T << E->getSourceRange();
13945        return ExprError();
13946      }
13947      CheckBoolLikeConversion(E, Loc);
13948    }
13949  
13950    return E;
13951  }
13952  
ActOnBooleanCondition(Scope * S,SourceLocation Loc,Expr * SubExpr)13953  ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13954                                         Expr *SubExpr) {
13955    if (!SubExpr)
13956      return ExprError();
13957  
13958    return CheckBooleanCondition(SubExpr, Loc);
13959  }
13960  
13961  namespace {
13962    /// A visitor for rebuilding a call to an __unknown_any expression
13963    /// to have an appropriate type.
13964    struct RebuildUnknownAnyFunction
13965      : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13966  
13967      Sema &S;
13968  
RebuildUnknownAnyFunction__anon3a8c63620b11::RebuildUnknownAnyFunction13969      RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13970  
VisitStmt__anon3a8c63620b11::RebuildUnknownAnyFunction13971      ExprResult VisitStmt(Stmt *S) {
13972        llvm_unreachable("unexpected statement!");
13973      }
13974  
VisitExpr__anon3a8c63620b11::RebuildUnknownAnyFunction13975      ExprResult VisitExpr(Expr *E) {
13976        S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13977          << E->getSourceRange();
13978        return ExprError();
13979      }
13980  
13981      /// Rebuild an expression which simply semantically wraps another
13982      /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon3a8c63620b11::RebuildUnknownAnyFunction13983      template <class T> ExprResult rebuildSugarExpr(T *E) {
13984        ExprResult SubResult = Visit(E->getSubExpr());
13985        if (SubResult.isInvalid()) return ExprError();
13986  
13987        Expr *SubExpr = SubResult.get();
13988        E->setSubExpr(SubExpr);
13989        E->setType(SubExpr->getType());
13990        E->setValueKind(SubExpr->getValueKind());
13991        assert(E->getObjectKind() == OK_Ordinary);
13992        return E;
13993      }
13994  
VisitParenExpr__anon3a8c63620b11::RebuildUnknownAnyFunction13995      ExprResult VisitParenExpr(ParenExpr *E) {
13996        return rebuildSugarExpr(E);
13997      }
13998  
VisitUnaryExtension__anon3a8c63620b11::RebuildUnknownAnyFunction13999      ExprResult VisitUnaryExtension(UnaryOperator *E) {
14000        return rebuildSugarExpr(E);
14001      }
14002  
VisitUnaryAddrOf__anon3a8c63620b11::RebuildUnknownAnyFunction14003      ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14004        ExprResult SubResult = Visit(E->getSubExpr());
14005        if (SubResult.isInvalid()) return ExprError();
14006  
14007        Expr *SubExpr = SubResult.get();
14008        E->setSubExpr(SubExpr);
14009        E->setType(S.Context.getPointerType(SubExpr->getType()));
14010        assert(E->getValueKind() == VK_RValue);
14011        assert(E->getObjectKind() == OK_Ordinary);
14012        return E;
14013      }
14014  
resolveDecl__anon3a8c63620b11::RebuildUnknownAnyFunction14015      ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14016        if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14017  
14018        E->setType(VD->getType());
14019  
14020        assert(E->getValueKind() == VK_RValue);
14021        if (S.getLangOpts().CPlusPlus &&
14022            !(isa<CXXMethodDecl>(VD) &&
14023              cast<CXXMethodDecl>(VD)->isInstance()))
14024          E->setValueKind(VK_LValue);
14025  
14026        return E;
14027      }
14028  
VisitMemberExpr__anon3a8c63620b11::RebuildUnknownAnyFunction14029      ExprResult VisitMemberExpr(MemberExpr *E) {
14030        return resolveDecl(E, E->getMemberDecl());
14031      }
14032  
VisitDeclRefExpr__anon3a8c63620b11::RebuildUnknownAnyFunction14033      ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14034        return resolveDecl(E, E->getDecl());
14035      }
14036    };
14037  }
14038  
14039  /// Given a function expression of unknown-any type, try to rebuild it
14040  /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)14041  static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14042    ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14043    if (Result.isInvalid()) return ExprError();
14044    return S.DefaultFunctionArrayConversion(Result.get());
14045  }
14046  
14047  namespace {
14048    /// A visitor for rebuilding an expression of type __unknown_anytype
14049    /// into one which resolves the type directly on the referring
14050    /// expression.  Strict preservation of the original source
14051    /// structure is not a goal.
14052    struct RebuildUnknownAnyExpr
14053      : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14054  
14055      Sema &S;
14056  
14057      /// The current destination type.
14058      QualType DestType;
14059  
RebuildUnknownAnyExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14060      RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14061        : S(S), DestType(CastType) {}
14062  
VisitStmt__anon3a8c63620c11::RebuildUnknownAnyExpr14063      ExprResult VisitStmt(Stmt *S) {
14064        llvm_unreachable("unexpected statement!");
14065      }
14066  
VisitExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14067      ExprResult VisitExpr(Expr *E) {
14068        S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14069          << E->getSourceRange();
14070        return ExprError();
14071      }
14072  
14073      ExprResult VisitCallExpr(CallExpr *E);
14074      ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14075  
14076      /// Rebuild an expression which simply semantically wraps another
14077      /// expression which it shares the type and value kind of.
rebuildSugarExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14078      template <class T> ExprResult rebuildSugarExpr(T *E) {
14079        ExprResult SubResult = Visit(E->getSubExpr());
14080        if (SubResult.isInvalid()) return ExprError();
14081        Expr *SubExpr = SubResult.get();
14082        E->setSubExpr(SubExpr);
14083        E->setType(SubExpr->getType());
14084        E->setValueKind(SubExpr->getValueKind());
14085        assert(E->getObjectKind() == OK_Ordinary);
14086        return E;
14087      }
14088  
VisitParenExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14089      ExprResult VisitParenExpr(ParenExpr *E) {
14090        return rebuildSugarExpr(E);
14091      }
14092  
VisitUnaryExtension__anon3a8c63620c11::RebuildUnknownAnyExpr14093      ExprResult VisitUnaryExtension(UnaryOperator *E) {
14094        return rebuildSugarExpr(E);
14095      }
14096  
VisitUnaryAddrOf__anon3a8c63620c11::RebuildUnknownAnyExpr14097      ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14098        const PointerType *Ptr = DestType->getAs<PointerType>();
14099        if (!Ptr) {
14100          S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14101            << E->getSourceRange();
14102          return ExprError();
14103        }
14104        assert(E->getValueKind() == VK_RValue);
14105        assert(E->getObjectKind() == OK_Ordinary);
14106        E->setType(DestType);
14107  
14108        // Build the sub-expression as if it were an object of the pointee type.
14109        DestType = Ptr->getPointeeType();
14110        ExprResult SubResult = Visit(E->getSubExpr());
14111        if (SubResult.isInvalid()) return ExprError();
14112        E->setSubExpr(SubResult.get());
14113        return E;
14114      }
14115  
14116      ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14117  
14118      ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14119  
VisitMemberExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14120      ExprResult VisitMemberExpr(MemberExpr *E) {
14121        return resolveDecl(E, E->getMemberDecl());
14122      }
14123  
VisitDeclRefExpr__anon3a8c63620c11::RebuildUnknownAnyExpr14124      ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14125        return resolveDecl(E, E->getDecl());
14126      }
14127    };
14128  }
14129  
14130  /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)14131  ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14132    Expr *CalleeExpr = E->getCallee();
14133  
14134    enum FnKind {
14135      FK_MemberFunction,
14136      FK_FunctionPointer,
14137      FK_BlockPointer
14138    };
14139  
14140    FnKind Kind;
14141    QualType CalleeType = CalleeExpr->getType();
14142    if (CalleeType == S.Context.BoundMemberTy) {
14143      assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14144      Kind = FK_MemberFunction;
14145      CalleeType = Expr::findBoundMemberType(CalleeExpr);
14146    } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14147      CalleeType = Ptr->getPointeeType();
14148      Kind = FK_FunctionPointer;
14149    } else {
14150      CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14151      Kind = FK_BlockPointer;
14152    }
14153    const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14154  
14155    // Verify that this is a legal result type of a function.
14156    if (DestType->isArrayType() || DestType->isFunctionType()) {
14157      unsigned diagID = diag::err_func_returning_array_function;
14158      if (Kind == FK_BlockPointer)
14159        diagID = diag::err_block_returning_array_function;
14160  
14161      S.Diag(E->getExprLoc(), diagID)
14162        << DestType->isFunctionType() << DestType;
14163      return ExprError();
14164    }
14165  
14166    // Otherwise, go ahead and set DestType as the call's result.
14167    E->setType(DestType.getNonLValueExprType(S.Context));
14168    E->setValueKind(Expr::getValueKindForType(DestType));
14169    assert(E->getObjectKind() == OK_Ordinary);
14170  
14171    // Rebuild the function type, replacing the result type with DestType.
14172    const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14173    if (Proto) {
14174      // __unknown_anytype(...) is a special case used by the debugger when
14175      // it has no idea what a function's signature is.
14176      //
14177      // We want to build this call essentially under the K&R
14178      // unprototyped rules, but making a FunctionNoProtoType in C++
14179      // would foul up all sorts of assumptions.  However, we cannot
14180      // simply pass all arguments as variadic arguments, nor can we
14181      // portably just call the function under a non-variadic type; see
14182      // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14183      // However, it turns out that in practice it is generally safe to
14184      // call a function declared as "A foo(B,C,D);" under the prototype
14185      // "A foo(B,C,D,...);".  The only known exception is with the
14186      // Windows ABI, where any variadic function is implicitly cdecl
14187      // regardless of its normal CC.  Therefore we change the parameter
14188      // types to match the types of the arguments.
14189      //
14190      // This is a hack, but it is far superior to moving the
14191      // corresponding target-specific code from IR-gen to Sema/AST.
14192  
14193      ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14194      SmallVector<QualType, 8> ArgTypes;
14195      if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14196        ArgTypes.reserve(E->getNumArgs());
14197        for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14198          Expr *Arg = E->getArg(i);
14199          QualType ArgType = Arg->getType();
14200          if (E->isLValue()) {
14201            ArgType = S.Context.getLValueReferenceType(ArgType);
14202          } else if (E->isXValue()) {
14203            ArgType = S.Context.getRValueReferenceType(ArgType);
14204          }
14205          ArgTypes.push_back(ArgType);
14206        }
14207        ParamTypes = ArgTypes;
14208      }
14209      DestType = S.Context.getFunctionType(DestType, ParamTypes,
14210                                           Proto->getExtProtoInfo());
14211    } else {
14212      DestType = S.Context.getFunctionNoProtoType(DestType,
14213                                                  FnType->getExtInfo());
14214    }
14215  
14216    // Rebuild the appropriate pointer-to-function type.
14217    switch (Kind) {
14218    case FK_MemberFunction:
14219      // Nothing to do.
14220      break;
14221  
14222    case FK_FunctionPointer:
14223      DestType = S.Context.getPointerType(DestType);
14224      break;
14225  
14226    case FK_BlockPointer:
14227      DestType = S.Context.getBlockPointerType(DestType);
14228      break;
14229    }
14230  
14231    // Finally, we can recurse.
14232    ExprResult CalleeResult = Visit(CalleeExpr);
14233    if (!CalleeResult.isUsable()) return ExprError();
14234    E->setCallee(CalleeResult.get());
14235  
14236    // Bind a temporary if necessary.
14237    return S.MaybeBindToTemporary(E);
14238  }
14239  
VisitObjCMessageExpr(ObjCMessageExpr * E)14240  ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14241    // Verify that this is a legal result type of a call.
14242    if (DestType->isArrayType() || DestType->isFunctionType()) {
14243      S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14244        << DestType->isFunctionType() << DestType;
14245      return ExprError();
14246    }
14247  
14248    // Rewrite the method result type if available.
14249    if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14250      assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14251      Method->setReturnType(DestType);
14252    }
14253  
14254    // Change the type of the message.
14255    E->setType(DestType.getNonReferenceType());
14256    E->setValueKind(Expr::getValueKindForType(DestType));
14257  
14258    return S.MaybeBindToTemporary(E);
14259  }
14260  
VisitImplicitCastExpr(ImplicitCastExpr * E)14261  ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14262    // The only case we should ever see here is a function-to-pointer decay.
14263    if (E->getCastKind() == CK_FunctionToPointerDecay) {
14264      assert(E->getValueKind() == VK_RValue);
14265      assert(E->getObjectKind() == OK_Ordinary);
14266  
14267      E->setType(DestType);
14268  
14269      // Rebuild the sub-expression as the pointee (function) type.
14270      DestType = DestType->castAs<PointerType>()->getPointeeType();
14271  
14272      ExprResult Result = Visit(E->getSubExpr());
14273      if (!Result.isUsable()) return ExprError();
14274  
14275      E->setSubExpr(Result.get());
14276      return E;
14277    } else if (E->getCastKind() == CK_LValueToRValue) {
14278      assert(E->getValueKind() == VK_RValue);
14279      assert(E->getObjectKind() == OK_Ordinary);
14280  
14281      assert(isa<BlockPointerType>(E->getType()));
14282  
14283      E->setType(DestType);
14284  
14285      // The sub-expression has to be a lvalue reference, so rebuild it as such.
14286      DestType = S.Context.getLValueReferenceType(DestType);
14287  
14288      ExprResult Result = Visit(E->getSubExpr());
14289      if (!Result.isUsable()) return ExprError();
14290  
14291      E->setSubExpr(Result.get());
14292      return E;
14293    } else {
14294      llvm_unreachable("Unhandled cast type!");
14295    }
14296  }
14297  
resolveDecl(Expr * E,ValueDecl * VD)14298  ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14299    ExprValueKind ValueKind = VK_LValue;
14300    QualType Type = DestType;
14301  
14302    // We know how to make this work for certain kinds of decls:
14303  
14304    //  - functions
14305    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14306      if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14307        DestType = Ptr->getPointeeType();
14308        ExprResult Result = resolveDecl(E, VD);
14309        if (Result.isInvalid()) return ExprError();
14310        return S.ImpCastExprToType(Result.get(), Type,
14311                                   CK_FunctionToPointerDecay, VK_RValue);
14312      }
14313  
14314      if (!Type->isFunctionType()) {
14315        S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14316          << VD << E->getSourceRange();
14317        return ExprError();
14318      }
14319      if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14320        // We must match the FunctionDecl's type to the hack introduced in
14321        // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14322        // type. See the lengthy commentary in that routine.
14323        QualType FDT = FD->getType();
14324        const FunctionType *FnType = FDT->castAs<FunctionType>();
14325        const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14326        DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14327        if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14328          SourceLocation Loc = FD->getLocation();
14329          FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14330                                        FD->getDeclContext(),
14331                                        Loc, Loc, FD->getNameInfo().getName(),
14332                                        DestType, FD->getTypeSourceInfo(),
14333                                        SC_None, false/*isInlineSpecified*/,
14334                                        FD->hasPrototype(),
14335                                        false/*isConstexprSpecified*/);
14336  
14337          if (FD->getQualifier())
14338            NewFD->setQualifierInfo(FD->getQualifierLoc());
14339  
14340          SmallVector<ParmVarDecl*, 16> Params;
14341          for (const auto &AI : FT->param_types()) {
14342            ParmVarDecl *Param =
14343              S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14344            Param->setScopeInfo(0, Params.size());
14345            Params.push_back(Param);
14346          }
14347          NewFD->setParams(Params);
14348          DRE->setDecl(NewFD);
14349          VD = DRE->getDecl();
14350        }
14351      }
14352  
14353      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14354        if (MD->isInstance()) {
14355          ValueKind = VK_RValue;
14356          Type = S.Context.BoundMemberTy;
14357        }
14358  
14359      // Function references aren't l-values in C.
14360      if (!S.getLangOpts().CPlusPlus)
14361        ValueKind = VK_RValue;
14362  
14363    //  - variables
14364    } else if (isa<VarDecl>(VD)) {
14365      if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14366        Type = RefTy->getPointeeType();
14367      } else if (Type->isFunctionType()) {
14368        S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14369          << VD << E->getSourceRange();
14370        return ExprError();
14371      }
14372  
14373    //  - nothing else
14374    } else {
14375      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14376        << VD << E->getSourceRange();
14377      return ExprError();
14378    }
14379  
14380    // Modifying the declaration like this is friendly to IR-gen but
14381    // also really dangerous.
14382    VD->setType(DestType);
14383    E->setType(Type);
14384    E->setValueKind(ValueKind);
14385    return E;
14386  }
14387  
14388  /// Check a cast of an unknown-any type.  We intentionally only
14389  /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)14390  ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14391                                       Expr *CastExpr, CastKind &CastKind,
14392                                       ExprValueKind &VK, CXXCastPath &Path) {
14393    // Rewrite the casted expression from scratch.
14394    ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14395    if (!result.isUsable()) return ExprError();
14396  
14397    CastExpr = result.get();
14398    VK = CastExpr->getValueKind();
14399    CastKind = CK_NoOp;
14400  
14401    return CastExpr;
14402  }
14403  
forceUnknownAnyToType(Expr * E,QualType ToType)14404  ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14405    return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14406  }
14407  
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)14408  ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14409                                      Expr *arg, QualType &paramType) {
14410    // If the syntactic form of the argument is not an explicit cast of
14411    // any sort, just do default argument promotion.
14412    ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14413    if (!castArg) {
14414      ExprResult result = DefaultArgumentPromotion(arg);
14415      if (result.isInvalid()) return ExprError();
14416      paramType = result.get()->getType();
14417      return result;
14418    }
14419  
14420    // Otherwise, use the type that was written in the explicit cast.
14421    assert(!arg->hasPlaceholderType());
14422    paramType = castArg->getTypeAsWritten();
14423  
14424    // Copy-initialize a parameter of that type.
14425    InitializedEntity entity =
14426      InitializedEntity::InitializeParameter(Context, paramType,
14427                                             /*consumed*/ false);
14428    return PerformCopyInitialization(entity, callLoc, arg);
14429  }
14430  
diagnoseUnknownAnyExpr(Sema & S,Expr * E)14431  static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14432    Expr *orig = E;
14433    unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14434    while (true) {
14435      E = E->IgnoreParenImpCasts();
14436      if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14437        E = call->getCallee();
14438        diagID = diag::err_uncasted_call_of_unknown_any;
14439      } else {
14440        break;
14441      }
14442    }
14443  
14444    SourceLocation loc;
14445    NamedDecl *d;
14446    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14447      loc = ref->getLocation();
14448      d = ref->getDecl();
14449    } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14450      loc = mem->getMemberLoc();
14451      d = mem->getMemberDecl();
14452    } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14453      diagID = diag::err_uncasted_call_of_unknown_any;
14454      loc = msg->getSelectorStartLoc();
14455      d = msg->getMethodDecl();
14456      if (!d) {
14457        S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14458          << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14459          << orig->getSourceRange();
14460        return ExprError();
14461      }
14462    } else {
14463      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14464        << E->getSourceRange();
14465      return ExprError();
14466    }
14467  
14468    S.Diag(loc, diagID) << d << orig->getSourceRange();
14469  
14470    // Never recoverable.
14471    return ExprError();
14472  }
14473  
14474  /// Check for operands with placeholder types and complain if found.
14475  /// Returns true if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)14476  ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14477    if (!getLangOpts().CPlusPlus) {
14478      // C cannot handle TypoExpr nodes on either side of a binop because it
14479      // doesn't handle dependent types properly, so make sure any TypoExprs have
14480      // been dealt with before checking the operands.
14481      ExprResult Result = CorrectDelayedTyposInExpr(E);
14482      if (!Result.isUsable()) return ExprError();
14483      E = Result.get();
14484    }
14485  
14486    const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14487    if (!placeholderType) return E;
14488  
14489    switch (placeholderType->getKind()) {
14490  
14491    // Overloaded expressions.
14492    case BuiltinType::Overload: {
14493      // Try to resolve a single function template specialization.
14494      // This is obligatory.
14495      ExprResult result = E;
14496      if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14497        return result;
14498  
14499      // If that failed, try to recover with a call.
14500      } else {
14501        tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14502                             /*complain*/ true);
14503        return result;
14504      }
14505    }
14506  
14507    // Bound member functions.
14508    case BuiltinType::BoundMember: {
14509      ExprResult result = E;
14510      const Expr *BME = E->IgnoreParens();
14511      PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14512      // Try to give a nicer diagnostic if it is a bound member that we recognize.
14513      if (isa<CXXPseudoDestructorExpr>(BME)) {
14514        PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14515      } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14516        if (ME->getMemberNameInfo().getName().getNameKind() ==
14517            DeclarationName::CXXDestructorName)
14518          PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14519      }
14520      tryToRecoverWithCall(result, PD,
14521                           /*complain*/ true);
14522      return result;
14523    }
14524  
14525    // ARC unbridged casts.
14526    case BuiltinType::ARCUnbridgedCast: {
14527      Expr *realCast = stripARCUnbridgedCast(E);
14528      diagnoseARCUnbridgedCast(realCast);
14529      return realCast;
14530    }
14531  
14532    // Expressions of unknown type.
14533    case BuiltinType::UnknownAny:
14534      return diagnoseUnknownAnyExpr(*this, E);
14535  
14536    // Pseudo-objects.
14537    case BuiltinType::PseudoObject:
14538      return checkPseudoObjectRValue(E);
14539  
14540    case BuiltinType::BuiltinFn: {
14541      // Accept __noop without parens by implicitly converting it to a call expr.
14542      auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14543      if (DRE) {
14544        auto *FD = cast<FunctionDecl>(DRE->getDecl());
14545        if (FD->getBuiltinID() == Builtin::BI__noop) {
14546          E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14547                                CK_BuiltinFnToFnPtr).get();
14548          return new (Context) CallExpr(Context, E, None, Context.IntTy,
14549                                        VK_RValue, SourceLocation());
14550        }
14551      }
14552  
14553      Diag(E->getLocStart(), diag::err_builtin_fn_use);
14554      return ExprError();
14555    }
14556  
14557    // Expressions of unknown type.
14558    case BuiltinType::OMPArraySection:
14559      Diag(E->getLocStart(), diag::err_omp_array_section_use);
14560      return ExprError();
14561  
14562    // Everything else should be impossible.
14563  #define BUILTIN_TYPE(Id, SingletonId) \
14564    case BuiltinType::Id:
14565  #define PLACEHOLDER_TYPE(Id, SingletonId)
14566  #include "clang/AST/BuiltinTypes.def"
14567      break;
14568    }
14569  
14570    llvm_unreachable("invalid placeholder type!");
14571  }
14572  
CheckCaseExpression(Expr * E)14573  bool Sema::CheckCaseExpression(Expr *E) {
14574    if (E->isTypeDependent())
14575      return true;
14576    if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14577      return E->getType()->isIntegralOrEnumerationType();
14578    return false;
14579  }
14580  
14581  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14582  ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)14583  Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14584    assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14585           "Unknown Objective-C Boolean value!");
14586    QualType BoolT = Context.ObjCBuiltinBoolTy;
14587    if (!Context.getBOOLDecl()) {
14588      LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14589                          Sema::LookupOrdinaryName);
14590      if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14591        NamedDecl *ND = Result.getFoundDecl();
14592        if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14593          Context.setBOOLDecl(TD);
14594      }
14595    }
14596    if (Context.getBOOLDecl())
14597      BoolT = Context.getBOOLType();
14598    return new (Context)
14599        ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14600  }
14601