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/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/AnalysisBasedWarnings.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/DelayedDiagnostic.h"
36#include "clang/Sema/Designator.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/SemaFixItUtils.h"
43#include "clang/Sema/Template.h"
44using namespace clang;
45using namespace sema;
46
47/// \brief Determine whether the use of this declaration is valid, without
48/// emitting diagnostics.
49bool Sema::CanUseDecl(NamedDecl *D) {
50  // See if this is an auto-typed variable whose initializer we are parsing.
51  if (ParsingInitForAutoVars.count(D))
52    return false;
53
54  // See if this is a deleted function.
55  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56    if (FD->isDeleted())
57      return false;
58  }
59
60  // See if this function is unavailable.
61  if (D->getAvailability() == AR_Unavailable &&
62      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
63    return false;
64
65  return true;
66}
67
68static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69  // Warn if this is used but marked unused.
70  if (D->hasAttr<UnusedAttr>()) {
71    const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
72    if (!DC->hasAttr<UnusedAttr>())
73      S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
74  }
75}
76
77static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
78                              NamedDecl *D, SourceLocation Loc,
79                              const ObjCInterfaceDecl *UnknownObjCClass) {
80  // See if this declaration is unavailable or deprecated.
81  std::string Message;
82  AvailabilityResult Result = D->getAvailability(&Message);
83  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84    if (Result == AR_Available) {
85      const DeclContext *DC = ECD->getDeclContext();
86      if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87        Result = TheEnumDecl->getAvailability(&Message);
88    }
89
90  const ObjCPropertyDecl *ObjCPDecl = 0;
91  if (Result == AR_Deprecated || Result == AR_Unavailable) {
92    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93      if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94        AvailabilityResult PDeclResult = PD->getAvailability(0);
95        if (PDeclResult == Result)
96          ObjCPDecl = PD;
97      }
98    }
99  }
100
101  switch (Result) {
102    case AR_Available:
103    case AR_NotYetIntroduced:
104      break;
105
106    case AR_Deprecated:
107      S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
108      break;
109
110    case AR_Unavailable:
111      if (S.getCurContextAvailability() != AR_Unavailable) {
112        if (Message.empty()) {
113          if (!UnknownObjCClass) {
114            S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
115            if (ObjCPDecl)
116              S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117                << ObjCPDecl->getDeclName() << 1;
118          }
119          else
120            S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
121              << D->getDeclName();
122        }
123        else
124          S.Diag(Loc, diag::err_unavailable_message)
125            << D->getDeclName() << Message;
126        S.Diag(D->getLocation(), diag::note_unavailable_here)
127                  << isa<FunctionDecl>(D) << false;
128        if (ObjCPDecl)
129          S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130          << ObjCPDecl->getDeclName() << 1;
131      }
132      break;
133    }
134    return Result;
135}
136
137/// \brief Emit a note explaining that this function is deleted or unavailable.
138void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
140
141  if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142    // If the method was explicitly defaulted, point at that declaration.
143    if (!Method->isImplicit())
144      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
145
146    // Try to diagnose why this special member function was implicitly
147    // deleted. This might fail, if that reason no longer applies.
148    CXXSpecialMember CSM = getSpecialMember(Method);
149    if (CSM != CXXInvalid)
150      ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
151
152    return;
153  }
154
155  Diag(Decl->getLocation(), diag::note_unavailable_here)
156    << 1 << Decl->isDeleted();
157}
158
159/// \brief Determine whether a FunctionDecl was ever declared with an
160/// explicit storage class.
161static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162  for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163                                     E = D->redecls_end();
164       I != E; ++I) {
165    if (I->getStorageClassAsWritten() != SC_None)
166      return true;
167  }
168  return false;
169}
170
171/// \brief Check whether we're in an extern inline function and referring to a
172/// variable or function with internal linkage (C11 6.7.4p3).
173///
174/// This is only a warning because we used to silently accept this code, but
175/// in many cases it will not behave correctly. This is not enabled in C++ mode
176/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177/// and so while there may still be user mistakes, most of the time we can't
178/// prove that there are errors.
179static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
180                                                      const NamedDecl *D,
181                                                      SourceLocation Loc) {
182  // This is disabled under C++; there are too many ways for this to fire in
183  // contexts where the warning is a false positive, or where it is technically
184  // correct but benign.
185  if (S.getLangOpts().CPlusPlus)
186    return;
187
188  // Check if this is an inlined function or method.
189  FunctionDecl *Current = S.getCurFunctionDecl();
190  if (!Current)
191    return;
192  if (!Current->isInlined())
193    return;
194  if (Current->getLinkage() != ExternalLinkage)
195    return;
196
197  // Check if the decl has internal linkage.
198  if (D->getLinkage() != InternalLinkage)
199    return;
200
201  // Downgrade from ExtWarn to Extension if
202  //  (1) the supposedly external inline function is in the main file,
203  //      and probably won't be included anywhere else.
204  //  (2) the thing we're referencing is a pure function.
205  //  (3) the thing we're referencing is another inline function.
206  // This last can give us false negatives, but it's better than warning on
207  // wrappers for simple C library functions.
208  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209  bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210  if (!DowngradeWarning && UsedFn)
211    DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
212
213  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214                               : diag::warn_internal_in_extern_inline)
215    << /*IsVar=*/!UsedFn << D;
216
217  // Suggest "static" on the inline function, if possible.
218  if (!hasAnyExplicitStorageClass(Current)) {
219    const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
220    SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
221    S.Diag(DeclBegin, diag::note_convert_inline_to_static)
222      << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
223  }
224
225  S.Diag(D->getCanonicalDecl()->getLocation(),
226         diag::note_internal_decl_declared_here)
227    << D;
228}
229
230/// \brief Determine whether the use of this declaration is valid, and
231/// emit any corresponding diagnostics.
232///
233/// This routine diagnoses various problems with referencing
234/// declarations that can occur when using a declaration. For example,
235/// it might warn if a deprecated or unavailable declaration is being
236/// used, or produce an error (and return true) if a C++0x deleted
237/// function is being used.
238///
239/// \returns true if there was an error (this declaration cannot be
240/// referenced), false otherwise.
241///
242bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
243                             const ObjCInterfaceDecl *UnknownObjCClass) {
244  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
245    // If there were any diagnostics suppressed by template argument deduction,
246    // emit them now.
247    llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
248      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
249    if (Pos != SuppressedDiagnostics.end()) {
250      SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
251      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
252        Diag(Suppressed[I].first, Suppressed[I].second);
253
254      // Clear out the list of suppressed diagnostics, so that we don't emit
255      // them again for this specialization. However, we don't obsolete this
256      // entry from the table, because we want to avoid ever emitting these
257      // diagnostics again.
258      Suppressed.clear();
259    }
260  }
261
262  // See if this is an auto-typed variable whose initializer we are parsing.
263  if (ParsingInitForAutoVars.count(D)) {
264    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265      << D->getDeclName();
266    return true;
267  }
268
269  // See if this is a deleted function.
270  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271    if (FD->isDeleted()) {
272      Diag(Loc, diag::err_deleted_function_use);
273      NoteDeletedFunction(FD);
274      return true;
275    }
276  }
277  DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
278
279  DiagnoseUnusedOfDecl(*this, D, Loc);
280
281  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
282
283  return false;
284}
285
286/// \brief Retrieve the message suffix that should be added to a
287/// diagnostic complaining about the given function being deleted or
288/// unavailable.
289std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
290  std::string Message;
291  if (FD->getAvailability(&Message))
292    return ": " + Message;
293
294  return std::string();
295}
296
297/// DiagnoseSentinelCalls - This routine checks whether a call or
298/// message-send is to a declaration with the sentinel attribute, and
299/// if so, it checks that the requirements of the sentinel are
300/// satisfied.
301void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
302                                 Expr **args, unsigned numArgs) {
303  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
304  if (!attr)
305    return;
306
307  // The number of formal parameters of the declaration.
308  unsigned numFormalParams;
309
310  // The kind of declaration.  This is also an index into a %select in
311  // the diagnostic.
312  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
313
314  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
315    numFormalParams = MD->param_size();
316    calleeType = CT_Method;
317  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
318    numFormalParams = FD->param_size();
319    calleeType = CT_Function;
320  } else if (isa<VarDecl>(D)) {
321    QualType type = cast<ValueDecl>(D)->getType();
322    const FunctionType *fn = 0;
323    if (const PointerType *ptr = type->getAs<PointerType>()) {
324      fn = ptr->getPointeeType()->getAs<FunctionType>();
325      if (!fn) return;
326      calleeType = CT_Function;
327    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
328      fn = ptr->getPointeeType()->castAs<FunctionType>();
329      calleeType = CT_Block;
330    } else {
331      return;
332    }
333
334    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
335      numFormalParams = proto->getNumArgs();
336    } else {
337      numFormalParams = 0;
338    }
339  } else {
340    return;
341  }
342
343  // "nullPos" is the number of formal parameters at the end which
344  // effectively count as part of the variadic arguments.  This is
345  // useful if you would prefer to not have *any* formal parameters,
346  // but the language forces you to have at least one.
347  unsigned nullPos = attr->getNullPos();
348  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
349  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
350
351  // The number of arguments which should follow the sentinel.
352  unsigned numArgsAfterSentinel = attr->getSentinel();
353
354  // If there aren't enough arguments for all the formal parameters,
355  // the sentinel, and the args after the sentinel, complain.
356  if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
357    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
358    Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
359    return;
360  }
361
362  // Otherwise, find the sentinel expression.
363  Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
364  if (!sentinelExpr) return;
365  if (sentinelExpr->isValueDependent()) return;
366  if (Context.isSentinelNullExpr(sentinelExpr)) return;
367
368  // Pick a reasonable string to insert.  Optimistically use 'nil' or
369  // 'NULL' if those are actually defined in the context.  Only use
370  // 'nil' for ObjC methods, where it's much more likely that the
371  // variadic arguments form a list of object pointers.
372  SourceLocation MissingNilLoc
373    = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
374  std::string NullValue;
375  if (calleeType == CT_Method &&
376      PP.getIdentifierInfo("nil")->hasMacroDefinition())
377    NullValue = "nil";
378  else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
379    NullValue = "NULL";
380  else
381    NullValue = "(void*) 0";
382
383  if (MissingNilLoc.isInvalid())
384    Diag(Loc, diag::warn_missing_sentinel) << calleeType;
385  else
386    Diag(MissingNilLoc, diag::warn_missing_sentinel)
387      << calleeType
388      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
389  Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
390}
391
392SourceRange Sema::getExprRange(Expr *E) const {
393  return E ? E->getSourceRange() : SourceRange();
394}
395
396//===----------------------------------------------------------------------===//
397//  Standard Promotions and Conversions
398//===----------------------------------------------------------------------===//
399
400/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
401ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
402  // Handle any placeholder expressions which made it here.
403  if (E->getType()->isPlaceholderType()) {
404    ExprResult result = CheckPlaceholderExpr(E);
405    if (result.isInvalid()) return ExprError();
406    E = result.take();
407  }
408
409  QualType Ty = E->getType();
410  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
411
412  if (Ty->isFunctionType())
413    E = ImpCastExprToType(E, Context.getPointerType(Ty),
414                          CK_FunctionToPointerDecay).take();
415  else if (Ty->isArrayType()) {
416    // In C90 mode, arrays only promote to pointers if the array expression is
417    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
418    // type 'array of type' is converted to an expression that has type 'pointer
419    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
420    // that has type 'array of type' ...".  The relevant change is "an lvalue"
421    // (C90) to "an expression" (C99).
422    //
423    // C++ 4.2p1:
424    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
425    // T" can be converted to an rvalue of type "pointer to T".
426    //
427    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
428      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
429                            CK_ArrayToPointerDecay).take();
430  }
431  return Owned(E);
432}
433
434static void CheckForNullPointerDereference(Sema &S, Expr *E) {
435  // Check to see if we are dereferencing a null pointer.  If so,
436  // and if not volatile-qualified, this is undefined behavior that the
437  // optimizer will delete, so warn about it.  People sometimes try to use this
438  // to get a deterministic trap and are surprised by clang's behavior.  This
439  // only handles the pattern "*null", which is a very syntactic check.
440  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
441    if (UO->getOpcode() == UO_Deref &&
442        UO->getSubExpr()->IgnoreParenCasts()->
443          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
444        !UO->getType().isVolatileQualified()) {
445    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
446                          S.PDiag(diag::warn_indirection_through_null)
447                            << UO->getSubExpr()->getSourceRange());
448    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449                        S.PDiag(diag::note_indirection_through_null));
450  }
451}
452
453ExprResult Sema::DefaultLvalueConversion(Expr *E) {
454  // Handle any placeholder expressions which made it here.
455  if (E->getType()->isPlaceholderType()) {
456    ExprResult result = CheckPlaceholderExpr(E);
457    if (result.isInvalid()) return ExprError();
458    E = result.take();
459  }
460
461  // C++ [conv.lval]p1:
462  //   A glvalue of a non-function, non-array type T can be
463  //   converted to a prvalue.
464  if (!E->isGLValue()) return Owned(E);
465
466  QualType T = E->getType();
467  assert(!T.isNull() && "r-value conversion on typeless expression?");
468
469  // We don't want to throw lvalue-to-rvalue casts on top of
470  // expressions of certain types in C++.
471  if (getLangOpts().CPlusPlus &&
472      (E->getType() == Context.OverloadTy ||
473       T->isDependentType() ||
474       T->isRecordType()))
475    return Owned(E);
476
477  // The C standard is actually really unclear on this point, and
478  // DR106 tells us what the result should be but not why.  It's
479  // generally best to say that void types just doesn't undergo
480  // lvalue-to-rvalue at all.  Note that expressions of unqualified
481  // 'void' type are never l-values, but qualified void can be.
482  if (T->isVoidType())
483    return Owned(E);
484
485  // OpenCL usually rejects direct accesses to values of 'half' type.
486  if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
487      T->isHalfType()) {
488    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
489      << 0 << T;
490    return ExprError();
491  }
492
493  CheckForNullPointerDereference(*this, E);
494
495  // C++ [conv.lval]p1:
496  //   [...] If T is a non-class type, the type of the prvalue is the
497  //   cv-unqualified version of T. Otherwise, the type of the
498  //   rvalue is T.
499  //
500  // C99 6.3.2.1p2:
501  //   If the lvalue has qualified type, the value has the unqualified
502  //   version of the type of the lvalue; otherwise, the value has the
503  //   type of the lvalue.
504  if (T.hasQualifiers())
505    T = T.getUnqualifiedType();
506
507  UpdateMarkingForLValueToRValue(E);
508
509  // Loading a __weak object implicitly retains the value, so we need a cleanup to
510  // balance that.
511  if (getLangOpts().ObjCAutoRefCount &&
512      E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
513    ExprNeedsCleanups = true;
514
515  ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
516                                                  E, 0, VK_RValue));
517
518  // C11 6.3.2.1p2:
519  //   ... if the lvalue has atomic type, the value has the non-atomic version
520  //   of the type of the lvalue ...
521  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
522    T = Atomic->getValueType().getUnqualifiedType();
523    Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
524                                         Res.get(), 0, VK_RValue));
525  }
526
527  return Res;
528}
529
530ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
531  ExprResult Res = DefaultFunctionArrayConversion(E);
532  if (Res.isInvalid())
533    return ExprError();
534  Res = DefaultLvalueConversion(Res.take());
535  if (Res.isInvalid())
536    return ExprError();
537  return Res;
538}
539
540
541/// UsualUnaryConversions - Performs various conversions that are common to most
542/// operators (C99 6.3). The conversions of array and function types are
543/// sometimes suppressed. For example, the array->pointer conversion doesn't
544/// apply if the array is an argument to the sizeof or address (&) operators.
545/// In these instances, this routine should *not* be called.
546ExprResult Sema::UsualUnaryConversions(Expr *E) {
547  // First, convert to an r-value.
548  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
549  if (Res.isInvalid())
550    return ExprError();
551  E = Res.take();
552
553  QualType Ty = E->getType();
554  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
555
556  // Half FP have to be promoted to float unless it is natively supported
557  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
558    return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
559
560  // Try to perform integral promotions if the object has a theoretically
561  // promotable type.
562  if (Ty->isIntegralOrUnscopedEnumerationType()) {
563    // C99 6.3.1.1p2:
564    //
565    //   The following may be used in an expression wherever an int or
566    //   unsigned int may be used:
567    //     - an object or expression with an integer type whose integer
568    //       conversion rank is less than or equal to the rank of int
569    //       and unsigned int.
570    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
571    //
572    //   If an int can represent all values of the original type, the
573    //   value is converted to an int; otherwise, it is converted to an
574    //   unsigned int. These are called the integer promotions. All
575    //   other types are unchanged by the integer promotions.
576
577    QualType PTy = Context.isPromotableBitField(E);
578    if (!PTy.isNull()) {
579      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
580      return Owned(E);
581    }
582    if (Ty->isPromotableIntegerType()) {
583      QualType PT = Context.getPromotedIntegerType(Ty);
584      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
585      return Owned(E);
586    }
587  }
588  return Owned(E);
589}
590
591/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
592/// do not have a prototype. Arguments that have type float or __fp16
593/// are promoted to double. All other argument types are converted by
594/// UsualUnaryConversions().
595ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
596  QualType Ty = E->getType();
597  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
598
599  ExprResult Res = UsualUnaryConversions(E);
600  if (Res.isInvalid())
601    return ExprError();
602  E = Res.take();
603
604  // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
605  // double.
606  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
607  if (BTy && (BTy->getKind() == BuiltinType::Half ||
608              BTy->getKind() == BuiltinType::Float))
609    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
610
611  // C++ performs lvalue-to-rvalue conversion as a default argument
612  // promotion, even on class types, but note:
613  //   C++11 [conv.lval]p2:
614  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
615  //     operand or a subexpression thereof the value contained in the
616  //     referenced object is not accessed. Otherwise, if the glvalue
617  //     has a class type, the conversion copy-initializes a temporary
618  //     of type T from the glvalue and the result of the conversion
619  //     is a prvalue for the temporary.
620  // FIXME: add some way to gate this entire thing for correctness in
621  // potentially potentially evaluated contexts.
622  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
623    ExprResult Temp = PerformCopyInitialization(
624                       InitializedEntity::InitializeTemporary(E->getType()),
625                                                E->getExprLoc(),
626                                                Owned(E));
627    if (Temp.isInvalid())
628      return ExprError();
629    E = Temp.get();
630  }
631
632  return Owned(E);
633}
634
635/// Determine the degree of POD-ness for an expression.
636/// Incomplete types are considered POD, since this check can be performed
637/// when we're in an unevaluated context.
638Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
639  if (Ty->isIncompleteType()) {
640    if (Ty->isObjCObjectType())
641      return VAK_Invalid;
642    return VAK_Valid;
643  }
644
645  if (Ty.isCXX98PODType(Context))
646    return VAK_Valid;
647
648  // C++11 [expr.call]p7:
649  //   Passing a potentially-evaluated argument of class type (Clause 9)
650  //   having a non-trivial copy constructor, a non-trivial move constructor,
651  //   or a non-trivial destructor, with no corresponding parameter,
652  //   is conditionally-supported with implementation-defined semantics.
653  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
654    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
655      if (!Record->hasNonTrivialCopyConstructor() &&
656          !Record->hasNonTrivialMoveConstructor() &&
657          !Record->hasNonTrivialDestructor())
658        return VAK_ValidInCXX11;
659
660  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
661    return VAK_Valid;
662  return VAK_Invalid;
663}
664
665bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
666  // Don't allow one to pass an Objective-C interface to a vararg.
667  const QualType & Ty = E->getType();
668
669  // Complain about passing non-POD types through varargs.
670  switch (isValidVarArgType(Ty)) {
671  case VAK_Valid:
672    break;
673  case VAK_ValidInCXX11:
674    DiagRuntimeBehavior(E->getLocStart(), 0,
675        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
676        << E->getType() << CT);
677    break;
678  case VAK_Invalid: {
679    if (Ty->isObjCObjectType())
680      return DiagRuntimeBehavior(E->getLocStart(), 0,
681                          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
682                            << Ty << CT);
683
684    return DiagRuntimeBehavior(E->getLocStart(), 0,
685                   PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
686                   << getLangOpts().CPlusPlus11 << Ty << CT);
687  }
688  }
689  // c++ rules are enforced elsewhere.
690  return false;
691}
692
693/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
694/// will create a trap if the resulting type is not a POD type.
695ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
696                                                  FunctionDecl *FDecl) {
697  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
698    // Strip the unbridged-cast placeholder expression off, if applicable.
699    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
700        (CT == VariadicMethod ||
701         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
702      E = stripARCUnbridgedCast(E);
703
704    // Otherwise, do normal placeholder checking.
705    } else {
706      ExprResult ExprRes = CheckPlaceholderExpr(E);
707      if (ExprRes.isInvalid())
708        return ExprError();
709      E = ExprRes.take();
710    }
711  }
712
713  ExprResult ExprRes = DefaultArgumentPromotion(E);
714  if (ExprRes.isInvalid())
715    return ExprError();
716  E = ExprRes.take();
717
718  // Diagnostics regarding non-POD argument types are
719  // emitted along with format string checking in Sema::CheckFunctionCall().
720  if (isValidVarArgType(E->getType()) == VAK_Invalid) {
721    // Turn this into a trap.
722    CXXScopeSpec SS;
723    SourceLocation TemplateKWLoc;
724    UnqualifiedId Name;
725    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
726                       E->getLocStart());
727    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
728                                          Name, true, false);
729    if (TrapFn.isInvalid())
730      return ExprError();
731
732    ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
733                                    E->getLocStart(), MultiExprArg(),
734                                    E->getLocEnd());
735    if (Call.isInvalid())
736      return ExprError();
737
738    ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
739                                  Call.get(), E);
740    if (Comma.isInvalid())
741      return ExprError();
742    return Comma.get();
743  }
744
745  if (!getLangOpts().CPlusPlus &&
746      RequireCompleteType(E->getExprLoc(), E->getType(),
747                          diag::err_call_incomplete_argument))
748    return ExprError();
749
750  return Owned(E);
751}
752
753/// \brief Converts an integer to complex float type.  Helper function of
754/// UsualArithmeticConversions()
755///
756/// \return false if the integer expression is an integer type and is
757/// successfully converted to the complex type.
758static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
759                                                  ExprResult &ComplexExpr,
760                                                  QualType IntTy,
761                                                  QualType ComplexTy,
762                                                  bool SkipCast) {
763  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
764  if (SkipCast) return false;
765  if (IntTy->isIntegerType()) {
766    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
767    IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
768    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
769                                  CK_FloatingRealToComplex);
770  } else {
771    assert(IntTy->isComplexIntegerType());
772    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
773                                  CK_IntegralComplexToFloatingComplex);
774  }
775  return false;
776}
777
778/// \brief Takes two complex float types and converts them to the same type.
779/// Helper function of UsualArithmeticConversions()
780static QualType
781handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
782                                            ExprResult &RHS, QualType LHSType,
783                                            QualType RHSType,
784                                            bool IsCompAssign) {
785  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
786
787  if (order < 0) {
788    // _Complex float -> _Complex double
789    if (!IsCompAssign)
790      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
791    return RHSType;
792  }
793  if (order > 0)
794    // _Complex float -> _Complex double
795    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
796  return LHSType;
797}
798
799/// \brief Converts otherExpr to complex float and promotes complexExpr if
800/// necessary.  Helper function of UsualArithmeticConversions()
801static QualType handleOtherComplexFloatConversion(Sema &S,
802                                                  ExprResult &ComplexExpr,
803                                                  ExprResult &OtherExpr,
804                                                  QualType ComplexTy,
805                                                  QualType OtherTy,
806                                                  bool ConvertComplexExpr,
807                                                  bool ConvertOtherExpr) {
808  int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
809
810  // If just the complexExpr is complex, the otherExpr needs to be converted,
811  // and the complexExpr might need to be promoted.
812  if (order > 0) { // complexExpr is wider
813    // float -> _Complex double
814    if (ConvertOtherExpr) {
815      QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
816      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
817      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
818                                      CK_FloatingRealToComplex);
819    }
820    return ComplexTy;
821  }
822
823  // otherTy is at least as wide.  Find its corresponding complex type.
824  QualType result = (order == 0 ? ComplexTy :
825                                  S.Context.getComplexType(OtherTy));
826
827  // double -> _Complex double
828  if (ConvertOtherExpr)
829    OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
830                                    CK_FloatingRealToComplex);
831
832  // _Complex float -> _Complex double
833  if (ConvertComplexExpr && order < 0)
834    ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
835                                      CK_FloatingComplexCast);
836
837  return result;
838}
839
840/// \brief Handle arithmetic conversion with complex types.  Helper function of
841/// UsualArithmeticConversions()
842static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
843                                             ExprResult &RHS, QualType LHSType,
844                                             QualType RHSType,
845                                             bool IsCompAssign) {
846  // if we have an integer operand, the result is the complex type.
847  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
848                                             /*skipCast*/false))
849    return LHSType;
850  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
851                                             /*skipCast*/IsCompAssign))
852    return RHSType;
853
854  // This handles complex/complex, complex/float, or float/complex.
855  // When both operands are complex, the shorter operand is converted to the
856  // type of the longer, and that is the type of the result. This corresponds
857  // to what is done when combining two real floating-point operands.
858  // The fun begins when size promotion occur across type domains.
859  // From H&S 6.3.4: When one operand is complex and the other is a real
860  // floating-point type, the less precise type is converted, within it's
861  // real or complex domain, to the precision of the other type. For example,
862  // when combining a "long double" with a "double _Complex", the
863  // "double _Complex" is promoted to "long double _Complex".
864
865  bool LHSComplexFloat = LHSType->isComplexType();
866  bool RHSComplexFloat = RHSType->isComplexType();
867
868  // If both are complex, just cast to the more precise type.
869  if (LHSComplexFloat && RHSComplexFloat)
870    return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
871                                                       LHSType, RHSType,
872                                                       IsCompAssign);
873
874  // If only one operand is complex, promote it if necessary and convert the
875  // other operand to complex.
876  if (LHSComplexFloat)
877    return handleOtherComplexFloatConversion(
878        S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
879        /*convertOtherExpr*/ true);
880
881  assert(RHSComplexFloat);
882  return handleOtherComplexFloatConversion(
883      S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
884      /*convertOtherExpr*/ !IsCompAssign);
885}
886
887/// \brief Hande arithmetic conversion from integer to float.  Helper function
888/// of UsualArithmeticConversions()
889static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
890                                           ExprResult &IntExpr,
891                                           QualType FloatTy, QualType IntTy,
892                                           bool ConvertFloat, bool ConvertInt) {
893  if (IntTy->isIntegerType()) {
894    if (ConvertInt)
895      // Convert intExpr to the lhs floating point type.
896      IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
897                                    CK_IntegralToFloating);
898    return FloatTy;
899  }
900
901  // Convert both sides to the appropriate complex float.
902  assert(IntTy->isComplexIntegerType());
903  QualType result = S.Context.getComplexType(FloatTy);
904
905  // _Complex int -> _Complex float
906  if (ConvertInt)
907    IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
908                                  CK_IntegralComplexToFloatingComplex);
909
910  // float -> _Complex float
911  if (ConvertFloat)
912    FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
913                                    CK_FloatingRealToComplex);
914
915  return result;
916}
917
918/// \brief Handle arithmethic conversion with floating point types.  Helper
919/// function of UsualArithmeticConversions()
920static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
921                                      ExprResult &RHS, QualType LHSType,
922                                      QualType RHSType, bool IsCompAssign) {
923  bool LHSFloat = LHSType->isRealFloatingType();
924  bool RHSFloat = RHSType->isRealFloatingType();
925
926  // If we have two real floating types, convert the smaller operand
927  // to the bigger result.
928  if (LHSFloat && RHSFloat) {
929    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
930    if (order > 0) {
931      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
932      return LHSType;
933    }
934
935    assert(order < 0 && "illegal float comparison");
936    if (!IsCompAssign)
937      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
938    return RHSType;
939  }
940
941  if (LHSFloat)
942    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
943                                      /*convertFloat=*/!IsCompAssign,
944                                      /*convertInt=*/ true);
945  assert(RHSFloat);
946  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
947                                    /*convertInt=*/ true,
948                                    /*convertFloat=*/!IsCompAssign);
949}
950
951typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
952
953namespace {
954/// These helper callbacks are placed in an anonymous namespace to
955/// permit their use as function template parameters.
956ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
957  return S.ImpCastExprToType(op, toType, CK_IntegralCast);
958}
959
960ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
961  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
962                             CK_IntegralComplexCast);
963}
964}
965
966/// \brief Handle integer arithmetic conversions.  Helper function of
967/// UsualArithmeticConversions()
968template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
969static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
970                                        ExprResult &RHS, QualType LHSType,
971                                        QualType RHSType, bool IsCompAssign) {
972  // The rules for this case are in C99 6.3.1.8
973  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
974  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
975  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
976  if (LHSSigned == RHSSigned) {
977    // Same signedness; use the higher-ranked type
978    if (order >= 0) {
979      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
980      return LHSType;
981    } else if (!IsCompAssign)
982      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
983    return RHSType;
984  } else if (order != (LHSSigned ? 1 : -1)) {
985    // The unsigned type has greater than or equal rank to the
986    // signed type, so use the unsigned type
987    if (RHSSigned) {
988      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
989      return LHSType;
990    } else if (!IsCompAssign)
991      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
992    return RHSType;
993  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
994    // The two types are different widths; if we are here, that
995    // means the signed type is larger than the unsigned type, so
996    // use the signed type.
997    if (LHSSigned) {
998      RHS = (*doRHSCast)(S, RHS.take(), LHSType);
999      return LHSType;
1000    } else if (!IsCompAssign)
1001      LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1002    return RHSType;
1003  } else {
1004    // The signed type is higher-ranked than the unsigned type,
1005    // but isn't actually any bigger (like unsigned int and long
1006    // on most 32-bit systems).  Use the unsigned type corresponding
1007    // to the signed type.
1008    QualType result =
1009      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1010    RHS = (*doRHSCast)(S, RHS.take(), result);
1011    if (!IsCompAssign)
1012      LHS = (*doLHSCast)(S, LHS.take(), result);
1013    return result;
1014  }
1015}
1016
1017/// \brief Handle conversions with GCC complex int extension.  Helper function
1018/// of UsualArithmeticConversions()
1019static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1020                                           ExprResult &RHS, QualType LHSType,
1021                                           QualType RHSType,
1022                                           bool IsCompAssign) {
1023  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1024  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1025
1026  if (LHSComplexInt && RHSComplexInt) {
1027    QualType LHSEltType = LHSComplexInt->getElementType();
1028    QualType RHSEltType = RHSComplexInt->getElementType();
1029    QualType ScalarType =
1030      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1031        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1032
1033    return S.Context.getComplexType(ScalarType);
1034  }
1035
1036  if (LHSComplexInt) {
1037    QualType LHSEltType = LHSComplexInt->getElementType();
1038    QualType ScalarType =
1039      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1040        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1041    QualType ComplexType = S.Context.getComplexType(ScalarType);
1042    RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1043                              CK_IntegralRealToComplex);
1044
1045    return ComplexType;
1046  }
1047
1048  assert(RHSComplexInt);
1049
1050  QualType RHSEltType = RHSComplexInt->getElementType();
1051  QualType ScalarType =
1052    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1053      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1054  QualType ComplexType = S.Context.getComplexType(ScalarType);
1055
1056  if (!IsCompAssign)
1057    LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1058                              CK_IntegralRealToComplex);
1059  return ComplexType;
1060}
1061
1062/// UsualArithmeticConversions - Performs various conversions that are common to
1063/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1064/// routine returns the first non-arithmetic type found. The client is
1065/// responsible for emitting appropriate error diagnostics.
1066QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1067                                          bool IsCompAssign) {
1068  if (!IsCompAssign) {
1069    LHS = UsualUnaryConversions(LHS.take());
1070    if (LHS.isInvalid())
1071      return QualType();
1072  }
1073
1074  RHS = UsualUnaryConversions(RHS.take());
1075  if (RHS.isInvalid())
1076    return QualType();
1077
1078  // For conversion purposes, we ignore any qualifiers.
1079  // For example, "const float" and "float" are equivalent.
1080  QualType LHSType =
1081    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1082  QualType RHSType =
1083    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1084
1085  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1086  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1087    LHSType = AtomicLHS->getValueType();
1088
1089  // If both types are identical, no conversion is needed.
1090  if (LHSType == RHSType)
1091    return LHSType;
1092
1093  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1094  // The caller can deal with this (e.g. pointer + int).
1095  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1096    return QualType();
1097
1098  // Apply unary and bitfield promotions to the LHS's type.
1099  QualType LHSUnpromotedType = LHSType;
1100  if (LHSType->isPromotableIntegerType())
1101    LHSType = Context.getPromotedIntegerType(LHSType);
1102  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1103  if (!LHSBitfieldPromoteTy.isNull())
1104    LHSType = LHSBitfieldPromoteTy;
1105  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1106    LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1107
1108  // If both types are identical, no conversion is needed.
1109  if (LHSType == RHSType)
1110    return LHSType;
1111
1112  // At this point, we have two different arithmetic types.
1113
1114  // Handle complex types first (C99 6.3.1.8p1).
1115  if (LHSType->isComplexType() || RHSType->isComplexType())
1116    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1117                                        IsCompAssign);
1118
1119  // Now handle "real" floating types (i.e. float, double, long double).
1120  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1121    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1122                                 IsCompAssign);
1123
1124  // Handle GCC complex int extension.
1125  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1126    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1127                                      IsCompAssign);
1128
1129  // Finally, we have two differing integer types.
1130  return handleIntegerConversion<doIntegralCast, doIntegralCast>
1131           (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1132}
1133
1134
1135//===----------------------------------------------------------------------===//
1136//  Semantic Analysis for various Expression Types
1137//===----------------------------------------------------------------------===//
1138
1139
1140ExprResult
1141Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1142                                SourceLocation DefaultLoc,
1143                                SourceLocation RParenLoc,
1144                                Expr *ControllingExpr,
1145                                MultiTypeArg ArgTypes,
1146                                MultiExprArg ArgExprs) {
1147  unsigned NumAssocs = ArgTypes.size();
1148  assert(NumAssocs == ArgExprs.size());
1149
1150  ParsedType *ParsedTypes = ArgTypes.data();
1151  Expr **Exprs = ArgExprs.data();
1152
1153  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1154  for (unsigned i = 0; i < NumAssocs; ++i) {
1155    if (ParsedTypes[i])
1156      (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1157    else
1158      Types[i] = 0;
1159  }
1160
1161  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1162                                             ControllingExpr, Types, Exprs,
1163                                             NumAssocs);
1164  delete [] Types;
1165  return ER;
1166}
1167
1168ExprResult
1169Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1170                                 SourceLocation DefaultLoc,
1171                                 SourceLocation RParenLoc,
1172                                 Expr *ControllingExpr,
1173                                 TypeSourceInfo **Types,
1174                                 Expr **Exprs,
1175                                 unsigned NumAssocs) {
1176  if (ControllingExpr->getType()->isPlaceholderType()) {
1177    ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1178    if (result.isInvalid()) return ExprError();
1179    ControllingExpr = result.take();
1180  }
1181
1182  bool TypeErrorFound = false,
1183       IsResultDependent = ControllingExpr->isTypeDependent(),
1184       ContainsUnexpandedParameterPack
1185         = ControllingExpr->containsUnexpandedParameterPack();
1186
1187  for (unsigned i = 0; i < NumAssocs; ++i) {
1188    if (Exprs[i]->containsUnexpandedParameterPack())
1189      ContainsUnexpandedParameterPack = true;
1190
1191    if (Types[i]) {
1192      if (Types[i]->getType()->containsUnexpandedParameterPack())
1193        ContainsUnexpandedParameterPack = true;
1194
1195      if (Types[i]->getType()->isDependentType()) {
1196        IsResultDependent = true;
1197      } else {
1198        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1199        // complete object type other than a variably modified type."
1200        unsigned D = 0;
1201        if (Types[i]->getType()->isIncompleteType())
1202          D = diag::err_assoc_type_incomplete;
1203        else if (!Types[i]->getType()->isObjectType())
1204          D = diag::err_assoc_type_nonobject;
1205        else if (Types[i]->getType()->isVariablyModifiedType())
1206          D = diag::err_assoc_type_variably_modified;
1207
1208        if (D != 0) {
1209          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1210            << Types[i]->getTypeLoc().getSourceRange()
1211            << Types[i]->getType();
1212          TypeErrorFound = true;
1213        }
1214
1215        // C11 6.5.1.1p2 "No two generic associations in the same generic
1216        // selection shall specify compatible types."
1217        for (unsigned j = i+1; j < NumAssocs; ++j)
1218          if (Types[j] && !Types[j]->getType()->isDependentType() &&
1219              Context.typesAreCompatible(Types[i]->getType(),
1220                                         Types[j]->getType())) {
1221            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1222                 diag::err_assoc_compatible_types)
1223              << Types[j]->getTypeLoc().getSourceRange()
1224              << Types[j]->getType()
1225              << Types[i]->getType();
1226            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1227                 diag::note_compat_assoc)
1228              << Types[i]->getTypeLoc().getSourceRange()
1229              << Types[i]->getType();
1230            TypeErrorFound = true;
1231          }
1232      }
1233    }
1234  }
1235  if (TypeErrorFound)
1236    return ExprError();
1237
1238  // If we determined that the generic selection is result-dependent, don't
1239  // try to compute the result expression.
1240  if (IsResultDependent)
1241    return Owned(new (Context) GenericSelectionExpr(
1242                   Context, KeyLoc, ControllingExpr,
1243                   llvm::makeArrayRef(Types, NumAssocs),
1244                   llvm::makeArrayRef(Exprs, NumAssocs),
1245                   DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1246
1247  SmallVector<unsigned, 1> CompatIndices;
1248  unsigned DefaultIndex = -1U;
1249  for (unsigned i = 0; i < NumAssocs; ++i) {
1250    if (!Types[i])
1251      DefaultIndex = i;
1252    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1253                                        Types[i]->getType()))
1254      CompatIndices.push_back(i);
1255  }
1256
1257  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1258  // type compatible with at most one of the types named in its generic
1259  // association list."
1260  if (CompatIndices.size() > 1) {
1261    // We strip parens here because the controlling expression is typically
1262    // parenthesized in macro definitions.
1263    ControllingExpr = ControllingExpr->IgnoreParens();
1264    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1265      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1266      << (unsigned) CompatIndices.size();
1267    for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1268         E = CompatIndices.end(); I != E; ++I) {
1269      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1270           diag::note_compat_assoc)
1271        << Types[*I]->getTypeLoc().getSourceRange()
1272        << Types[*I]->getType();
1273    }
1274    return ExprError();
1275  }
1276
1277  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1278  // its controlling expression shall have type compatible with exactly one of
1279  // the types named in its generic association list."
1280  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1281    // We strip parens here because the controlling expression is typically
1282    // parenthesized in macro definitions.
1283    ControllingExpr = ControllingExpr->IgnoreParens();
1284    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1285      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1286    return ExprError();
1287  }
1288
1289  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1290  // type name that is compatible with the type of the controlling expression,
1291  // then the result expression of the generic selection is the expression
1292  // in that generic association. Otherwise, the result expression of the
1293  // generic selection is the expression in the default generic association."
1294  unsigned ResultIndex =
1295    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1296
1297  return Owned(new (Context) GenericSelectionExpr(
1298                 Context, KeyLoc, ControllingExpr,
1299                 llvm::makeArrayRef(Types, NumAssocs),
1300                 llvm::makeArrayRef(Exprs, NumAssocs),
1301                 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1302                 ResultIndex));
1303}
1304
1305/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1306/// location of the token and the offset of the ud-suffix within it.
1307static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1308                                     unsigned Offset) {
1309  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1310                                        S.getLangOpts());
1311}
1312
1313/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1314/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1315static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1316                                                 IdentifierInfo *UDSuffix,
1317                                                 SourceLocation UDSuffixLoc,
1318                                                 ArrayRef<Expr*> Args,
1319                                                 SourceLocation LitEndLoc) {
1320  assert(Args.size() <= 2 && "too many arguments for literal operator");
1321
1322  QualType ArgTy[2];
1323  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1324    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1325    if (ArgTy[ArgIdx]->isArrayType())
1326      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1327  }
1328
1329  DeclarationName OpName =
1330    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1331  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1332  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1333
1334  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1335  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1336                              /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1337    return ExprError();
1338
1339  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1340}
1341
1342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1343/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1345/// multiple tokens.  However, the common case is that StringToks points to one
1346/// string.
1347///
1348ExprResult
1349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1350                         Scope *UDLScope) {
1351  assert(NumStringToks && "Must have at least one string!");
1352
1353  StringLiteralParser Literal(StringToks, NumStringToks, PP);
1354  if (Literal.hadError)
1355    return ExprError();
1356
1357  SmallVector<SourceLocation, 4> StringTokLocs;
1358  for (unsigned i = 0; i != NumStringToks; ++i)
1359    StringTokLocs.push_back(StringToks[i].getLocation());
1360
1361  QualType StrTy = Context.CharTy;
1362  if (Literal.isWide())
1363    StrTy = Context.getWCharType();
1364  else if (Literal.isUTF16())
1365    StrTy = Context.Char16Ty;
1366  else if (Literal.isUTF32())
1367    StrTy = Context.Char32Ty;
1368  else if (Literal.isPascal())
1369    StrTy = Context.UnsignedCharTy;
1370
1371  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1372  if (Literal.isWide())
1373    Kind = StringLiteral::Wide;
1374  else if (Literal.isUTF8())
1375    Kind = StringLiteral::UTF8;
1376  else if (Literal.isUTF16())
1377    Kind = StringLiteral::UTF16;
1378  else if (Literal.isUTF32())
1379    Kind = StringLiteral::UTF32;
1380
1381  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1382  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1383    StrTy.addConst();
1384
1385  // Get an array type for the string, according to C99 6.4.5.  This includes
1386  // the nul terminator character as well as the string length for pascal
1387  // strings.
1388  StrTy = Context.getConstantArrayType(StrTy,
1389                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
1390                                       ArrayType::Normal, 0);
1391
1392  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1393  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1394                                             Kind, Literal.Pascal, StrTy,
1395                                             &StringTokLocs[0],
1396                                             StringTokLocs.size());
1397  if (Literal.getUDSuffix().empty())
1398    return Owned(Lit);
1399
1400  // We're building a user-defined literal.
1401  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1402  SourceLocation UDSuffixLoc =
1403    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1404                   Literal.getUDSuffixOffset());
1405
1406  // Make sure we're allowed user-defined literals here.
1407  if (!UDLScope)
1408    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1409
1410  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1411  //   operator "" X (str, len)
1412  QualType SizeType = Context.getSizeType();
1413  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1414  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1415                                                  StringTokLocs[0]);
1416  Expr *Args[] = { Lit, LenArg };
1417  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1418                                        Args, StringTokLocs.back());
1419}
1420
1421ExprResult
1422Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1423                       SourceLocation Loc,
1424                       const CXXScopeSpec *SS) {
1425  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1426  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1427}
1428
1429/// BuildDeclRefExpr - Build an expression that references a
1430/// declaration that does not require a closure capture.
1431ExprResult
1432Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1433                       const DeclarationNameInfo &NameInfo,
1434                       const CXXScopeSpec *SS) {
1435  if (getLangOpts().CUDA)
1436    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1437      if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1438        CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1439                           CalleeTarget = IdentifyCUDATarget(Callee);
1440        if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1441          Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1442            << CalleeTarget << D->getIdentifier() << CallerTarget;
1443          Diag(D->getLocation(), diag::note_previous_decl)
1444            << D->getIdentifier();
1445          return ExprError();
1446        }
1447      }
1448
1449  bool refersToEnclosingScope =
1450    (CurContext != D->getDeclContext() &&
1451     D->getDeclContext()->isFunctionOrMethod());
1452
1453  DeclRefExpr *E = DeclRefExpr::Create(Context,
1454                                       SS ? SS->getWithLocInContext(Context)
1455                                              : NestedNameSpecifierLoc(),
1456                                       SourceLocation(),
1457                                       D, refersToEnclosingScope,
1458                                       NameInfo, Ty, VK);
1459
1460  MarkDeclRefReferenced(E);
1461
1462  if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1463      Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1464    DiagnosticsEngine::Level Level =
1465      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1466                               E->getLocStart());
1467    if (Level != DiagnosticsEngine::Ignored)
1468      getCurFunction()->recordUseOfWeak(E);
1469  }
1470
1471  // Just in case we're building an illegal pointer-to-member.
1472  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1473  if (FD && FD->isBitField())
1474    E->setObjectKind(OK_BitField);
1475
1476  return Owned(E);
1477}
1478
1479/// Decomposes the given name into a DeclarationNameInfo, its location, and
1480/// possibly a list of template arguments.
1481///
1482/// If this produces template arguments, it is permitted to call
1483/// DecomposeTemplateName.
1484///
1485/// This actually loses a lot of source location information for
1486/// non-standard name kinds; we should consider preserving that in
1487/// some way.
1488void
1489Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1490                             TemplateArgumentListInfo &Buffer,
1491                             DeclarationNameInfo &NameInfo,
1492                             const TemplateArgumentListInfo *&TemplateArgs) {
1493  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1494    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1495    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1496
1497    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1498                                       Id.TemplateId->NumArgs);
1499    translateTemplateArguments(TemplateArgsPtr, Buffer);
1500
1501    TemplateName TName = Id.TemplateId->Template.get();
1502    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1503    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1504    TemplateArgs = &Buffer;
1505  } else {
1506    NameInfo = GetNameFromUnqualifiedId(Id);
1507    TemplateArgs = 0;
1508  }
1509}
1510
1511/// Diagnose an empty lookup.
1512///
1513/// \return false if new lookup candidates were found
1514bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1515                               CorrectionCandidateCallback &CCC,
1516                               TemplateArgumentListInfo *ExplicitTemplateArgs,
1517                               llvm::ArrayRef<Expr *> Args) {
1518  DeclarationName Name = R.getLookupName();
1519
1520  unsigned diagnostic = diag::err_undeclared_var_use;
1521  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1522  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1523      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1524      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1525    diagnostic = diag::err_undeclared_use;
1526    diagnostic_suggest = diag::err_undeclared_use_suggest;
1527  }
1528
1529  // If the original lookup was an unqualified lookup, fake an
1530  // unqualified lookup.  This is useful when (for example) the
1531  // original lookup would not have found something because it was a
1532  // dependent name.
1533  DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1534    ? CurContext : 0;
1535  while (DC) {
1536    if (isa<CXXRecordDecl>(DC)) {
1537      LookupQualifiedName(R, DC);
1538
1539      if (!R.empty()) {
1540        // Don't give errors about ambiguities in this lookup.
1541        R.suppressDiagnostics();
1542
1543        // During a default argument instantiation the CurContext points
1544        // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1545        // function parameter list, hence add an explicit check.
1546        bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1547                              ActiveTemplateInstantiations.back().Kind ==
1548            ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1549        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1550        bool isInstance = CurMethod &&
1551                          CurMethod->isInstance() &&
1552                          DC == CurMethod->getParent() && !isDefaultArgument;
1553
1554
1555        // Give a code modification hint to insert 'this->'.
1556        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1557        // Actually quite difficult!
1558        if (getLangOpts().MicrosoftMode)
1559          diagnostic = diag::warn_found_via_dependent_bases_lookup;
1560        if (isInstance) {
1561          Diag(R.getNameLoc(), diagnostic) << Name
1562            << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1563          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1564              CallsUndergoingInstantiation.back()->getCallee());
1565
1566
1567          CXXMethodDecl *DepMethod;
1568          if (CurMethod->getTemplatedKind() ==
1569              FunctionDecl::TK_FunctionTemplateSpecialization)
1570            DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1571                getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1572          else
1573            DepMethod = cast<CXXMethodDecl>(
1574                CurMethod->getInstantiatedFromMemberFunction());
1575          assert(DepMethod && "No template pattern found");
1576
1577          QualType DepThisType = DepMethod->getThisType(Context);
1578          CheckCXXThisCapture(R.getNameLoc());
1579          CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1580                                     R.getNameLoc(), DepThisType, false);
1581          TemplateArgumentListInfo TList;
1582          if (ULE->hasExplicitTemplateArgs())
1583            ULE->copyTemplateArgumentsInto(TList);
1584
1585          CXXScopeSpec SS;
1586          SS.Adopt(ULE->getQualifierLoc());
1587          CXXDependentScopeMemberExpr *DepExpr =
1588              CXXDependentScopeMemberExpr::Create(
1589                  Context, DepThis, DepThisType, true, SourceLocation(),
1590                  SS.getWithLocInContext(Context),
1591                  ULE->getTemplateKeywordLoc(), 0,
1592                  R.getLookupNameInfo(),
1593                  ULE->hasExplicitTemplateArgs() ? &TList : 0);
1594          CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1595        } else {
1596          Diag(R.getNameLoc(), diagnostic) << Name;
1597        }
1598
1599        // Do we really want to note all of these?
1600        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1601          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1602
1603        // Return true if we are inside a default argument instantiation
1604        // and the found name refers to an instance member function, otherwise
1605        // the function calling DiagnoseEmptyLookup will try to create an
1606        // implicit member call and this is wrong for default argument.
1607        if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1608          Diag(R.getNameLoc(), diag::err_member_call_without_object);
1609          return true;
1610        }
1611
1612        // Tell the callee to try to recover.
1613        return false;
1614      }
1615
1616      R.clear();
1617    }
1618
1619    // In Microsoft mode, if we are performing lookup from within a friend
1620    // function definition declared at class scope then we must set
1621    // DC to the lexical parent to be able to search into the parent
1622    // class.
1623    if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1624        cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1625        DC->getLexicalParent()->isRecord())
1626      DC = DC->getLexicalParent();
1627    else
1628      DC = DC->getParent();
1629  }
1630
1631  // We didn't find anything, so try to correct for a typo.
1632  TypoCorrection Corrected;
1633  if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1634                                    S, &SS, CCC))) {
1635    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1636    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1637    R.setLookupName(Corrected.getCorrection());
1638
1639    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1640      if (Corrected.isOverloaded()) {
1641        OverloadCandidateSet OCS(R.getNameLoc());
1642        OverloadCandidateSet::iterator Best;
1643        for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1644                                        CDEnd = Corrected.end();
1645             CD != CDEnd; ++CD) {
1646          if (FunctionTemplateDecl *FTD =
1647                   dyn_cast<FunctionTemplateDecl>(*CD))
1648            AddTemplateOverloadCandidate(
1649                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1650                Args, OCS);
1651          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1652            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1653              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1654                                   Args, OCS);
1655        }
1656        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1657          case OR_Success:
1658            ND = Best->Function;
1659            break;
1660          default:
1661            break;
1662        }
1663      }
1664      R.addDecl(ND);
1665      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1666        if (SS.isEmpty())
1667          Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1668            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1669        else
1670          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1671            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1672            << SS.getRange()
1673            << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1674                                            CorrectedStr);
1675
1676        unsigned diag = isa<ImplicitParamDecl>(ND)
1677          ? diag::note_implicit_param_decl
1678          : diag::note_previous_decl;
1679
1680        Diag(ND->getLocation(), diag)
1681          << CorrectedQuotedStr;
1682
1683        // Tell the callee to try to recover.
1684        return false;
1685      }
1686
1687      if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1688        // FIXME: If we ended up with a typo for a type name or
1689        // Objective-C class name, we're in trouble because the parser
1690        // is in the wrong place to recover. Suggest the typo
1691        // correction, but don't make it a fix-it since we're not going
1692        // to recover well anyway.
1693        if (SS.isEmpty())
1694          Diag(R.getNameLoc(), diagnostic_suggest)
1695            << Name << CorrectedQuotedStr;
1696        else
1697          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1698            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1699            << SS.getRange();
1700
1701        // Don't try to recover; it won't work.
1702        return true;
1703      }
1704    } else {
1705      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1706      // because we aren't able to recover.
1707      if (SS.isEmpty())
1708        Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1709      else
1710        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1711        << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1712        << SS.getRange();
1713      return true;
1714    }
1715  }
1716  R.clear();
1717
1718  // Emit a special diagnostic for failed member lookups.
1719  // FIXME: computing the declaration context might fail here (?)
1720  if (!SS.isEmpty()) {
1721    Diag(R.getNameLoc(), diag::err_no_member)
1722      << Name << computeDeclContext(SS, false)
1723      << SS.getRange();
1724    return true;
1725  }
1726
1727  // Give up, we can't recover.
1728  Diag(R.getNameLoc(), diagnostic) << Name;
1729  return true;
1730}
1731
1732ExprResult Sema::ActOnIdExpression(Scope *S,
1733                                   CXXScopeSpec &SS,
1734                                   SourceLocation TemplateKWLoc,
1735                                   UnqualifiedId &Id,
1736                                   bool HasTrailingLParen,
1737                                   bool IsAddressOfOperand,
1738                                   CorrectionCandidateCallback *CCC) {
1739  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1740         "cannot be direct & operand and have a trailing lparen");
1741
1742  if (SS.isInvalid())
1743    return ExprError();
1744
1745  TemplateArgumentListInfo TemplateArgsBuffer;
1746
1747  // Decompose the UnqualifiedId into the following data.
1748  DeclarationNameInfo NameInfo;
1749  const TemplateArgumentListInfo *TemplateArgs;
1750  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1751
1752  DeclarationName Name = NameInfo.getName();
1753  IdentifierInfo *II = Name.getAsIdentifierInfo();
1754  SourceLocation NameLoc = NameInfo.getLoc();
1755
1756  // C++ [temp.dep.expr]p3:
1757  //   An id-expression is type-dependent if it contains:
1758  //     -- an identifier that was declared with a dependent type,
1759  //        (note: handled after lookup)
1760  //     -- a template-id that is dependent,
1761  //        (note: handled in BuildTemplateIdExpr)
1762  //     -- a conversion-function-id that specifies a dependent type,
1763  //     -- a nested-name-specifier that contains a class-name that
1764  //        names a dependent type.
1765  // Determine whether this is a member of an unknown specialization;
1766  // we need to handle these differently.
1767  bool DependentID = false;
1768  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1769      Name.getCXXNameType()->isDependentType()) {
1770    DependentID = true;
1771  } else if (SS.isSet()) {
1772    if (DeclContext *DC = computeDeclContext(SS, false)) {
1773      if (RequireCompleteDeclContext(SS, DC))
1774        return ExprError();
1775    } else {
1776      DependentID = true;
1777    }
1778  }
1779
1780  if (DependentID)
1781    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1782                                      IsAddressOfOperand, TemplateArgs);
1783
1784  // Perform the required lookup.
1785  LookupResult R(*this, NameInfo,
1786                 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1787                  ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1788  if (TemplateArgs) {
1789    // Lookup the template name again to correctly establish the context in
1790    // which it was found. This is really unfortunate as we already did the
1791    // lookup to determine that it was a template name in the first place. If
1792    // this becomes a performance hit, we can work harder to preserve those
1793    // results until we get here but it's likely not worth it.
1794    bool MemberOfUnknownSpecialization;
1795    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1796                       MemberOfUnknownSpecialization);
1797
1798    if (MemberOfUnknownSpecialization ||
1799        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1800      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1801                                        IsAddressOfOperand, TemplateArgs);
1802  } else {
1803    bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1804    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1805
1806    // If the result might be in a dependent base class, this is a dependent
1807    // id-expression.
1808    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1809      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1810                                        IsAddressOfOperand, TemplateArgs);
1811
1812    // If this reference is in an Objective-C method, then we need to do
1813    // some special Objective-C lookup, too.
1814    if (IvarLookupFollowUp) {
1815      ExprResult E(LookupInObjCMethod(R, S, II, true));
1816      if (E.isInvalid())
1817        return ExprError();
1818
1819      if (Expr *Ex = E.takeAs<Expr>())
1820        return Owned(Ex);
1821    }
1822  }
1823
1824  if (R.isAmbiguous())
1825    return ExprError();
1826
1827  // Determine whether this name might be a candidate for
1828  // argument-dependent lookup.
1829  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1830
1831  if (R.empty() && !ADL) {
1832    // Otherwise, this could be an implicitly declared function reference (legal
1833    // in C90, extension in C99, forbidden in C++).
1834    if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1835      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1836      if (D) R.addDecl(D);
1837    }
1838
1839    // If this name wasn't predeclared and if this is not a function
1840    // call, diagnose the problem.
1841    if (R.empty()) {
1842
1843      // In Microsoft mode, if we are inside a template class member function
1844      // and we can't resolve an identifier then assume the identifier is type
1845      // dependent. The goal is to postpone name lookup to instantiation time
1846      // to be able to search into type dependent base classes.
1847      if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1848          isa<CXXMethodDecl>(CurContext))
1849        return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1850                                          IsAddressOfOperand, TemplateArgs);
1851
1852      CorrectionCandidateCallback DefaultValidator;
1853      if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1854        return ExprError();
1855
1856      assert(!R.empty() &&
1857             "DiagnoseEmptyLookup returned false but added no results");
1858
1859      // If we found an Objective-C instance variable, let
1860      // LookupInObjCMethod build the appropriate expression to
1861      // reference the ivar.
1862      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1863        R.clear();
1864        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1865        // In a hopelessly buggy code, Objective-C instance variable
1866        // lookup fails and no expression will be built to reference it.
1867        if (!E.isInvalid() && !E.get())
1868          return ExprError();
1869        return E;
1870      }
1871    }
1872  }
1873
1874  // This is guaranteed from this point on.
1875  assert(!R.empty() || ADL);
1876
1877  // Check whether this might be a C++ implicit instance member access.
1878  // C++ [class.mfct.non-static]p3:
1879  //   When an id-expression that is not part of a class member access
1880  //   syntax and not used to form a pointer to member is used in the
1881  //   body of a non-static member function of class X, if name lookup
1882  //   resolves the name in the id-expression to a non-static non-type
1883  //   member of some class C, the id-expression is transformed into a
1884  //   class member access expression using (*this) as the
1885  //   postfix-expression to the left of the . operator.
1886  //
1887  // But we don't actually need to do this for '&' operands if R
1888  // resolved to a function or overloaded function set, because the
1889  // expression is ill-formed if it actually works out to be a
1890  // non-static member function:
1891  //
1892  // C++ [expr.ref]p4:
1893  //   Otherwise, if E1.E2 refers to a non-static member function. . .
1894  //   [t]he expression can be used only as the left-hand operand of a
1895  //   member function call.
1896  //
1897  // There are other safeguards against such uses, but it's important
1898  // to get this right here so that we don't end up making a
1899  // spuriously dependent expression if we're inside a dependent
1900  // instance method.
1901  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1902    bool MightBeImplicitMember;
1903    if (!IsAddressOfOperand)
1904      MightBeImplicitMember = true;
1905    else if (!SS.isEmpty())
1906      MightBeImplicitMember = false;
1907    else if (R.isOverloadedResult())
1908      MightBeImplicitMember = false;
1909    else if (R.isUnresolvableResult())
1910      MightBeImplicitMember = true;
1911    else
1912      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1913                              isa<IndirectFieldDecl>(R.getFoundDecl());
1914
1915    if (MightBeImplicitMember)
1916      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1917                                             R, TemplateArgs);
1918  }
1919
1920  if (TemplateArgs || TemplateKWLoc.isValid())
1921    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1922
1923  return BuildDeclarationNameExpr(SS, R, ADL);
1924}
1925
1926/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1927/// declaration name, generally during template instantiation.
1928/// There's a large number of things which don't need to be done along
1929/// this path.
1930ExprResult
1931Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1932                                        const DeclarationNameInfo &NameInfo,
1933                                        bool IsAddressOfOperand) {
1934  DeclContext *DC = computeDeclContext(SS, false);
1935  if (!DC)
1936    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1937                                     NameInfo, /*TemplateArgs=*/0);
1938
1939  if (RequireCompleteDeclContext(SS, DC))
1940    return ExprError();
1941
1942  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1943  LookupQualifiedName(R, DC);
1944
1945  if (R.isAmbiguous())
1946    return ExprError();
1947
1948  if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1949    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1950                                     NameInfo, /*TemplateArgs=*/0);
1951
1952  if (R.empty()) {
1953    Diag(NameInfo.getLoc(), diag::err_no_member)
1954      << NameInfo.getName() << DC << SS.getRange();
1955    return ExprError();
1956  }
1957
1958  // Defend against this resolving to an implicit member access. We usually
1959  // won't get here if this might be a legitimate a class member (we end up in
1960  // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1961  // a pointer-to-member or in an unevaluated context in C++11.
1962  if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1963    return BuildPossibleImplicitMemberExpr(SS,
1964                                           /*TemplateKWLoc=*/SourceLocation(),
1965                                           R, /*TemplateArgs=*/0);
1966
1967  return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
1968}
1969
1970/// LookupInObjCMethod - The parser has read a name in, and Sema has
1971/// detected that we're currently inside an ObjC method.  Perform some
1972/// additional lookup.
1973///
1974/// Ideally, most of this would be done by lookup, but there's
1975/// actually quite a lot of extra work involved.
1976///
1977/// Returns a null sentinel to indicate trivial success.
1978ExprResult
1979Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1980                         IdentifierInfo *II, bool AllowBuiltinCreation) {
1981  SourceLocation Loc = Lookup.getNameLoc();
1982  ObjCMethodDecl *CurMethod = getCurMethodDecl();
1983
1984  // Check for error condition which is already reported.
1985  if (!CurMethod)
1986    return ExprError();
1987
1988  // There are two cases to handle here.  1) scoped lookup could have failed,
1989  // in which case we should look for an ivar.  2) scoped lookup could have
1990  // found a decl, but that decl is outside the current instance method (i.e.
1991  // a global variable).  In these two cases, we do a lookup for an ivar with
1992  // this name, if the lookup sucedes, we replace it our current decl.
1993
1994  // If we're in a class method, we don't normally want to look for
1995  // ivars.  But if we don't find anything else, and there's an
1996  // ivar, that's an error.
1997  bool IsClassMethod = CurMethod->isClassMethod();
1998
1999  bool LookForIvars;
2000  if (Lookup.empty())
2001    LookForIvars = true;
2002  else if (IsClassMethod)
2003    LookForIvars = false;
2004  else
2005    LookForIvars = (Lookup.isSingleResult() &&
2006                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2007  ObjCInterfaceDecl *IFace = 0;
2008  if (LookForIvars) {
2009    IFace = CurMethod->getClassInterface();
2010    ObjCInterfaceDecl *ClassDeclared;
2011    ObjCIvarDecl *IV = 0;
2012    if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2013      // Diagnose using an ivar in a class method.
2014      if (IsClassMethod)
2015        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2016                         << IV->getDeclName());
2017
2018      // If we're referencing an invalid decl, just return this as a silent
2019      // error node.  The error diagnostic was already emitted on the decl.
2020      if (IV->isInvalidDecl())
2021        return ExprError();
2022
2023      // Check if referencing a field with __attribute__((deprecated)).
2024      if (DiagnoseUseOfDecl(IV, Loc))
2025        return ExprError();
2026
2027      // Diagnose the use of an ivar outside of the declaring class.
2028      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2029          !declaresSameEntity(ClassDeclared, IFace) &&
2030          !getLangOpts().DebuggerSupport)
2031        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2032
2033      // FIXME: This should use a new expr for a direct reference, don't
2034      // turn this into Self->ivar, just return a BareIVarExpr or something.
2035      IdentifierInfo &II = Context.Idents.get("self");
2036      UnqualifiedId SelfName;
2037      SelfName.setIdentifier(&II, SourceLocation());
2038      SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2039      CXXScopeSpec SelfScopeSpec;
2040      SourceLocation TemplateKWLoc;
2041      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2042                                              SelfName, false, false);
2043      if (SelfExpr.isInvalid())
2044        return ExprError();
2045
2046      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2047      if (SelfExpr.isInvalid())
2048        return ExprError();
2049
2050      MarkAnyDeclReferenced(Loc, IV, true);
2051
2052      ObjCMethodFamily MF = CurMethod->getMethodFamily();
2053      if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2054          !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2055        Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2056
2057      ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2058                                                              Loc,
2059                                                              SelfExpr.take(),
2060                                                              true, true);
2061
2062      if (getLangOpts().ObjCAutoRefCount) {
2063        if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2064          DiagnosticsEngine::Level Level =
2065            Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2066          if (Level != DiagnosticsEngine::Ignored)
2067            getCurFunction()->recordUseOfWeak(Result);
2068        }
2069        if (CurContext->isClosure())
2070          Diag(Loc, diag::warn_implicitly_retains_self)
2071            << FixItHint::CreateInsertion(Loc, "self->");
2072      }
2073
2074      return Owned(Result);
2075    }
2076  } else if (CurMethod->isInstanceMethod()) {
2077    // We should warn if a local variable hides an ivar.
2078    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2079      ObjCInterfaceDecl *ClassDeclared;
2080      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2081        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2082            declaresSameEntity(IFace, ClassDeclared))
2083          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2084      }
2085    }
2086  } else if (Lookup.isSingleResult() &&
2087             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2088    // If accessing a stand-alone ivar in a class method, this is an error.
2089    if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2090      return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2091                       << IV->getDeclName());
2092  }
2093
2094  if (Lookup.empty() && II && AllowBuiltinCreation) {
2095    // FIXME. Consolidate this with similar code in LookupName.
2096    if (unsigned BuiltinID = II->getBuiltinID()) {
2097      if (!(getLangOpts().CPlusPlus &&
2098            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2099        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2100                                           S, Lookup.isForRedeclaration(),
2101                                           Lookup.getNameLoc());
2102        if (D) Lookup.addDecl(D);
2103      }
2104    }
2105  }
2106  // Sentinel value saying that we didn't do anything special.
2107  return Owned((Expr*) 0);
2108}
2109
2110/// \brief Cast a base object to a member's actual type.
2111///
2112/// Logically this happens in three phases:
2113///
2114/// * First we cast from the base type to the naming class.
2115///   The naming class is the class into which we were looking
2116///   when we found the member;  it's the qualifier type if a
2117///   qualifier was provided, and otherwise it's the base type.
2118///
2119/// * Next we cast from the naming class to the declaring class.
2120///   If the member we found was brought into a class's scope by
2121///   a using declaration, this is that class;  otherwise it's
2122///   the class declaring the member.
2123///
2124/// * Finally we cast from the declaring class to the "true"
2125///   declaring class of the member.  This conversion does not
2126///   obey access control.
2127ExprResult
2128Sema::PerformObjectMemberConversion(Expr *From,
2129                                    NestedNameSpecifier *Qualifier,
2130                                    NamedDecl *FoundDecl,
2131                                    NamedDecl *Member) {
2132  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2133  if (!RD)
2134    return Owned(From);
2135
2136  QualType DestRecordType;
2137  QualType DestType;
2138  QualType FromRecordType;
2139  QualType FromType = From->getType();
2140  bool PointerConversions = false;
2141  if (isa<FieldDecl>(Member)) {
2142    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2143
2144    if (FromType->getAs<PointerType>()) {
2145      DestType = Context.getPointerType(DestRecordType);
2146      FromRecordType = FromType->getPointeeType();
2147      PointerConversions = true;
2148    } else {
2149      DestType = DestRecordType;
2150      FromRecordType = FromType;
2151    }
2152  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2153    if (Method->isStatic())
2154      return Owned(From);
2155
2156    DestType = Method->getThisType(Context);
2157    DestRecordType = DestType->getPointeeType();
2158
2159    if (FromType->getAs<PointerType>()) {
2160      FromRecordType = FromType->getPointeeType();
2161      PointerConversions = true;
2162    } else {
2163      FromRecordType = FromType;
2164      DestType = DestRecordType;
2165    }
2166  } else {
2167    // No conversion necessary.
2168    return Owned(From);
2169  }
2170
2171  if (DestType->isDependentType() || FromType->isDependentType())
2172    return Owned(From);
2173
2174  // If the unqualified types are the same, no conversion is necessary.
2175  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2176    return Owned(From);
2177
2178  SourceRange FromRange = From->getSourceRange();
2179  SourceLocation FromLoc = FromRange.getBegin();
2180
2181  ExprValueKind VK = From->getValueKind();
2182
2183  // C++ [class.member.lookup]p8:
2184  //   [...] Ambiguities can often be resolved by qualifying a name with its
2185  //   class name.
2186  //
2187  // If the member was a qualified name and the qualified referred to a
2188  // specific base subobject type, we'll cast to that intermediate type
2189  // first and then to the object in which the member is declared. That allows
2190  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2191  //
2192  //   class Base { public: int x; };
2193  //   class Derived1 : public Base { };
2194  //   class Derived2 : public Base { };
2195  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2196  //
2197  //   void VeryDerived::f() {
2198  //     x = 17; // error: ambiguous base subobjects
2199  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2200  //   }
2201  if (Qualifier) {
2202    QualType QType = QualType(Qualifier->getAsType(), 0);
2203    assert(!QType.isNull() && "lookup done with dependent qualifier?");
2204    assert(QType->isRecordType() && "lookup done with non-record type");
2205
2206    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2207
2208    // In C++98, the qualifier type doesn't actually have to be a base
2209    // type of the object type, in which case we just ignore it.
2210    // Otherwise build the appropriate casts.
2211    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2212      CXXCastPath BasePath;
2213      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2214                                       FromLoc, FromRange, &BasePath))
2215        return ExprError();
2216
2217      if (PointerConversions)
2218        QType = Context.getPointerType(QType);
2219      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2220                               VK, &BasePath).take();
2221
2222      FromType = QType;
2223      FromRecordType = QRecordType;
2224
2225      // If the qualifier type was the same as the destination type,
2226      // we're done.
2227      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2228        return Owned(From);
2229    }
2230  }
2231
2232  bool IgnoreAccess = false;
2233
2234  // If we actually found the member through a using declaration, cast
2235  // down to the using declaration's type.
2236  //
2237  // Pointer equality is fine here because only one declaration of a
2238  // class ever has member declarations.
2239  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2240    assert(isa<UsingShadowDecl>(FoundDecl));
2241    QualType URecordType = Context.getTypeDeclType(
2242                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2243
2244    // We only need to do this if the naming-class to declaring-class
2245    // conversion is non-trivial.
2246    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2247      assert(IsDerivedFrom(FromRecordType, URecordType));
2248      CXXCastPath BasePath;
2249      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2250                                       FromLoc, FromRange, &BasePath))
2251        return ExprError();
2252
2253      QualType UType = URecordType;
2254      if (PointerConversions)
2255        UType = Context.getPointerType(UType);
2256      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2257                               VK, &BasePath).take();
2258      FromType = UType;
2259      FromRecordType = URecordType;
2260    }
2261
2262    // We don't do access control for the conversion from the
2263    // declaring class to the true declaring class.
2264    IgnoreAccess = true;
2265  }
2266
2267  CXXCastPath BasePath;
2268  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2269                                   FromLoc, FromRange, &BasePath,
2270                                   IgnoreAccess))
2271    return ExprError();
2272
2273  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2274                           VK, &BasePath);
2275}
2276
2277bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2278                                      const LookupResult &R,
2279                                      bool HasTrailingLParen) {
2280  // Only when used directly as the postfix-expression of a call.
2281  if (!HasTrailingLParen)
2282    return false;
2283
2284  // Never if a scope specifier was provided.
2285  if (SS.isSet())
2286    return false;
2287
2288  // Only in C++ or ObjC++.
2289  if (!getLangOpts().CPlusPlus)
2290    return false;
2291
2292  // Turn off ADL when we find certain kinds of declarations during
2293  // normal lookup:
2294  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2295    NamedDecl *D = *I;
2296
2297    // C++0x [basic.lookup.argdep]p3:
2298    //     -- a declaration of a class member
2299    // Since using decls preserve this property, we check this on the
2300    // original decl.
2301    if (D->isCXXClassMember())
2302      return false;
2303
2304    // C++0x [basic.lookup.argdep]p3:
2305    //     -- a block-scope function declaration that is not a
2306    //        using-declaration
2307    // NOTE: we also trigger this for function templates (in fact, we
2308    // don't check the decl type at all, since all other decl types
2309    // turn off ADL anyway).
2310    if (isa<UsingShadowDecl>(D))
2311      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2312    else if (D->getDeclContext()->isFunctionOrMethod())
2313      return false;
2314
2315    // C++0x [basic.lookup.argdep]p3:
2316    //     -- a declaration that is neither a function or a function
2317    //        template
2318    // And also for builtin functions.
2319    if (isa<FunctionDecl>(D)) {
2320      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2321
2322      // But also builtin functions.
2323      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2324        return false;
2325    } else if (!isa<FunctionTemplateDecl>(D))
2326      return false;
2327  }
2328
2329  return true;
2330}
2331
2332
2333/// Diagnoses obvious problems with the use of the given declaration
2334/// as an expression.  This is only actually called for lookups that
2335/// were not overloaded, and it doesn't promise that the declaration
2336/// will in fact be used.
2337static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2338  if (isa<TypedefNameDecl>(D)) {
2339    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2340    return true;
2341  }
2342
2343  if (isa<ObjCInterfaceDecl>(D)) {
2344    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2345    return true;
2346  }
2347
2348  if (isa<NamespaceDecl>(D)) {
2349    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2350    return true;
2351  }
2352
2353  return false;
2354}
2355
2356ExprResult
2357Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2358                               LookupResult &R,
2359                               bool NeedsADL) {
2360  // If this is a single, fully-resolved result and we don't need ADL,
2361  // just build an ordinary singleton decl ref.
2362  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2363    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2364                                    R.getFoundDecl());
2365
2366  // We only need to check the declaration if there's exactly one
2367  // result, because in the overloaded case the results can only be
2368  // functions and function templates.
2369  if (R.isSingleResult() &&
2370      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2371    return ExprError();
2372
2373  // Otherwise, just build an unresolved lookup expression.  Suppress
2374  // any lookup-related diagnostics; we'll hash these out later, when
2375  // we've picked a target.
2376  R.suppressDiagnostics();
2377
2378  UnresolvedLookupExpr *ULE
2379    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2380                                   SS.getWithLocInContext(Context),
2381                                   R.getLookupNameInfo(),
2382                                   NeedsADL, R.isOverloadedResult(),
2383                                   R.begin(), R.end());
2384
2385  return Owned(ULE);
2386}
2387
2388/// \brief Complete semantic analysis for a reference to the given declaration.
2389ExprResult
2390Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2391                               const DeclarationNameInfo &NameInfo,
2392                               NamedDecl *D) {
2393  assert(D && "Cannot refer to a NULL declaration");
2394  assert(!isa<FunctionTemplateDecl>(D) &&
2395         "Cannot refer unambiguously to a function template");
2396
2397  SourceLocation Loc = NameInfo.getLoc();
2398  if (CheckDeclInExpr(*this, Loc, D))
2399    return ExprError();
2400
2401  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2402    // Specifically diagnose references to class templates that are missing
2403    // a template argument list.
2404    Diag(Loc, diag::err_template_decl_ref)
2405      << Template << SS.getRange();
2406    Diag(Template->getLocation(), diag::note_template_decl_here);
2407    return ExprError();
2408  }
2409
2410  // Make sure that we're referring to a value.
2411  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2412  if (!VD) {
2413    Diag(Loc, diag::err_ref_non_value)
2414      << D << SS.getRange();
2415    Diag(D->getLocation(), diag::note_declared_at);
2416    return ExprError();
2417  }
2418
2419  // Check whether this declaration can be used. Note that we suppress
2420  // this check when we're going to perform argument-dependent lookup
2421  // on this function name, because this might not be the function
2422  // that overload resolution actually selects.
2423  if (DiagnoseUseOfDecl(VD, Loc))
2424    return ExprError();
2425
2426  // Only create DeclRefExpr's for valid Decl's.
2427  if (VD->isInvalidDecl())
2428    return ExprError();
2429
2430  // Handle members of anonymous structs and unions.  If we got here,
2431  // and the reference is to a class member indirect field, then this
2432  // must be the subject of a pointer-to-member expression.
2433  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2434    if (!indirectField->isCXXClassMember())
2435      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2436                                                      indirectField);
2437
2438  {
2439    QualType type = VD->getType();
2440    ExprValueKind valueKind = VK_RValue;
2441
2442    switch (D->getKind()) {
2443    // Ignore all the non-ValueDecl kinds.
2444#define ABSTRACT_DECL(kind)
2445#define VALUE(type, base)
2446#define DECL(type, base) \
2447    case Decl::type:
2448#include "clang/AST/DeclNodes.inc"
2449      llvm_unreachable("invalid value decl kind");
2450
2451    // These shouldn't make it here.
2452    case Decl::ObjCAtDefsField:
2453    case Decl::ObjCIvar:
2454      llvm_unreachable("forming non-member reference to ivar?");
2455
2456    // Enum constants are always r-values and never references.
2457    // Unresolved using declarations are dependent.
2458    case Decl::EnumConstant:
2459    case Decl::UnresolvedUsingValue:
2460      valueKind = VK_RValue;
2461      break;
2462
2463    // Fields and indirect fields that got here must be for
2464    // pointer-to-member expressions; we just call them l-values for
2465    // internal consistency, because this subexpression doesn't really
2466    // exist in the high-level semantics.
2467    case Decl::Field:
2468    case Decl::IndirectField:
2469      assert(getLangOpts().CPlusPlus &&
2470             "building reference to field in C?");
2471
2472      // These can't have reference type in well-formed programs, but
2473      // for internal consistency we do this anyway.
2474      type = type.getNonReferenceType();
2475      valueKind = VK_LValue;
2476      break;
2477
2478    // Non-type template parameters are either l-values or r-values
2479    // depending on the type.
2480    case Decl::NonTypeTemplateParm: {
2481      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2482        type = reftype->getPointeeType();
2483        valueKind = VK_LValue; // even if the parameter is an r-value reference
2484        break;
2485      }
2486
2487      // For non-references, we need to strip qualifiers just in case
2488      // the template parameter was declared as 'const int' or whatever.
2489      valueKind = VK_RValue;
2490      type = type.getUnqualifiedType();
2491      break;
2492    }
2493
2494    case Decl::Var:
2495      // In C, "extern void blah;" is valid and is an r-value.
2496      if (!getLangOpts().CPlusPlus &&
2497          !type.hasQualifiers() &&
2498          type->isVoidType()) {
2499        valueKind = VK_RValue;
2500        break;
2501      }
2502      // fallthrough
2503
2504    case Decl::ImplicitParam:
2505    case Decl::ParmVar: {
2506      // These are always l-values.
2507      valueKind = VK_LValue;
2508      type = type.getNonReferenceType();
2509
2510      // FIXME: Does the addition of const really only apply in
2511      // potentially-evaluated contexts? Since the variable isn't actually
2512      // captured in an unevaluated context, it seems that the answer is no.
2513      if (!isUnevaluatedContext()) {
2514        QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2515        if (!CapturedType.isNull())
2516          type = CapturedType;
2517      }
2518
2519      break;
2520    }
2521
2522    case Decl::Function: {
2523      if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2524        if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2525          type = Context.BuiltinFnTy;
2526          valueKind = VK_RValue;
2527          break;
2528        }
2529      }
2530
2531      const FunctionType *fty = type->castAs<FunctionType>();
2532
2533      // If we're referring to a function with an __unknown_anytype
2534      // result type, make the entire expression __unknown_anytype.
2535      if (fty->getResultType() == Context.UnknownAnyTy) {
2536        type = Context.UnknownAnyTy;
2537        valueKind = VK_RValue;
2538        break;
2539      }
2540
2541      // Functions are l-values in C++.
2542      if (getLangOpts().CPlusPlus) {
2543        valueKind = VK_LValue;
2544        break;
2545      }
2546
2547      // C99 DR 316 says that, if a function type comes from a
2548      // function definition (without a prototype), that type is only
2549      // used for checking compatibility. Therefore, when referencing
2550      // the function, we pretend that we don't have the full function
2551      // type.
2552      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2553          isa<FunctionProtoType>(fty))
2554        type = Context.getFunctionNoProtoType(fty->getResultType(),
2555                                              fty->getExtInfo());
2556
2557      // Functions are r-values in C.
2558      valueKind = VK_RValue;
2559      break;
2560    }
2561
2562    case Decl::CXXMethod:
2563      // If we're referring to a method with an __unknown_anytype
2564      // result type, make the entire expression __unknown_anytype.
2565      // This should only be possible with a type written directly.
2566      if (const FunctionProtoType *proto
2567            = dyn_cast<FunctionProtoType>(VD->getType()))
2568        if (proto->getResultType() == Context.UnknownAnyTy) {
2569          type = Context.UnknownAnyTy;
2570          valueKind = VK_RValue;
2571          break;
2572        }
2573
2574      // C++ methods are l-values if static, r-values if non-static.
2575      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2576        valueKind = VK_LValue;
2577        break;
2578      }
2579      // fallthrough
2580
2581    case Decl::CXXConversion:
2582    case Decl::CXXDestructor:
2583    case Decl::CXXConstructor:
2584      valueKind = VK_RValue;
2585      break;
2586    }
2587
2588    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2589  }
2590}
2591
2592ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2593  PredefinedExpr::IdentType IT;
2594
2595  switch (Kind) {
2596  default: llvm_unreachable("Unknown simple primary expr!");
2597  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2598  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2599  case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2600  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2601  }
2602
2603  // Pre-defined identifiers are of type char[x], where x is the length of the
2604  // string.
2605
2606  Decl *currentDecl = getCurFunctionOrMethodDecl();
2607  // Blocks and lambdas can occur at global scope. Don't emit a warning.
2608  if (!currentDecl) {
2609    if (const BlockScopeInfo *BSI = getCurBlock())
2610      currentDecl = BSI->TheDecl;
2611    else if (const LambdaScopeInfo *LSI = getCurLambda())
2612      currentDecl = LSI->CallOperator;
2613  }
2614
2615  if (!currentDecl) {
2616    Diag(Loc, diag::ext_predef_outside_function);
2617    currentDecl = Context.getTranslationUnitDecl();
2618  }
2619
2620  QualType ResTy;
2621  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2622    ResTy = Context.DependentTy;
2623  } else {
2624    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2625
2626    llvm::APInt LengthI(32, Length + 1);
2627    if (IT == PredefinedExpr::LFunction)
2628      ResTy = Context.WCharTy.withConst();
2629    else
2630      ResTy = Context.CharTy.withConst();
2631    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2632  }
2633  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2634}
2635
2636ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2637  SmallString<16> CharBuffer;
2638  bool Invalid = false;
2639  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2640  if (Invalid)
2641    return ExprError();
2642
2643  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2644                            PP, Tok.getKind());
2645  if (Literal.hadError())
2646    return ExprError();
2647
2648  QualType Ty;
2649  if (Literal.isWide())
2650    Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2651  else if (Literal.isUTF16())
2652    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2653  else if (Literal.isUTF32())
2654    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2655  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2656    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2657  else
2658    Ty = Context.CharTy;  // 'x' -> char in C++
2659
2660  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2661  if (Literal.isWide())
2662    Kind = CharacterLiteral::Wide;
2663  else if (Literal.isUTF16())
2664    Kind = CharacterLiteral::UTF16;
2665  else if (Literal.isUTF32())
2666    Kind = CharacterLiteral::UTF32;
2667
2668  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2669                                             Tok.getLocation());
2670
2671  if (Literal.getUDSuffix().empty())
2672    return Owned(Lit);
2673
2674  // We're building a user-defined literal.
2675  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2676  SourceLocation UDSuffixLoc =
2677    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2678
2679  // Make sure we're allowed user-defined literals here.
2680  if (!UDLScope)
2681    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2682
2683  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2684  //   operator "" X (ch)
2685  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2686                                        llvm::makeArrayRef(&Lit, 1),
2687                                        Tok.getLocation());
2688}
2689
2690ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2691  unsigned IntSize = Context.getTargetInfo().getIntWidth();
2692  return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2693                                      Context.IntTy, Loc));
2694}
2695
2696static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2697                                  QualType Ty, SourceLocation Loc) {
2698  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2699
2700  using llvm::APFloat;
2701  APFloat Val(Format);
2702
2703  APFloat::opStatus result = Literal.GetFloatValue(Val);
2704
2705  // Overflow is always an error, but underflow is only an error if
2706  // we underflowed to zero (APFloat reports denormals as underflow).
2707  if ((result & APFloat::opOverflow) ||
2708      ((result & APFloat::opUnderflow) && Val.isZero())) {
2709    unsigned diagnostic;
2710    SmallString<20> buffer;
2711    if (result & APFloat::opOverflow) {
2712      diagnostic = diag::warn_float_overflow;
2713      APFloat::getLargest(Format).toString(buffer);
2714    } else {
2715      diagnostic = diag::warn_float_underflow;
2716      APFloat::getSmallest(Format).toString(buffer);
2717    }
2718
2719    S.Diag(Loc, diagnostic)
2720      << Ty
2721      << StringRef(buffer.data(), buffer.size());
2722  }
2723
2724  bool isExact = (result == APFloat::opOK);
2725  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2726}
2727
2728ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2729  // Fast path for a single digit (which is quite common).  A single digit
2730  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2731  if (Tok.getLength() == 1) {
2732    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2733    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2734  }
2735
2736  SmallString<128> SpellingBuffer;
2737  // NumericLiteralParser wants to overread by one character.  Add padding to
2738  // the buffer in case the token is copied to the buffer.  If getSpelling()
2739  // returns a StringRef to the memory buffer, it should have a null char at
2740  // the EOF, so it is also safe.
2741  SpellingBuffer.resize(Tok.getLength() + 1);
2742
2743  // Get the spelling of the token, which eliminates trigraphs, etc.
2744  bool Invalid = false;
2745  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2746  if (Invalid)
2747    return ExprError();
2748
2749  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2750  if (Literal.hadError)
2751    return ExprError();
2752
2753  if (Literal.hasUDSuffix()) {
2754    // We're building a user-defined literal.
2755    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2756    SourceLocation UDSuffixLoc =
2757      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2758
2759    // Make sure we're allowed user-defined literals here.
2760    if (!UDLScope)
2761      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2762
2763    QualType CookedTy;
2764    if (Literal.isFloatingLiteral()) {
2765      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2766      // long double, the literal is treated as a call of the form
2767      //   operator "" X (f L)
2768      CookedTy = Context.LongDoubleTy;
2769    } else {
2770      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2771      // unsigned long long, the literal is treated as a call of the form
2772      //   operator "" X (n ULL)
2773      CookedTy = Context.UnsignedLongLongTy;
2774    }
2775
2776    DeclarationName OpName =
2777      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2778    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2779    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2780
2781    // Perform literal operator lookup to determine if we're building a raw
2782    // literal or a cooked one.
2783    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2784    switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2785                                  /*AllowRawAndTemplate*/true)) {
2786    case LOLR_Error:
2787      return ExprError();
2788
2789    case LOLR_Cooked: {
2790      Expr *Lit;
2791      if (Literal.isFloatingLiteral()) {
2792        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2793      } else {
2794        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2795        if (Literal.GetIntegerValue(ResultVal))
2796          Diag(Tok.getLocation(), diag::warn_integer_too_large);
2797        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2798                                     Tok.getLocation());
2799      }
2800      return BuildLiteralOperatorCall(R, OpNameInfo,
2801                                      llvm::makeArrayRef(&Lit, 1),
2802                                      Tok.getLocation());
2803    }
2804
2805    case LOLR_Raw: {
2806      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2807      // literal is treated as a call of the form
2808      //   operator "" X ("n")
2809      SourceLocation TokLoc = Tok.getLocation();
2810      unsigned Length = Literal.getUDSuffixOffset();
2811      QualType StrTy = Context.getConstantArrayType(
2812          Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2813          ArrayType::Normal, 0);
2814      Expr *Lit = StringLiteral::Create(
2815          Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2816          /*Pascal*/false, StrTy, &TokLoc, 1);
2817      return BuildLiteralOperatorCall(R, OpNameInfo,
2818                                      llvm::makeArrayRef(&Lit, 1), TokLoc);
2819    }
2820
2821    case LOLR_Template:
2822      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2823      // template), L is treated as a call fo the form
2824      //   operator "" X <'c1', 'c2', ... 'ck'>()
2825      // where n is the source character sequence c1 c2 ... ck.
2826      TemplateArgumentListInfo ExplicitArgs;
2827      unsigned CharBits = Context.getIntWidth(Context.CharTy);
2828      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2829      llvm::APSInt Value(CharBits, CharIsUnsigned);
2830      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2831        Value = TokSpelling[I];
2832        TemplateArgument Arg(Context, Value, Context.CharTy);
2833        TemplateArgumentLocInfo ArgInfo;
2834        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2835      }
2836      return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2837                                      Tok.getLocation(), &ExplicitArgs);
2838    }
2839
2840    llvm_unreachable("unexpected literal operator lookup result");
2841  }
2842
2843  Expr *Res;
2844
2845  if (Literal.isFloatingLiteral()) {
2846    QualType Ty;
2847    if (Literal.isFloat)
2848      Ty = Context.FloatTy;
2849    else if (!Literal.isLong)
2850      Ty = Context.DoubleTy;
2851    else
2852      Ty = Context.LongDoubleTy;
2853
2854    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2855
2856    if (Ty == Context.DoubleTy) {
2857      if (getLangOpts().SinglePrecisionConstants) {
2858        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2859      } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2860        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2861        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2862      }
2863    }
2864  } else if (!Literal.isIntegerLiteral()) {
2865    return ExprError();
2866  } else {
2867    QualType Ty;
2868
2869    // 'long long' is a C99 or C++11 feature.
2870    if (!getLangOpts().C99 && Literal.isLongLong) {
2871      if (getLangOpts().CPlusPlus)
2872        Diag(Tok.getLocation(),
2873             getLangOpts().CPlusPlus11 ?
2874             diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2875      else
2876        Diag(Tok.getLocation(), diag::ext_c99_longlong);
2877    }
2878
2879    // Get the value in the widest-possible width.
2880    unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2881    // The microsoft literal suffix extensions support 128-bit literals, which
2882    // may be wider than [u]intmax_t.
2883    // FIXME: Actually, they don't. We seem to have accidentally invented the
2884    //        i128 suffix.
2885    if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2886        PP.getTargetInfo().hasInt128Type())
2887      MaxWidth = 128;
2888    llvm::APInt ResultVal(MaxWidth, 0);
2889
2890    if (Literal.GetIntegerValue(ResultVal)) {
2891      // If this value didn't fit into uintmax_t, warn and force to ull.
2892      Diag(Tok.getLocation(), diag::warn_integer_too_large);
2893      Ty = Context.UnsignedLongLongTy;
2894      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2895             "long long is not intmax_t?");
2896    } else {
2897      // If this value fits into a ULL, try to figure out what else it fits into
2898      // according to the rules of C99 6.4.4.1p5.
2899
2900      // Octal, Hexadecimal, and integers with a U suffix are allowed to
2901      // be an unsigned int.
2902      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2903
2904      // Check from smallest to largest, picking the smallest type we can.
2905      unsigned Width = 0;
2906      if (!Literal.isLong && !Literal.isLongLong) {
2907        // Are int/unsigned possibilities?
2908        unsigned IntSize = Context.getTargetInfo().getIntWidth();
2909
2910        // Does it fit in a unsigned int?
2911        if (ResultVal.isIntN(IntSize)) {
2912          // Does it fit in a signed int?
2913          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2914            Ty = Context.IntTy;
2915          else if (AllowUnsigned)
2916            Ty = Context.UnsignedIntTy;
2917          Width = IntSize;
2918        }
2919      }
2920
2921      // Are long/unsigned long possibilities?
2922      if (Ty.isNull() && !Literal.isLongLong) {
2923        unsigned LongSize = Context.getTargetInfo().getLongWidth();
2924
2925        // Does it fit in a unsigned long?
2926        if (ResultVal.isIntN(LongSize)) {
2927          // Does it fit in a signed long?
2928          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2929            Ty = Context.LongTy;
2930          else if (AllowUnsigned)
2931            Ty = Context.UnsignedLongTy;
2932          Width = LongSize;
2933        }
2934      }
2935
2936      // Check long long if needed.
2937      if (Ty.isNull()) {
2938        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2939
2940        // Does it fit in a unsigned long long?
2941        if (ResultVal.isIntN(LongLongSize)) {
2942          // Does it fit in a signed long long?
2943          // To be compatible with MSVC, hex integer literals ending with the
2944          // LL or i64 suffix are always signed in Microsoft mode.
2945          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2946              (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2947            Ty = Context.LongLongTy;
2948          else if (AllowUnsigned)
2949            Ty = Context.UnsignedLongLongTy;
2950          Width = LongLongSize;
2951        }
2952      }
2953
2954      // If it doesn't fit in unsigned long long, and we're using Microsoft
2955      // extensions, then its a 128-bit integer literal.
2956      if (Ty.isNull() && Literal.isMicrosoftInteger &&
2957          PP.getTargetInfo().hasInt128Type()) {
2958        if (Literal.isUnsigned)
2959          Ty = Context.UnsignedInt128Ty;
2960        else
2961          Ty = Context.Int128Ty;
2962        Width = 128;
2963      }
2964
2965      // If we still couldn't decide a type, we probably have something that
2966      // does not fit in a signed long long, but has no U suffix.
2967      if (Ty.isNull()) {
2968        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2969        Ty = Context.UnsignedLongLongTy;
2970        Width = Context.getTargetInfo().getLongLongWidth();
2971      }
2972
2973      if (ResultVal.getBitWidth() != Width)
2974        ResultVal = ResultVal.trunc(Width);
2975    }
2976    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2977  }
2978
2979  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2980  if (Literal.isImaginary)
2981    Res = new (Context) ImaginaryLiteral(Res,
2982                                        Context.getComplexType(Res->getType()));
2983
2984  return Owned(Res);
2985}
2986
2987ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2988  assert((E != 0) && "ActOnParenExpr() missing expr");
2989  return Owned(new (Context) ParenExpr(L, R, E));
2990}
2991
2992static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2993                                         SourceLocation Loc,
2994                                         SourceRange ArgRange) {
2995  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2996  // scalar or vector data type argument..."
2997  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2998  // type (C99 6.2.5p18) or void.
2999  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3000    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3001      << T << ArgRange;
3002    return true;
3003  }
3004
3005  assert((T->isVoidType() || !T->isIncompleteType()) &&
3006         "Scalar types should always be complete");
3007  return false;
3008}
3009
3010static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3011                                           SourceLocation Loc,
3012                                           SourceRange ArgRange,
3013                                           UnaryExprOrTypeTrait TraitKind) {
3014  // C99 6.5.3.4p1:
3015  if (T->isFunctionType()) {
3016    // alignof(function) is allowed as an extension.
3017    if (TraitKind == UETT_SizeOf)
3018      S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3019    return false;
3020  }
3021
3022  // Allow sizeof(void)/alignof(void) as an extension.
3023  if (T->isVoidType()) {
3024    S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3025    return false;
3026  }
3027
3028  return true;
3029}
3030
3031static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3032                                             SourceLocation Loc,
3033                                             SourceRange ArgRange,
3034                                             UnaryExprOrTypeTrait TraitKind) {
3035  // Reject sizeof(interface) and sizeof(interface<proto>) if the
3036  // runtime doesn't allow it.
3037  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3038    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3039      << T << (TraitKind == UETT_SizeOf)
3040      << ArgRange;
3041    return true;
3042  }
3043
3044  return false;
3045}
3046
3047/// \brief Check the constrains on expression operands to unary type expression
3048/// and type traits.
3049///
3050/// Completes any types necessary and validates the constraints on the operand
3051/// expression. The logic mostly mirrors the type-based overload, but may modify
3052/// the expression as it completes the type for that expression through template
3053/// instantiation, etc.
3054bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3055                                            UnaryExprOrTypeTrait ExprKind) {
3056  QualType ExprTy = E->getType();
3057
3058  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3059  //   the result is the size of the referenced type."
3060  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3061  //   result shall be the alignment of the referenced type."
3062  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3063    ExprTy = Ref->getPointeeType();
3064
3065  if (ExprKind == UETT_VecStep)
3066    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3067                                        E->getSourceRange());
3068
3069  // Whitelist some types as extensions
3070  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3071                                      E->getSourceRange(), ExprKind))
3072    return false;
3073
3074  if (RequireCompleteExprType(E,
3075                              diag::err_sizeof_alignof_incomplete_type,
3076                              ExprKind, E->getSourceRange()))
3077    return true;
3078
3079  // Completeing the expression's type may have changed it.
3080  ExprTy = E->getType();
3081  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3082    ExprTy = Ref->getPointeeType();
3083
3084  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3085                                       E->getSourceRange(), ExprKind))
3086    return true;
3087
3088  if (ExprKind == UETT_SizeOf) {
3089    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3090      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3091        QualType OType = PVD->getOriginalType();
3092        QualType Type = PVD->getType();
3093        if (Type->isPointerType() && OType->isArrayType()) {
3094          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3095            << Type << OType;
3096          Diag(PVD->getLocation(), diag::note_declared_at);
3097        }
3098      }
3099    }
3100  }
3101
3102  return false;
3103}
3104
3105/// \brief Check the constraints on operands to unary expression and type
3106/// traits.
3107///
3108/// This will complete any types necessary, and validate the various constraints
3109/// on those operands.
3110///
3111/// The UsualUnaryConversions() function is *not* called by this routine.
3112/// C99 6.3.2.1p[2-4] all state:
3113///   Except when it is the operand of the sizeof operator ...
3114///
3115/// C++ [expr.sizeof]p4
3116///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3117///   standard conversions are not applied to the operand of sizeof.
3118///
3119/// This policy is followed for all of the unary trait expressions.
3120bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3121                                            SourceLocation OpLoc,
3122                                            SourceRange ExprRange,
3123                                            UnaryExprOrTypeTrait ExprKind) {
3124  if (ExprType->isDependentType())
3125    return false;
3126
3127  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3128  //   the result is the size of the referenced type."
3129  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3130  //   result shall be the alignment of the referenced type."
3131  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3132    ExprType = Ref->getPointeeType();
3133
3134  if (ExprKind == UETT_VecStep)
3135    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3136
3137  // Whitelist some types as extensions
3138  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3139                                      ExprKind))
3140    return false;
3141
3142  if (RequireCompleteType(OpLoc, ExprType,
3143                          diag::err_sizeof_alignof_incomplete_type,
3144                          ExprKind, ExprRange))
3145    return true;
3146
3147  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3148                                       ExprKind))
3149    return true;
3150
3151  return false;
3152}
3153
3154static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3155  E = E->IgnoreParens();
3156
3157  // alignof decl is always ok.
3158  if (isa<DeclRefExpr>(E))
3159    return false;
3160
3161  // Cannot know anything else if the expression is dependent.
3162  if (E->isTypeDependent())
3163    return false;
3164
3165  if (E->getBitField()) {
3166    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3167       << 1 << E->getSourceRange();
3168    return true;
3169  }
3170
3171  // Alignment of a field access is always okay, so long as it isn't a
3172  // bit-field.
3173  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3174    if (isa<FieldDecl>(ME->getMemberDecl()))
3175      return false;
3176
3177  return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3178}
3179
3180bool Sema::CheckVecStepExpr(Expr *E) {
3181  E = E->IgnoreParens();
3182
3183  // Cannot know anything else if the expression is dependent.
3184  if (E->isTypeDependent())
3185    return false;
3186
3187  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3188}
3189
3190/// \brief Build a sizeof or alignof expression given a type operand.
3191ExprResult
3192Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3193                                     SourceLocation OpLoc,
3194                                     UnaryExprOrTypeTrait ExprKind,
3195                                     SourceRange R) {
3196  if (!TInfo)
3197    return ExprError();
3198
3199  QualType T = TInfo->getType();
3200
3201  if (!T->isDependentType() &&
3202      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3203    return ExprError();
3204
3205  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3206  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3207                                                      Context.getSizeType(),
3208                                                      OpLoc, R.getEnd()));
3209}
3210
3211/// \brief Build a sizeof or alignof expression given an expression
3212/// operand.
3213ExprResult
3214Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3215                                     UnaryExprOrTypeTrait ExprKind) {
3216  ExprResult PE = CheckPlaceholderExpr(E);
3217  if (PE.isInvalid())
3218    return ExprError();
3219
3220  E = PE.get();
3221
3222  // Verify that the operand is valid.
3223  bool isInvalid = false;
3224  if (E->isTypeDependent()) {
3225    // Delay type-checking for type-dependent expressions.
3226  } else if (ExprKind == UETT_AlignOf) {
3227    isInvalid = CheckAlignOfExpr(*this, E);
3228  } else if (ExprKind == UETT_VecStep) {
3229    isInvalid = CheckVecStepExpr(E);
3230  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3231    Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3232    isInvalid = true;
3233  } else {
3234    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3235  }
3236
3237  if (isInvalid)
3238    return ExprError();
3239
3240  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3241    PE = TransformToPotentiallyEvaluated(E);
3242    if (PE.isInvalid()) return ExprError();
3243    E = PE.take();
3244  }
3245
3246  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3247  return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3248      ExprKind, E, Context.getSizeType(), OpLoc,
3249      E->getSourceRange().getEnd()));
3250}
3251
3252/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3253/// expr and the same for @c alignof and @c __alignof
3254/// Note that the ArgRange is invalid if isType is false.
3255ExprResult
3256Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3257                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
3258                                    void *TyOrEx, const SourceRange &ArgRange) {
3259  // If error parsing type, ignore.
3260  if (TyOrEx == 0) return ExprError();
3261
3262  if (IsType) {
3263    TypeSourceInfo *TInfo;
3264    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3265    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3266  }
3267
3268  Expr *ArgEx = (Expr *)TyOrEx;
3269  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3270  return Result;
3271}
3272
3273static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3274                                     bool IsReal) {
3275  if (V.get()->isTypeDependent())
3276    return S.Context.DependentTy;
3277
3278  // _Real and _Imag are only l-values for normal l-values.
3279  if (V.get()->getObjectKind() != OK_Ordinary) {
3280    V = S.DefaultLvalueConversion(V.take());
3281    if (V.isInvalid())
3282      return QualType();
3283  }
3284
3285  // These operators return the element type of a complex type.
3286  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3287    return CT->getElementType();
3288
3289  // Otherwise they pass through real integer and floating point types here.
3290  if (V.get()->getType()->isArithmeticType())
3291    return V.get()->getType();
3292
3293  // Test for placeholders.
3294  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3295  if (PR.isInvalid()) return QualType();
3296  if (PR.get() != V.get()) {
3297    V = PR;
3298    return CheckRealImagOperand(S, V, Loc, IsReal);
3299  }
3300
3301  // Reject anything else.
3302  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3303    << (IsReal ? "__real" : "__imag");
3304  return QualType();
3305}
3306
3307
3308
3309ExprResult
3310Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3311                          tok::TokenKind Kind, Expr *Input) {
3312  UnaryOperatorKind Opc;
3313  switch (Kind) {
3314  default: llvm_unreachable("Unknown unary op!");
3315  case tok::plusplus:   Opc = UO_PostInc; break;
3316  case tok::minusminus: Opc = UO_PostDec; break;
3317  }
3318
3319  // Since this might is a postfix expression, get rid of ParenListExprs.
3320  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3321  if (Result.isInvalid()) return ExprError();
3322  Input = Result.take();
3323
3324  return BuildUnaryOp(S, OpLoc, Opc, Input);
3325}
3326
3327/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3328///
3329/// \return true on error
3330static bool checkArithmeticOnObjCPointer(Sema &S,
3331                                         SourceLocation opLoc,
3332                                         Expr *op) {
3333  assert(op->getType()->isObjCObjectPointerType());
3334  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3335    return false;
3336
3337  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3338    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3339    << op->getSourceRange();
3340  return true;
3341}
3342
3343ExprResult
3344Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3345                              Expr *idx, SourceLocation rbLoc) {
3346  // Since this might be a postfix expression, get rid of ParenListExprs.
3347  if (isa<ParenListExpr>(base)) {
3348    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3349    if (result.isInvalid()) return ExprError();
3350    base = result.take();
3351  }
3352
3353  // Handle any non-overload placeholder types in the base and index
3354  // expressions.  We can't handle overloads here because the other
3355  // operand might be an overloadable type, in which case the overload
3356  // resolution for the operator overload should get the first crack
3357  // at the overload.
3358  if (base->getType()->isNonOverloadPlaceholderType()) {
3359    ExprResult result = CheckPlaceholderExpr(base);
3360    if (result.isInvalid()) return ExprError();
3361    base = result.take();
3362  }
3363  if (idx->getType()->isNonOverloadPlaceholderType()) {
3364    ExprResult result = CheckPlaceholderExpr(idx);
3365    if (result.isInvalid()) return ExprError();
3366    idx = result.take();
3367  }
3368
3369  // Build an unanalyzed expression if either operand is type-dependent.
3370  if (getLangOpts().CPlusPlus &&
3371      (base->isTypeDependent() || idx->isTypeDependent())) {
3372    return Owned(new (Context) ArraySubscriptExpr(base, idx,
3373                                                  Context.DependentTy,
3374                                                  VK_LValue, OK_Ordinary,
3375                                                  rbLoc));
3376  }
3377
3378  // Use C++ overloaded-operator rules if either operand has record
3379  // type.  The spec says to do this if either type is *overloadable*,
3380  // but enum types can't declare subscript operators or conversion
3381  // operators, so there's nothing interesting for overload resolution
3382  // to do if there aren't any record types involved.
3383  //
3384  // ObjC pointers have their own subscripting logic that is not tied
3385  // to overload resolution and so should not take this path.
3386  if (getLangOpts().CPlusPlus &&
3387      (base->getType()->isRecordType() ||
3388       (!base->getType()->isObjCObjectPointerType() &&
3389        idx->getType()->isRecordType()))) {
3390    return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3391  }
3392
3393  return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3394}
3395
3396ExprResult
3397Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3398                                      Expr *Idx, SourceLocation RLoc) {
3399  Expr *LHSExp = Base;
3400  Expr *RHSExp = Idx;
3401
3402  // Perform default conversions.
3403  if (!LHSExp->getType()->getAs<VectorType>()) {
3404    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3405    if (Result.isInvalid())
3406      return ExprError();
3407    LHSExp = Result.take();
3408  }
3409  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3410  if (Result.isInvalid())
3411    return ExprError();
3412  RHSExp = Result.take();
3413
3414  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3415  ExprValueKind VK = VK_LValue;
3416  ExprObjectKind OK = OK_Ordinary;
3417
3418  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3419  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3420  // in the subscript position. As a result, we need to derive the array base
3421  // and index from the expression types.
3422  Expr *BaseExpr, *IndexExpr;
3423  QualType ResultType;
3424  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3425    BaseExpr = LHSExp;
3426    IndexExpr = RHSExp;
3427    ResultType = Context.DependentTy;
3428  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3429    BaseExpr = LHSExp;
3430    IndexExpr = RHSExp;
3431    ResultType = PTy->getPointeeType();
3432  } else if (const ObjCObjectPointerType *PTy =
3433               LHSTy->getAs<ObjCObjectPointerType>()) {
3434    BaseExpr = LHSExp;
3435    IndexExpr = RHSExp;
3436
3437    // Use custom logic if this should be the pseudo-object subscript
3438    // expression.
3439    if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3440      return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3441
3442    ResultType = PTy->getPointeeType();
3443    if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3444      Diag(LLoc, diag::err_subscript_nonfragile_interface)
3445        << ResultType << BaseExpr->getSourceRange();
3446      return ExprError();
3447    }
3448  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3449     // Handle the uncommon case of "123[Ptr]".
3450    BaseExpr = RHSExp;
3451    IndexExpr = LHSExp;
3452    ResultType = PTy->getPointeeType();
3453  } else if (const ObjCObjectPointerType *PTy =
3454               RHSTy->getAs<ObjCObjectPointerType>()) {
3455     // Handle the uncommon case of "123[Ptr]".
3456    BaseExpr = RHSExp;
3457    IndexExpr = LHSExp;
3458    ResultType = PTy->getPointeeType();
3459    if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3460      Diag(LLoc, diag::err_subscript_nonfragile_interface)
3461        << ResultType << BaseExpr->getSourceRange();
3462      return ExprError();
3463    }
3464  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3465    BaseExpr = LHSExp;    // vectors: V[123]
3466    IndexExpr = RHSExp;
3467    VK = LHSExp->getValueKind();
3468    if (VK != VK_RValue)
3469      OK = OK_VectorComponent;
3470
3471    // FIXME: need to deal with const...
3472    ResultType = VTy->getElementType();
3473  } else if (LHSTy->isArrayType()) {
3474    // If we see an array that wasn't promoted by
3475    // DefaultFunctionArrayLvalueConversion, it must be an array that
3476    // wasn't promoted because of the C90 rule that doesn't
3477    // allow promoting non-lvalue arrays.  Warn, then
3478    // force the promotion here.
3479    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3480        LHSExp->getSourceRange();
3481    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3482                               CK_ArrayToPointerDecay).take();
3483    LHSTy = LHSExp->getType();
3484
3485    BaseExpr = LHSExp;
3486    IndexExpr = RHSExp;
3487    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3488  } else if (RHSTy->isArrayType()) {
3489    // Same as previous, except for 123[f().a] case
3490    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3491        RHSExp->getSourceRange();
3492    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3493                               CK_ArrayToPointerDecay).take();
3494    RHSTy = RHSExp->getType();
3495
3496    BaseExpr = RHSExp;
3497    IndexExpr = LHSExp;
3498    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3499  } else {
3500    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3501       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3502  }
3503  // C99 6.5.2.1p1
3504  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3505    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3506                     << IndexExpr->getSourceRange());
3507
3508  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3509       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3510         && !IndexExpr->isTypeDependent())
3511    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3512
3513  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3514  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3515  // type. Note that Functions are not objects, and that (in C99 parlance)
3516  // incomplete types are not object types.
3517  if (ResultType->isFunctionType()) {
3518    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3519      << ResultType << BaseExpr->getSourceRange();
3520    return ExprError();
3521  }
3522
3523  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3524    // GNU extension: subscripting on pointer to void
3525    Diag(LLoc, diag::ext_gnu_subscript_void_type)
3526      << BaseExpr->getSourceRange();
3527
3528    // C forbids expressions of unqualified void type from being l-values.
3529    // See IsCForbiddenLValueType.
3530    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3531  } else if (!ResultType->isDependentType() &&
3532      RequireCompleteType(LLoc, ResultType,
3533                          diag::err_subscript_incomplete_type, BaseExpr))
3534    return ExprError();
3535
3536  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3537         !ResultType.isCForbiddenLValueType());
3538
3539  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3540                                                ResultType, VK, OK, RLoc));
3541}
3542
3543ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3544                                        FunctionDecl *FD,
3545                                        ParmVarDecl *Param) {
3546  if (Param->hasUnparsedDefaultArg()) {
3547    Diag(CallLoc,
3548         diag::err_use_of_default_argument_to_function_declared_later) <<
3549      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3550    Diag(UnparsedDefaultArgLocs[Param],
3551         diag::note_default_argument_declared_here);
3552    return ExprError();
3553  }
3554
3555  if (Param->hasUninstantiatedDefaultArg()) {
3556    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3557
3558    EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3559                                                 Param);
3560
3561    // Instantiate the expression.
3562    MultiLevelTemplateArgumentList ArgList
3563      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3564
3565    std::pair<const TemplateArgument *, unsigned> Innermost
3566      = ArgList.getInnermost();
3567    InstantiatingTemplate Inst(*this, CallLoc, Param,
3568                               ArrayRef<TemplateArgument>(Innermost.first,
3569                                                          Innermost.second));
3570    if (Inst)
3571      return ExprError();
3572
3573    ExprResult Result;
3574    {
3575      // C++ [dcl.fct.default]p5:
3576      //   The names in the [default argument] expression are bound, and
3577      //   the semantic constraints are checked, at the point where the
3578      //   default argument expression appears.
3579      ContextRAII SavedContext(*this, FD);
3580      LocalInstantiationScope Local(*this);
3581      Result = SubstExpr(UninstExpr, ArgList);
3582    }
3583    if (Result.isInvalid())
3584      return ExprError();
3585
3586    // Check the expression as an initializer for the parameter.
3587    InitializedEntity Entity
3588      = InitializedEntity::InitializeParameter(Context, Param);
3589    InitializationKind Kind
3590      = InitializationKind::CreateCopy(Param->getLocation(),
3591             /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3592    Expr *ResultE = Result.takeAs<Expr>();
3593
3594    InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3595    Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3596    if (Result.isInvalid())
3597      return ExprError();
3598
3599    Expr *Arg = Result.takeAs<Expr>();
3600    CheckCompletedExpr(Arg, Param->getOuterLocStart());
3601    // Build the default argument expression.
3602    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3603  }
3604
3605  // If the default expression creates temporaries, we need to
3606  // push them to the current stack of expression temporaries so they'll
3607  // be properly destroyed.
3608  // FIXME: We should really be rebuilding the default argument with new
3609  // bound temporaries; see the comment in PR5810.
3610  // We don't need to do that with block decls, though, because
3611  // blocks in default argument expression can never capture anything.
3612  if (isa<ExprWithCleanups>(Param->getInit())) {
3613    // Set the "needs cleanups" bit regardless of whether there are
3614    // any explicit objects.
3615    ExprNeedsCleanups = true;
3616
3617    // Append all the objects to the cleanup list.  Right now, this
3618    // should always be a no-op, because blocks in default argument
3619    // expressions should never be able to capture anything.
3620    assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3621           "default argument expression has capturing blocks?");
3622  }
3623
3624  // We already type-checked the argument, so we know it works.
3625  // Just mark all of the declarations in this potentially-evaluated expression
3626  // as being "referenced".
3627  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3628                                   /*SkipLocalVariables=*/true);
3629  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3630}
3631
3632
3633Sema::VariadicCallType
3634Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3635                          Expr *Fn) {
3636  if (Proto && Proto->isVariadic()) {
3637    if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3638      return VariadicConstructor;
3639    else if (Fn && Fn->getType()->isBlockPointerType())
3640      return VariadicBlock;
3641    else if (FDecl) {
3642      if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3643        if (Method->isInstance())
3644          return VariadicMethod;
3645    }
3646    return VariadicFunction;
3647  }
3648  return VariadicDoesNotApply;
3649}
3650
3651/// ConvertArgumentsForCall - Converts the arguments specified in
3652/// Args/NumArgs to the parameter types of the function FDecl with
3653/// function prototype Proto. Call is the call expression itself, and
3654/// Fn is the function expression. For a C++ member function, this
3655/// routine does not attempt to convert the object argument. Returns
3656/// true if the call is ill-formed.
3657bool
3658Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3659                              FunctionDecl *FDecl,
3660                              const FunctionProtoType *Proto,
3661                              Expr **Args, unsigned NumArgs,
3662                              SourceLocation RParenLoc,
3663                              bool IsExecConfig) {
3664  // Bail out early if calling a builtin with custom typechecking.
3665  // We don't need to do this in the
3666  if (FDecl)
3667    if (unsigned ID = FDecl->getBuiltinID())
3668      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3669        return false;
3670
3671  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3672  // assignment, to the types of the corresponding parameter, ...
3673  unsigned NumArgsInProto = Proto->getNumArgs();
3674  bool Invalid = false;
3675  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3676  unsigned FnKind = Fn->getType()->isBlockPointerType()
3677                       ? 1 /* block */
3678                       : (IsExecConfig ? 3 /* kernel function (exec config) */
3679                                       : 0 /* function */);
3680
3681  // If too few arguments are available (and we don't have default
3682  // arguments for the remaining parameters), don't make the call.
3683  if (NumArgs < NumArgsInProto) {
3684    if (NumArgs < MinArgs) {
3685      if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3686        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3687                          ? diag::err_typecheck_call_too_few_args_one
3688                          : diag::err_typecheck_call_too_few_args_at_least_one)
3689          << FnKind
3690          << FDecl->getParamDecl(0) << Fn->getSourceRange();
3691      else
3692        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3693                          ? diag::err_typecheck_call_too_few_args
3694                          : diag::err_typecheck_call_too_few_args_at_least)
3695          << FnKind
3696          << MinArgs << NumArgs << Fn->getSourceRange();
3697
3698      // Emit the location of the prototype.
3699      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3700        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3701          << FDecl;
3702
3703      return true;
3704    }
3705    Call->setNumArgs(Context, NumArgsInProto);
3706  }
3707
3708  // If too many are passed and not variadic, error on the extras and drop
3709  // them.
3710  if (NumArgs > NumArgsInProto) {
3711    if (!Proto->isVariadic()) {
3712      if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3713        Diag(Args[NumArgsInProto]->getLocStart(),
3714             MinArgs == NumArgsInProto
3715               ? diag::err_typecheck_call_too_many_args_one
3716               : diag::err_typecheck_call_too_many_args_at_most_one)
3717          << FnKind
3718          << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3719          << SourceRange(Args[NumArgsInProto]->getLocStart(),
3720                         Args[NumArgs-1]->getLocEnd());
3721      else
3722        Diag(Args[NumArgsInProto]->getLocStart(),
3723             MinArgs == NumArgsInProto
3724               ? diag::err_typecheck_call_too_many_args
3725               : diag::err_typecheck_call_too_many_args_at_most)
3726          << FnKind
3727          << NumArgsInProto << NumArgs << Fn->getSourceRange()
3728          << SourceRange(Args[NumArgsInProto]->getLocStart(),
3729                         Args[NumArgs-1]->getLocEnd());
3730
3731      // Emit the location of the prototype.
3732      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3733        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3734          << FDecl;
3735
3736      // This deletes the extra arguments.
3737      Call->setNumArgs(Context, NumArgsInProto);
3738      return true;
3739    }
3740  }
3741  SmallVector<Expr *, 8> AllArgs;
3742  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3743
3744  Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3745                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
3746  if (Invalid)
3747    return true;
3748  unsigned TotalNumArgs = AllArgs.size();
3749  for (unsigned i = 0; i < TotalNumArgs; ++i)
3750    Call->setArg(i, AllArgs[i]);
3751
3752  return false;
3753}
3754
3755bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3756                                  FunctionDecl *FDecl,
3757                                  const FunctionProtoType *Proto,
3758                                  unsigned FirstProtoArg,
3759                                  Expr **Args, unsigned NumArgs,
3760                                  SmallVector<Expr *, 8> &AllArgs,
3761                                  VariadicCallType CallType,
3762                                  bool AllowExplicit,
3763                                  bool IsListInitialization) {
3764  unsigned NumArgsInProto = Proto->getNumArgs();
3765  unsigned NumArgsToCheck = NumArgs;
3766  bool Invalid = false;
3767  if (NumArgs != NumArgsInProto)
3768    // Use default arguments for missing arguments
3769    NumArgsToCheck = NumArgsInProto;
3770  unsigned ArgIx = 0;
3771  // Continue to check argument types (even if we have too few/many args).
3772  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3773    QualType ProtoArgType = Proto->getArgType(i);
3774
3775    Expr *Arg;
3776    ParmVarDecl *Param;
3777    if (ArgIx < NumArgs) {
3778      Arg = Args[ArgIx++];
3779
3780      if (RequireCompleteType(Arg->getLocStart(),
3781                              ProtoArgType,
3782                              diag::err_call_incomplete_argument, Arg))
3783        return true;
3784
3785      // Pass the argument
3786      Param = 0;
3787      if (FDecl && i < FDecl->getNumParams())
3788        Param = FDecl->getParamDecl(i);
3789
3790      // Strip the unbridged-cast placeholder expression off, if applicable.
3791      if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3792          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3793          (!Param || !Param->hasAttr<CFConsumedAttr>()))
3794        Arg = stripARCUnbridgedCast(Arg);
3795
3796      InitializedEntity Entity = Param ?
3797          InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3798        : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3799                                                 Proto->isArgConsumed(i));
3800      ExprResult ArgE = PerformCopyInitialization(Entity,
3801                                                  SourceLocation(),
3802                                                  Owned(Arg),
3803                                                  IsListInitialization,
3804                                                  AllowExplicit);
3805      if (ArgE.isInvalid())
3806        return true;
3807
3808      Arg = ArgE.takeAs<Expr>();
3809    } else {
3810      assert(FDecl && "can't use default arguments without a known callee");
3811      Param = FDecl->getParamDecl(i);
3812
3813      ExprResult ArgExpr =
3814        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3815      if (ArgExpr.isInvalid())
3816        return true;
3817
3818      Arg = ArgExpr.takeAs<Expr>();
3819    }
3820
3821    // Check for array bounds violations for each argument to the call. This
3822    // check only triggers warnings when the argument isn't a more complex Expr
3823    // with its own checking, such as a BinaryOperator.
3824    CheckArrayAccess(Arg);
3825
3826    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3827    CheckStaticArrayArgument(CallLoc, Param, Arg);
3828
3829    AllArgs.push_back(Arg);
3830  }
3831
3832  // If this is a variadic call, handle args passed through "...".
3833  if (CallType != VariadicDoesNotApply) {
3834    // Assume that extern "C" functions with variadic arguments that
3835    // return __unknown_anytype aren't *really* variadic.
3836    if (Proto->getResultType() == Context.UnknownAnyTy &&
3837        FDecl && FDecl->isExternC()) {
3838      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3839        QualType paramType; // ignored
3840        ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
3841        Invalid |= arg.isInvalid();
3842        AllArgs.push_back(arg.take());
3843      }
3844
3845    // Otherwise do argument promotion, (C99 6.5.2.2p7).
3846    } else {
3847      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3848        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3849                                                          FDecl);
3850        Invalid |= Arg.isInvalid();
3851        AllArgs.push_back(Arg.take());
3852      }
3853    }
3854
3855    // Check for array bounds violations.
3856    for (unsigned i = ArgIx; i != NumArgs; ++i)
3857      CheckArrayAccess(Args[i]);
3858  }
3859  return Invalid;
3860}
3861
3862static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3863  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3864  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
3865    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3866      << ATL.getLocalSourceRange();
3867}
3868
3869/// CheckStaticArrayArgument - If the given argument corresponds to a static
3870/// array parameter, check that it is non-null, and that if it is formed by
3871/// array-to-pointer decay, the underlying array is sufficiently large.
3872///
3873/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3874/// array type derivation, then for each call to the function, the value of the
3875/// corresponding actual argument shall provide access to the first element of
3876/// an array with at least as many elements as specified by the size expression.
3877void
3878Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3879                               ParmVarDecl *Param,
3880                               const Expr *ArgExpr) {
3881  // Static array parameters are not supported in C++.
3882  if (!Param || getLangOpts().CPlusPlus)
3883    return;
3884
3885  QualType OrigTy = Param->getOriginalType();
3886
3887  const ArrayType *AT = Context.getAsArrayType(OrigTy);
3888  if (!AT || AT->getSizeModifier() != ArrayType::Static)
3889    return;
3890
3891  if (ArgExpr->isNullPointerConstant(Context,
3892                                     Expr::NPC_NeverValueDependent)) {
3893    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3894    DiagnoseCalleeStaticArrayParam(*this, Param);
3895    return;
3896  }
3897
3898  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3899  if (!CAT)
3900    return;
3901
3902  const ConstantArrayType *ArgCAT =
3903    Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3904  if (!ArgCAT)
3905    return;
3906
3907  if (ArgCAT->getSize().ult(CAT->getSize())) {
3908    Diag(CallLoc, diag::warn_static_array_too_small)
3909      << ArgExpr->getSourceRange()
3910      << (unsigned) ArgCAT->getSize().getZExtValue()
3911      << (unsigned) CAT->getSize().getZExtValue();
3912    DiagnoseCalleeStaticArrayParam(*this, Param);
3913  }
3914}
3915
3916/// Given a function expression of unknown-any type, try to rebuild it
3917/// to have a function type.
3918static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3919
3920/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3921/// This provides the location of the left/right parens and a list of comma
3922/// locations.
3923ExprResult
3924Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3925                    MultiExprArg ArgExprs, SourceLocation RParenLoc,
3926                    Expr *ExecConfig, bool IsExecConfig) {
3927  // Since this might be a postfix expression, get rid of ParenListExprs.
3928  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3929  if (Result.isInvalid()) return ExprError();
3930  Fn = Result.take();
3931
3932  if (getLangOpts().CPlusPlus) {
3933    // If this is a pseudo-destructor expression, build the call immediately.
3934    if (isa<CXXPseudoDestructorExpr>(Fn)) {
3935      if (!ArgExprs.empty()) {
3936        // Pseudo-destructor calls should not have any arguments.
3937        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3938          << FixItHint::CreateRemoval(
3939                                    SourceRange(ArgExprs[0]->getLocStart(),
3940                                                ArgExprs.back()->getLocEnd()));
3941      }
3942
3943      return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3944                                          Context.VoidTy, VK_RValue,
3945                                          RParenLoc));
3946    }
3947
3948    // Determine whether this is a dependent call inside a C++ template,
3949    // in which case we won't do any semantic analysis now.
3950    // FIXME: Will need to cache the results of name lookup (including ADL) in
3951    // Fn.
3952    bool Dependent = false;
3953    if (Fn->isTypeDependent())
3954      Dependent = true;
3955    else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3956      Dependent = true;
3957
3958    if (Dependent) {
3959      if (ExecConfig) {
3960        return Owned(new (Context) CUDAKernelCallExpr(
3961            Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3962            Context.DependentTy, VK_RValue, RParenLoc));
3963      } else {
3964        return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3965                                            Context.DependentTy, VK_RValue,
3966                                            RParenLoc));
3967      }
3968    }
3969
3970    // Determine whether this is a call to an object (C++ [over.call.object]).
3971    if (Fn->getType()->isRecordType())
3972      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3973                                                ArgExprs.data(),
3974                                                ArgExprs.size(), RParenLoc));
3975
3976    if (Fn->getType() == Context.UnknownAnyTy) {
3977      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3978      if (result.isInvalid()) return ExprError();
3979      Fn = result.take();
3980    }
3981
3982    if (Fn->getType() == Context.BoundMemberTy) {
3983      return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3984                                       ArgExprs.size(), RParenLoc);
3985    }
3986  }
3987
3988  // Check for overloaded calls.  This can happen even in C due to extensions.
3989  if (Fn->getType() == Context.OverloadTy) {
3990    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3991
3992    // We aren't supposed to apply this logic for if there's an '&' involved.
3993    if (!find.HasFormOfMemberPointer) {
3994      OverloadExpr *ovl = find.Expression;
3995      if (isa<UnresolvedLookupExpr>(ovl)) {
3996        UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3997        return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3998                                       ArgExprs.size(), RParenLoc, ExecConfig);
3999      } else {
4000        return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4001                                         ArgExprs.size(), RParenLoc);
4002      }
4003    }
4004  }
4005
4006  // If we're directly calling a function, get the appropriate declaration.
4007  if (Fn->getType() == Context.UnknownAnyTy) {
4008    ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4009    if (result.isInvalid()) return ExprError();
4010    Fn = result.take();
4011  }
4012
4013  Expr *NakedFn = Fn->IgnoreParens();
4014
4015  NamedDecl *NDecl = 0;
4016  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4017    if (UnOp->getOpcode() == UO_AddrOf)
4018      NakedFn = UnOp->getSubExpr()->IgnoreParens();
4019
4020  if (isa<DeclRefExpr>(NakedFn))
4021    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4022  else if (isa<MemberExpr>(NakedFn))
4023    NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4024
4025  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4026                               ArgExprs.size(), RParenLoc, ExecConfig,
4027                               IsExecConfig);
4028}
4029
4030ExprResult
4031Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4032                              MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4033  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4034  if (!ConfigDecl)
4035    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4036                          << "cudaConfigureCall");
4037  QualType ConfigQTy = ConfigDecl->getType();
4038
4039  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4040      ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4041  MarkFunctionReferenced(LLLLoc, ConfigDecl);
4042
4043  return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4044                       /*IsExecConfig=*/true);
4045}
4046
4047/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4048///
4049/// __builtin_astype( value, dst type )
4050///
4051ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4052                                 SourceLocation BuiltinLoc,
4053                                 SourceLocation RParenLoc) {
4054  ExprValueKind VK = VK_RValue;
4055  ExprObjectKind OK = OK_Ordinary;
4056  QualType DstTy = GetTypeFromParser(ParsedDestTy);
4057  QualType SrcTy = E->getType();
4058  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4059    return ExprError(Diag(BuiltinLoc,
4060                          diag::err_invalid_astype_of_different_size)
4061                     << DstTy
4062                     << SrcTy
4063                     << E->getSourceRange());
4064  return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4065               RParenLoc));
4066}
4067
4068/// BuildResolvedCallExpr - Build a call to a resolved expression,
4069/// i.e. an expression not of \p OverloadTy.  The expression should
4070/// unary-convert to an expression of function-pointer or
4071/// block-pointer type.
4072///
4073/// \param NDecl the declaration being called, if available
4074ExprResult
4075Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4076                            SourceLocation LParenLoc,
4077                            Expr **Args, unsigned NumArgs,
4078                            SourceLocation RParenLoc,
4079                            Expr *Config, bool IsExecConfig) {
4080  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4081  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4082
4083  // Promote the function operand.
4084  // We special-case function promotion here because we only allow promoting
4085  // builtin functions to function pointers in the callee of a call.
4086  ExprResult Result;
4087  if (BuiltinID &&
4088      Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4089    Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4090                               CK_BuiltinFnToFnPtr).take();
4091  } else {
4092    Result = UsualUnaryConversions(Fn);
4093  }
4094  if (Result.isInvalid())
4095    return ExprError();
4096  Fn = Result.take();
4097
4098  // Make the call expr early, before semantic checks.  This guarantees cleanup
4099  // of arguments and function on error.
4100  CallExpr *TheCall;
4101  if (Config)
4102    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4103                                               cast<CallExpr>(Config),
4104                                               llvm::makeArrayRef(Args,NumArgs),
4105                                               Context.BoolTy,
4106                                               VK_RValue,
4107                                               RParenLoc);
4108  else
4109    TheCall = new (Context) CallExpr(Context, Fn,
4110                                     llvm::makeArrayRef(Args, NumArgs),
4111                                     Context.BoolTy,
4112                                     VK_RValue,
4113                                     RParenLoc);
4114
4115  // Bail out early if calling a builtin with custom typechecking.
4116  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4117    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4118
4119 retry:
4120  const FunctionType *FuncT;
4121  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4122    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4123    // have type pointer to function".
4124    FuncT = PT->getPointeeType()->getAs<FunctionType>();
4125    if (FuncT == 0)
4126      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4127                         << Fn->getType() << Fn->getSourceRange());
4128  } else if (const BlockPointerType *BPT =
4129               Fn->getType()->getAs<BlockPointerType>()) {
4130    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4131  } else {
4132    // Handle calls to expressions of unknown-any type.
4133    if (Fn->getType() == Context.UnknownAnyTy) {
4134      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4135      if (rewrite.isInvalid()) return ExprError();
4136      Fn = rewrite.take();
4137      TheCall->setCallee(Fn);
4138      goto retry;
4139    }
4140
4141    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4142      << Fn->getType() << Fn->getSourceRange());
4143  }
4144
4145  if (getLangOpts().CUDA) {
4146    if (Config) {
4147      // CUDA: Kernel calls must be to global functions
4148      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4149        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4150            << FDecl->getName() << Fn->getSourceRange());
4151
4152      // CUDA: Kernel function must have 'void' return type
4153      if (!FuncT->getResultType()->isVoidType())
4154        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4155            << Fn->getType() << Fn->getSourceRange());
4156    } else {
4157      // CUDA: Calls to global functions must be configured
4158      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4159        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4160            << FDecl->getName() << Fn->getSourceRange());
4161    }
4162  }
4163
4164  // Check for a valid return type
4165  if (CheckCallReturnType(FuncT->getResultType(),
4166                          Fn->getLocStart(), TheCall,
4167                          FDecl))
4168    return ExprError();
4169
4170  // We know the result type of the call, set it.
4171  TheCall->setType(FuncT->getCallResultType(Context));
4172  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4173
4174  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4175  if (Proto) {
4176    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4177                                RParenLoc, IsExecConfig))
4178      return ExprError();
4179  } else {
4180    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4181
4182    if (FDecl) {
4183      // Check if we have too few/too many template arguments, based
4184      // on our knowledge of the function definition.
4185      const FunctionDecl *Def = 0;
4186      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4187        Proto = Def->getType()->getAs<FunctionProtoType>();
4188        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4189          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4190            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4191      }
4192
4193      // If the function we're calling isn't a function prototype, but we have
4194      // a function prototype from a prior declaratiom, use that prototype.
4195      if (!FDecl->hasPrototype())
4196        Proto = FDecl->getType()->getAs<FunctionProtoType>();
4197    }
4198
4199    // Promote the arguments (C99 6.5.2.2p6).
4200    for (unsigned i = 0; i != NumArgs; i++) {
4201      Expr *Arg = Args[i];
4202
4203      if (Proto && i < Proto->getNumArgs()) {
4204        InitializedEntity Entity
4205          = InitializedEntity::InitializeParameter(Context,
4206                                                   Proto->getArgType(i),
4207                                                   Proto->isArgConsumed(i));
4208        ExprResult ArgE = PerformCopyInitialization(Entity,
4209                                                    SourceLocation(),
4210                                                    Owned(Arg));
4211        if (ArgE.isInvalid())
4212          return true;
4213
4214        Arg = ArgE.takeAs<Expr>();
4215
4216      } else {
4217        ExprResult ArgE = DefaultArgumentPromotion(Arg);
4218
4219        if (ArgE.isInvalid())
4220          return true;
4221
4222        Arg = ArgE.takeAs<Expr>();
4223      }
4224
4225      if (RequireCompleteType(Arg->getLocStart(),
4226                              Arg->getType(),
4227                              diag::err_call_incomplete_argument, Arg))
4228        return ExprError();
4229
4230      TheCall->setArg(i, Arg);
4231    }
4232  }
4233
4234  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4235    if (!Method->isStatic())
4236      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4237        << Fn->getSourceRange());
4238
4239  // Check for sentinels
4240  if (NDecl)
4241    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4242
4243  // Do special checking on direct calls to functions.
4244  if (FDecl) {
4245    if (CheckFunctionCall(FDecl, TheCall, Proto))
4246      return ExprError();
4247
4248    if (BuiltinID)
4249      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4250  } else if (NDecl) {
4251    if (CheckBlockCall(NDecl, TheCall, Proto))
4252      return ExprError();
4253  }
4254
4255  return MaybeBindToTemporary(TheCall);
4256}
4257
4258ExprResult
4259Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4260                           SourceLocation RParenLoc, Expr *InitExpr) {
4261  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4262  // FIXME: put back this assert when initializers are worked out.
4263  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4264
4265  TypeSourceInfo *TInfo;
4266  QualType literalType = GetTypeFromParser(Ty, &TInfo);
4267  if (!TInfo)
4268    TInfo = Context.getTrivialTypeSourceInfo(literalType);
4269
4270  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4271}
4272
4273ExprResult
4274Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4275                               SourceLocation RParenLoc, Expr *LiteralExpr) {
4276  QualType literalType = TInfo->getType();
4277
4278  if (literalType->isArrayType()) {
4279    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4280          diag::err_illegal_decl_array_incomplete_type,
4281          SourceRange(LParenLoc,
4282                      LiteralExpr->getSourceRange().getEnd())))
4283      return ExprError();
4284    if (literalType->isVariableArrayType())
4285      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4286        << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4287  } else if (!literalType->isDependentType() &&
4288             RequireCompleteType(LParenLoc, literalType,
4289               diag::err_typecheck_decl_incomplete_type,
4290               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4291    return ExprError();
4292
4293  InitializedEntity Entity
4294    = InitializedEntity::InitializeTemporary(literalType);
4295  InitializationKind Kind
4296    = InitializationKind::CreateCStyleCast(LParenLoc,
4297                                           SourceRange(LParenLoc, RParenLoc),
4298                                           /*InitList=*/true);
4299  InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4300  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4301                                      &literalType);
4302  if (Result.isInvalid())
4303    return ExprError();
4304  LiteralExpr = Result.get();
4305
4306  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4307  if (isFileScope) { // 6.5.2.5p3
4308    if (CheckForConstantInitializer(LiteralExpr, literalType))
4309      return ExprError();
4310  }
4311
4312  // In C, compound literals are l-values for some reason.
4313  ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4314
4315  return MaybeBindToTemporary(
4316           new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4317                                             VK, LiteralExpr, isFileScope));
4318}
4319
4320ExprResult
4321Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4322                    SourceLocation RBraceLoc) {
4323  // Immediately handle non-overload placeholders.  Overloads can be
4324  // resolved contextually, but everything else here can't.
4325  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4326    if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4327      ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4328
4329      // Ignore failures; dropping the entire initializer list because
4330      // of one failure would be terrible for indexing/etc.
4331      if (result.isInvalid()) continue;
4332
4333      InitArgList[I] = result.take();
4334    }
4335  }
4336
4337  // Semantic analysis for initializers is done by ActOnDeclarator() and
4338  // CheckInitializer() - it requires knowledge of the object being intialized.
4339
4340  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4341                                               RBraceLoc);
4342  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4343  return Owned(E);
4344}
4345
4346/// Do an explicit extend of the given block pointer if we're in ARC.
4347static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4348  assert(E.get()->getType()->isBlockPointerType());
4349  assert(E.get()->isRValue());
4350
4351  // Only do this in an r-value context.
4352  if (!S.getLangOpts().ObjCAutoRefCount) return;
4353
4354  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4355                               CK_ARCExtendBlockObject, E.get(),
4356                               /*base path*/ 0, VK_RValue);
4357  S.ExprNeedsCleanups = true;
4358}
4359
4360/// Prepare a conversion of the given expression to an ObjC object
4361/// pointer type.
4362CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4363  QualType type = E.get()->getType();
4364  if (type->isObjCObjectPointerType()) {
4365    return CK_BitCast;
4366  } else if (type->isBlockPointerType()) {
4367    maybeExtendBlockObject(*this, E);
4368    return CK_BlockPointerToObjCPointerCast;
4369  } else {
4370    assert(type->isPointerType());
4371    return CK_CPointerToObjCPointerCast;
4372  }
4373}
4374
4375/// Prepares for a scalar cast, performing all the necessary stages
4376/// except the final cast and returning the kind required.
4377CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4378  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4379  // Also, callers should have filtered out the invalid cases with
4380  // pointers.  Everything else should be possible.
4381
4382  QualType SrcTy = Src.get()->getType();
4383  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4384    return CK_NoOp;
4385
4386  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4387  case Type::STK_MemberPointer:
4388    llvm_unreachable("member pointer type in C");
4389
4390  case Type::STK_CPointer:
4391  case Type::STK_BlockPointer:
4392  case Type::STK_ObjCObjectPointer:
4393    switch (DestTy->getScalarTypeKind()) {
4394    case Type::STK_CPointer:
4395      return CK_BitCast;
4396    case Type::STK_BlockPointer:
4397      return (SrcKind == Type::STK_BlockPointer
4398                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4399    case Type::STK_ObjCObjectPointer:
4400      if (SrcKind == Type::STK_ObjCObjectPointer)
4401        return CK_BitCast;
4402      if (SrcKind == Type::STK_CPointer)
4403        return CK_CPointerToObjCPointerCast;
4404      maybeExtendBlockObject(*this, Src);
4405      return CK_BlockPointerToObjCPointerCast;
4406    case Type::STK_Bool:
4407      return CK_PointerToBoolean;
4408    case Type::STK_Integral:
4409      return CK_PointerToIntegral;
4410    case Type::STK_Floating:
4411    case Type::STK_FloatingComplex:
4412    case Type::STK_IntegralComplex:
4413    case Type::STK_MemberPointer:
4414      llvm_unreachable("illegal cast from pointer");
4415    }
4416    llvm_unreachable("Should have returned before this");
4417
4418  case Type::STK_Bool: // casting from bool is like casting from an integer
4419  case Type::STK_Integral:
4420    switch (DestTy->getScalarTypeKind()) {
4421    case Type::STK_CPointer:
4422    case Type::STK_ObjCObjectPointer:
4423    case Type::STK_BlockPointer:
4424      if (Src.get()->isNullPointerConstant(Context,
4425                                           Expr::NPC_ValueDependentIsNull))
4426        return CK_NullToPointer;
4427      return CK_IntegralToPointer;
4428    case Type::STK_Bool:
4429      return CK_IntegralToBoolean;
4430    case Type::STK_Integral:
4431      return CK_IntegralCast;
4432    case Type::STK_Floating:
4433      return CK_IntegralToFloating;
4434    case Type::STK_IntegralComplex:
4435      Src = ImpCastExprToType(Src.take(),
4436                              DestTy->castAs<ComplexType>()->getElementType(),
4437                              CK_IntegralCast);
4438      return CK_IntegralRealToComplex;
4439    case Type::STK_FloatingComplex:
4440      Src = ImpCastExprToType(Src.take(),
4441                              DestTy->castAs<ComplexType>()->getElementType(),
4442                              CK_IntegralToFloating);
4443      return CK_FloatingRealToComplex;
4444    case Type::STK_MemberPointer:
4445      llvm_unreachable("member pointer type in C");
4446    }
4447    llvm_unreachable("Should have returned before this");
4448
4449  case Type::STK_Floating:
4450    switch (DestTy->getScalarTypeKind()) {
4451    case Type::STK_Floating:
4452      return CK_FloatingCast;
4453    case Type::STK_Bool:
4454      return CK_FloatingToBoolean;
4455    case Type::STK_Integral:
4456      return CK_FloatingToIntegral;
4457    case Type::STK_FloatingComplex:
4458      Src = ImpCastExprToType(Src.take(),
4459                              DestTy->castAs<ComplexType>()->getElementType(),
4460                              CK_FloatingCast);
4461      return CK_FloatingRealToComplex;
4462    case Type::STK_IntegralComplex:
4463      Src = ImpCastExprToType(Src.take(),
4464                              DestTy->castAs<ComplexType>()->getElementType(),
4465                              CK_FloatingToIntegral);
4466      return CK_IntegralRealToComplex;
4467    case Type::STK_CPointer:
4468    case Type::STK_ObjCObjectPointer:
4469    case Type::STK_BlockPointer:
4470      llvm_unreachable("valid float->pointer cast?");
4471    case Type::STK_MemberPointer:
4472      llvm_unreachable("member pointer type in C");
4473    }
4474    llvm_unreachable("Should have returned before this");
4475
4476  case Type::STK_FloatingComplex:
4477    switch (DestTy->getScalarTypeKind()) {
4478    case Type::STK_FloatingComplex:
4479      return CK_FloatingComplexCast;
4480    case Type::STK_IntegralComplex:
4481      return CK_FloatingComplexToIntegralComplex;
4482    case Type::STK_Floating: {
4483      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4484      if (Context.hasSameType(ET, DestTy))
4485        return CK_FloatingComplexToReal;
4486      Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4487      return CK_FloatingCast;
4488    }
4489    case Type::STK_Bool:
4490      return CK_FloatingComplexToBoolean;
4491    case Type::STK_Integral:
4492      Src = ImpCastExprToType(Src.take(),
4493                              SrcTy->castAs<ComplexType>()->getElementType(),
4494                              CK_FloatingComplexToReal);
4495      return CK_FloatingToIntegral;
4496    case Type::STK_CPointer:
4497    case Type::STK_ObjCObjectPointer:
4498    case Type::STK_BlockPointer:
4499      llvm_unreachable("valid complex float->pointer cast?");
4500    case Type::STK_MemberPointer:
4501      llvm_unreachable("member pointer type in C");
4502    }
4503    llvm_unreachable("Should have returned before this");
4504
4505  case Type::STK_IntegralComplex:
4506    switch (DestTy->getScalarTypeKind()) {
4507    case Type::STK_FloatingComplex:
4508      return CK_IntegralComplexToFloatingComplex;
4509    case Type::STK_IntegralComplex:
4510      return CK_IntegralComplexCast;
4511    case Type::STK_Integral: {
4512      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4513      if (Context.hasSameType(ET, DestTy))
4514        return CK_IntegralComplexToReal;
4515      Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4516      return CK_IntegralCast;
4517    }
4518    case Type::STK_Bool:
4519      return CK_IntegralComplexToBoolean;
4520    case Type::STK_Floating:
4521      Src = ImpCastExprToType(Src.take(),
4522                              SrcTy->castAs<ComplexType>()->getElementType(),
4523                              CK_IntegralComplexToReal);
4524      return CK_IntegralToFloating;
4525    case Type::STK_CPointer:
4526    case Type::STK_ObjCObjectPointer:
4527    case Type::STK_BlockPointer:
4528      llvm_unreachable("valid complex int->pointer cast?");
4529    case Type::STK_MemberPointer:
4530      llvm_unreachable("member pointer type in C");
4531    }
4532    llvm_unreachable("Should have returned before this");
4533  }
4534
4535  llvm_unreachable("Unhandled scalar cast");
4536}
4537
4538bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4539                           CastKind &Kind) {
4540  assert(VectorTy->isVectorType() && "Not a vector type!");
4541
4542  if (Ty->isVectorType() || Ty->isIntegerType()) {
4543    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4544      return Diag(R.getBegin(),
4545                  Ty->isVectorType() ?
4546                  diag::err_invalid_conversion_between_vectors :
4547                  diag::err_invalid_conversion_between_vector_and_integer)
4548        << VectorTy << Ty << R;
4549  } else
4550    return Diag(R.getBegin(),
4551                diag::err_invalid_conversion_between_vector_and_scalar)
4552      << VectorTy << Ty << R;
4553
4554  Kind = CK_BitCast;
4555  return false;
4556}
4557
4558ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4559                                    Expr *CastExpr, CastKind &Kind) {
4560  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4561
4562  QualType SrcTy = CastExpr->getType();
4563
4564  // If SrcTy is a VectorType, the total size must match to explicitly cast to
4565  // an ExtVectorType.
4566  // In OpenCL, casts between vectors of different types are not allowed.
4567  // (See OpenCL 6.2).
4568  if (SrcTy->isVectorType()) {
4569    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4570        || (getLangOpts().OpenCL &&
4571            (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4572      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4573        << DestTy << SrcTy << R;
4574      return ExprError();
4575    }
4576    Kind = CK_BitCast;
4577    return Owned(CastExpr);
4578  }
4579
4580  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4581  // conversion will take place first from scalar to elt type, and then
4582  // splat from elt type to vector.
4583  if (SrcTy->isPointerType())
4584    return Diag(R.getBegin(),
4585                diag::err_invalid_conversion_between_vector_and_scalar)
4586      << DestTy << SrcTy << R;
4587
4588  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4589  ExprResult CastExprRes = Owned(CastExpr);
4590  CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4591  if (CastExprRes.isInvalid())
4592    return ExprError();
4593  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4594
4595  Kind = CK_VectorSplat;
4596  return Owned(CastExpr);
4597}
4598
4599ExprResult
4600Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4601                    Declarator &D, ParsedType &Ty,
4602                    SourceLocation RParenLoc, Expr *CastExpr) {
4603  assert(!D.isInvalidType() && (CastExpr != 0) &&
4604         "ActOnCastExpr(): missing type or expr");
4605
4606  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4607  if (D.isInvalidType())
4608    return ExprError();
4609
4610  if (getLangOpts().CPlusPlus) {
4611    // Check that there are no default arguments (C++ only).
4612    CheckExtraCXXDefaultArguments(D);
4613  }
4614
4615  checkUnusedDeclAttributes(D);
4616
4617  QualType castType = castTInfo->getType();
4618  Ty = CreateParsedType(castType, castTInfo);
4619
4620  bool isVectorLiteral = false;
4621
4622  // Check for an altivec or OpenCL literal,
4623  // i.e. all the elements are integer constants.
4624  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4625  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4626  if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4627       && castType->isVectorType() && (PE || PLE)) {
4628    if (PLE && PLE->getNumExprs() == 0) {
4629      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4630      return ExprError();
4631    }
4632    if (PE || PLE->getNumExprs() == 1) {
4633      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4634      if (!E->getType()->isVectorType())
4635        isVectorLiteral = true;
4636    }
4637    else
4638      isVectorLiteral = true;
4639  }
4640
4641  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4642  // then handle it as such.
4643  if (isVectorLiteral)
4644    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4645
4646  // If the Expr being casted is a ParenListExpr, handle it specially.
4647  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4648  // sequence of BinOp comma operators.
4649  if (isa<ParenListExpr>(CastExpr)) {
4650    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4651    if (Result.isInvalid()) return ExprError();
4652    CastExpr = Result.take();
4653  }
4654
4655  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4656}
4657
4658ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4659                                    SourceLocation RParenLoc, Expr *E,
4660                                    TypeSourceInfo *TInfo) {
4661  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4662         "Expected paren or paren list expression");
4663
4664  Expr **exprs;
4665  unsigned numExprs;
4666  Expr *subExpr;
4667  SourceLocation LiteralLParenLoc, LiteralRParenLoc;
4668  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4669    LiteralLParenLoc = PE->getLParenLoc();
4670    LiteralRParenLoc = PE->getRParenLoc();
4671    exprs = PE->getExprs();
4672    numExprs = PE->getNumExprs();
4673  } else { // isa<ParenExpr> by assertion at function entrance
4674    LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4675    LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
4676    subExpr = cast<ParenExpr>(E)->getSubExpr();
4677    exprs = &subExpr;
4678    numExprs = 1;
4679  }
4680
4681  QualType Ty = TInfo->getType();
4682  assert(Ty->isVectorType() && "Expected vector type");
4683
4684  SmallVector<Expr *, 8> initExprs;
4685  const VectorType *VTy = Ty->getAs<VectorType>();
4686  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4687
4688  // '(...)' form of vector initialization in AltiVec: the number of
4689  // initializers must be one or must match the size of the vector.
4690  // If a single value is specified in the initializer then it will be
4691  // replicated to all the components of the vector
4692  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4693    // The number of initializers must be one or must match the size of the
4694    // vector. If a single value is specified in the initializer then it will
4695    // be replicated to all the components of the vector
4696    if (numExprs == 1) {
4697      QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4698      ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4699      if (Literal.isInvalid())
4700        return ExprError();
4701      Literal = ImpCastExprToType(Literal.take(), ElemTy,
4702                                  PrepareScalarCast(Literal, ElemTy));
4703      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4704    }
4705    else if (numExprs < numElems) {
4706      Diag(E->getExprLoc(),
4707           diag::err_incorrect_number_of_vector_initializers);
4708      return ExprError();
4709    }
4710    else
4711      initExprs.append(exprs, exprs + numExprs);
4712  }
4713  else {
4714    // For OpenCL, when the number of initializers is a single value,
4715    // it will be replicated to all components of the vector.
4716    if (getLangOpts().OpenCL &&
4717        VTy->getVectorKind() == VectorType::GenericVector &&
4718        numExprs == 1) {
4719        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4720        ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4721        if (Literal.isInvalid())
4722          return ExprError();
4723        Literal = ImpCastExprToType(Literal.take(), ElemTy,
4724                                    PrepareScalarCast(Literal, ElemTy));
4725        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4726    }
4727
4728    initExprs.append(exprs, exprs + numExprs);
4729  }
4730  // FIXME: This means that pretty-printing the final AST will produce curly
4731  // braces instead of the original commas.
4732  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4733                                                   initExprs, LiteralRParenLoc);
4734  initE->setType(Ty);
4735  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4736}
4737
4738/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4739/// the ParenListExpr into a sequence of comma binary operators.
4740ExprResult
4741Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4742  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4743  if (!E)
4744    return Owned(OrigExpr);
4745
4746  ExprResult Result(E->getExpr(0));
4747
4748  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4749    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4750                        E->getExpr(i));
4751
4752  if (Result.isInvalid()) return ExprError();
4753
4754  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4755}
4756
4757ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4758                                    SourceLocation R,
4759                                    MultiExprArg Val) {
4760  Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4761  return Owned(expr);
4762}
4763
4764/// \brief Emit a specialized diagnostic when one expression is a null pointer
4765/// constant and the other is not a pointer.  Returns true if a diagnostic is
4766/// emitted.
4767bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4768                                      SourceLocation QuestionLoc) {
4769  Expr *NullExpr = LHSExpr;
4770  Expr *NonPointerExpr = RHSExpr;
4771  Expr::NullPointerConstantKind NullKind =
4772      NullExpr->isNullPointerConstant(Context,
4773                                      Expr::NPC_ValueDependentIsNotNull);
4774
4775  if (NullKind == Expr::NPCK_NotNull) {
4776    NullExpr = RHSExpr;
4777    NonPointerExpr = LHSExpr;
4778    NullKind =
4779        NullExpr->isNullPointerConstant(Context,
4780                                        Expr::NPC_ValueDependentIsNotNull);
4781  }
4782
4783  if (NullKind == Expr::NPCK_NotNull)
4784    return false;
4785
4786  if (NullKind == Expr::NPCK_ZeroExpression)
4787    return false;
4788
4789  if (NullKind == Expr::NPCK_ZeroLiteral) {
4790    // In this case, check to make sure that we got here from a "NULL"
4791    // string in the source code.
4792    NullExpr = NullExpr->IgnoreParenImpCasts();
4793    SourceLocation loc = NullExpr->getExprLoc();
4794    if (!findMacroSpelling(loc, "NULL"))
4795      return false;
4796  }
4797
4798  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
4799  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4800      << NonPointerExpr->getType() << DiagType
4801      << NonPointerExpr->getSourceRange();
4802  return true;
4803}
4804
4805/// \brief Return false if the condition expression is valid, true otherwise.
4806static bool checkCondition(Sema &S, Expr *Cond) {
4807  QualType CondTy = Cond->getType();
4808
4809  // C99 6.5.15p2
4810  if (CondTy->isScalarType()) return false;
4811
4812  // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4813  if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4814    return false;
4815
4816  // Emit the proper error message.
4817  S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4818                              diag::err_typecheck_cond_expect_scalar :
4819                              diag::err_typecheck_cond_expect_scalar_or_vector)
4820    << CondTy;
4821  return true;
4822}
4823
4824/// \brief Return false if the two expressions can be converted to a vector,
4825/// true otherwise
4826static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4827                                                    ExprResult &RHS,
4828                                                    QualType CondTy) {
4829  // Both operands should be of scalar type.
4830  if (!LHS.get()->getType()->isScalarType()) {
4831    S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4832      << CondTy;
4833    return true;
4834  }
4835  if (!RHS.get()->getType()->isScalarType()) {
4836    S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4837      << CondTy;
4838    return true;
4839  }
4840
4841  // Implicity convert these scalars to the type of the condition.
4842  LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4843  RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4844  return false;
4845}
4846
4847/// \brief Handle when one or both operands are void type.
4848static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4849                                         ExprResult &RHS) {
4850    Expr *LHSExpr = LHS.get();
4851    Expr *RHSExpr = RHS.get();
4852
4853    if (!LHSExpr->getType()->isVoidType())
4854      S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4855        << RHSExpr->getSourceRange();
4856    if (!RHSExpr->getType()->isVoidType())
4857      S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4858        << LHSExpr->getSourceRange();
4859    LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4860    RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4861    return S.Context.VoidTy;
4862}
4863
4864/// \brief Return false if the NullExpr can be promoted to PointerTy,
4865/// true otherwise.
4866static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4867                                        QualType PointerTy) {
4868  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4869      !NullExpr.get()->isNullPointerConstant(S.Context,
4870                                            Expr::NPC_ValueDependentIsNull))
4871    return true;
4872
4873  NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4874  return false;
4875}
4876
4877/// \brief Checks compatibility between two pointers and return the resulting
4878/// type.
4879static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4880                                                     ExprResult &RHS,
4881                                                     SourceLocation Loc) {
4882  QualType LHSTy = LHS.get()->getType();
4883  QualType RHSTy = RHS.get()->getType();
4884
4885  if (S.Context.hasSameType(LHSTy, RHSTy)) {
4886    // Two identical pointers types are always compatible.
4887    return LHSTy;
4888  }
4889
4890  QualType lhptee, rhptee;
4891
4892  // Get the pointee types.
4893  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4894    lhptee = LHSBTy->getPointeeType();
4895    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4896  } else {
4897    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4898    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4899  }
4900
4901  // C99 6.5.15p6: If both operands are pointers to compatible types or to
4902  // differently qualified versions of compatible types, the result type is
4903  // a pointer to an appropriately qualified version of the composite
4904  // type.
4905
4906  // Only CVR-qualifiers exist in the standard, and the differently-qualified
4907  // clause doesn't make sense for our extensions. E.g. address space 2 should
4908  // be incompatible with address space 3: they may live on different devices or
4909  // anything.
4910  Qualifiers lhQual = lhptee.getQualifiers();
4911  Qualifiers rhQual = rhptee.getQualifiers();
4912
4913  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4914  lhQual.removeCVRQualifiers();
4915  rhQual.removeCVRQualifiers();
4916
4917  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4918  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4919
4920  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4921
4922  if (CompositeTy.isNull()) {
4923    S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4924      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4925      << RHS.get()->getSourceRange();
4926    // In this situation, we assume void* type. No especially good
4927    // reason, but this is what gcc does, and we do have to pick
4928    // to get a consistent AST.
4929    QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4930    LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4931    RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4932    return incompatTy;
4933  }
4934
4935  // The pointer types are compatible.
4936  QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4937  ResultTy = S.Context.getPointerType(ResultTy);
4938
4939  LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4940  RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4941  return ResultTy;
4942}
4943
4944/// \brief Return the resulting type when the operands are both block pointers.
4945static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4946                                                          ExprResult &LHS,
4947                                                          ExprResult &RHS,
4948                                                          SourceLocation Loc) {
4949  QualType LHSTy = LHS.get()->getType();
4950  QualType RHSTy = RHS.get()->getType();
4951
4952  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4953    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4954      QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4955      LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4956      RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4957      return destType;
4958    }
4959    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4960      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4961      << RHS.get()->getSourceRange();
4962    return QualType();
4963  }
4964
4965  // We have 2 block pointer types.
4966  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4967}
4968
4969/// \brief Return the resulting type when the operands are both pointers.
4970static QualType
4971checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4972                                            ExprResult &RHS,
4973                                            SourceLocation Loc) {
4974  // get the pointer types
4975  QualType LHSTy = LHS.get()->getType();
4976  QualType RHSTy = RHS.get()->getType();
4977
4978  // get the "pointed to" types
4979  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4980  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4981
4982  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4983  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4984    // Figure out necessary qualifiers (C99 6.5.15p6)
4985    QualType destPointee
4986      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4987    QualType destType = S.Context.getPointerType(destPointee);
4988    // Add qualifiers if necessary.
4989    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4990    // Promote to void*.
4991    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4992    return destType;
4993  }
4994  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4995    QualType destPointee
4996      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4997    QualType destType = S.Context.getPointerType(destPointee);
4998    // Add qualifiers if necessary.
4999    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5000    // Promote to void*.
5001    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5002    return destType;
5003  }
5004
5005  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5006}
5007
5008/// \brief Return false if the first expression is not an integer and the second
5009/// expression is not a pointer, true otherwise.
5010static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5011                                        Expr* PointerExpr, SourceLocation Loc,
5012                                        bool IsIntFirstExpr) {
5013  if (!PointerExpr->getType()->isPointerType() ||
5014      !Int.get()->getType()->isIntegerType())
5015    return false;
5016
5017  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5018  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5019
5020  S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5021    << Expr1->getType() << Expr2->getType()
5022    << Expr1->getSourceRange() << Expr2->getSourceRange();
5023  Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5024                            CK_IntegralToPointer);
5025  return true;
5026}
5027
5028/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5029/// In that case, LHS = cond.
5030/// C99 6.5.15
5031QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5032                                        ExprResult &RHS, ExprValueKind &VK,
5033                                        ExprObjectKind &OK,
5034                                        SourceLocation QuestionLoc) {
5035
5036  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5037  if (!LHSResult.isUsable()) return QualType();
5038  LHS = LHSResult;
5039
5040  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5041  if (!RHSResult.isUsable()) return QualType();
5042  RHS = RHSResult;
5043
5044  // C++ is sufficiently different to merit its own checker.
5045  if (getLangOpts().CPlusPlus)
5046    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5047
5048  VK = VK_RValue;
5049  OK = OK_Ordinary;
5050
5051  Cond = UsualUnaryConversions(Cond.take());
5052  if (Cond.isInvalid())
5053    return QualType();
5054  LHS = UsualUnaryConversions(LHS.take());
5055  if (LHS.isInvalid())
5056    return QualType();
5057  RHS = UsualUnaryConversions(RHS.take());
5058  if (RHS.isInvalid())
5059    return QualType();
5060
5061  QualType CondTy = Cond.get()->getType();
5062  QualType LHSTy = LHS.get()->getType();
5063  QualType RHSTy = RHS.get()->getType();
5064
5065  // first, check the condition.
5066  if (checkCondition(*this, Cond.get()))
5067    return QualType();
5068
5069  // Now check the two expressions.
5070  if (LHSTy->isVectorType() || RHSTy->isVectorType())
5071    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5072
5073  // OpenCL: If the condition is a vector, and both operands are scalar,
5074  // attempt to implicity convert them to the vector type to act like the
5075  // built in select.
5076  if (getLangOpts().OpenCL && CondTy->isVectorType())
5077    if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5078      return QualType();
5079
5080  // If both operands have arithmetic type, do the usual arithmetic conversions
5081  // to find a common type: C99 6.5.15p3,5.
5082  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5083    UsualArithmeticConversions(LHS, RHS);
5084    if (LHS.isInvalid() || RHS.isInvalid())
5085      return QualType();
5086    return LHS.get()->getType();
5087  }
5088
5089  // If both operands are the same structure or union type, the result is that
5090  // type.
5091  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5092    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5093      if (LHSRT->getDecl() == RHSRT->getDecl())
5094        // "If both the operands have structure or union type, the result has
5095        // that type."  This implies that CV qualifiers are dropped.
5096        return LHSTy.getUnqualifiedType();
5097    // FIXME: Type of conditional expression must be complete in C mode.
5098  }
5099
5100  // C99 6.5.15p5: "If both operands have void type, the result has void type."
5101  // The following || allows only one side to be void (a GCC-ism).
5102  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5103    return checkConditionalVoidType(*this, LHS, RHS);
5104  }
5105
5106  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5107  // the type of the other operand."
5108  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5109  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5110
5111  // All objective-c pointer type analysis is done here.
5112  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5113                                                        QuestionLoc);
5114  if (LHS.isInvalid() || RHS.isInvalid())
5115    return QualType();
5116  if (!compositeType.isNull())
5117    return compositeType;
5118
5119
5120  // Handle block pointer types.
5121  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5122    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5123                                                     QuestionLoc);
5124
5125  // Check constraints for C object pointers types (C99 6.5.15p3,6).
5126  if (LHSTy->isPointerType() && RHSTy->isPointerType())
5127    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5128                                                       QuestionLoc);
5129
5130  // GCC compatibility: soften pointer/integer mismatch.  Note that
5131  // null pointers have been filtered out by this point.
5132  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5133      /*isIntFirstExpr=*/true))
5134    return RHSTy;
5135  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5136      /*isIntFirstExpr=*/false))
5137    return LHSTy;
5138
5139  // Emit a better diagnostic if one of the expressions is a null pointer
5140  // constant and the other is not a pointer type. In this case, the user most
5141  // likely forgot to take the address of the other expression.
5142  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5143    return QualType();
5144
5145  // Otherwise, the operands are not compatible.
5146  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5147    << LHSTy << RHSTy << LHS.get()->getSourceRange()
5148    << RHS.get()->getSourceRange();
5149  return QualType();
5150}
5151
5152/// FindCompositeObjCPointerType - Helper method to find composite type of
5153/// two objective-c pointer types of the two input expressions.
5154QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5155                                            SourceLocation QuestionLoc) {
5156  QualType LHSTy = LHS.get()->getType();
5157  QualType RHSTy = RHS.get()->getType();
5158
5159  // Handle things like Class and struct objc_class*.  Here we case the result
5160  // to the pseudo-builtin, because that will be implicitly cast back to the
5161  // redefinition type if an attempt is made to access its fields.
5162  if (LHSTy->isObjCClassType() &&
5163      (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5164    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5165    return LHSTy;
5166  }
5167  if (RHSTy->isObjCClassType() &&
5168      (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5169    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5170    return RHSTy;
5171  }
5172  // And the same for struct objc_object* / id
5173  if (LHSTy->isObjCIdType() &&
5174      (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5175    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5176    return LHSTy;
5177  }
5178  if (RHSTy->isObjCIdType() &&
5179      (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5180    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5181    return RHSTy;
5182  }
5183  // And the same for struct objc_selector* / SEL
5184  if (Context.isObjCSelType(LHSTy) &&
5185      (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5186    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5187    return LHSTy;
5188  }
5189  if (Context.isObjCSelType(RHSTy) &&
5190      (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5191    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5192    return RHSTy;
5193  }
5194  // Check constraints for Objective-C object pointers types.
5195  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5196
5197    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5198      // Two identical object pointer types are always compatible.
5199      return LHSTy;
5200    }
5201    const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5202    const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5203    QualType compositeType = LHSTy;
5204
5205    // If both operands are interfaces and either operand can be
5206    // assigned to the other, use that type as the composite
5207    // type. This allows
5208    //   xxx ? (A*) a : (B*) b
5209    // where B is a subclass of A.
5210    //
5211    // Additionally, as for assignment, if either type is 'id'
5212    // allow silent coercion. Finally, if the types are
5213    // incompatible then make sure to use 'id' as the composite
5214    // type so the result is acceptable for sending messages to.
5215
5216    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5217    // It could return the composite type.
5218    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5219      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5220    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5221      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5222    } else if ((LHSTy->isObjCQualifiedIdType() ||
5223                RHSTy->isObjCQualifiedIdType()) &&
5224               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5225      // Need to handle "id<xx>" explicitly.
5226      // GCC allows qualified id and any Objective-C type to devolve to
5227      // id. Currently localizing to here until clear this should be
5228      // part of ObjCQualifiedIdTypesAreCompatible.
5229      compositeType = Context.getObjCIdType();
5230    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5231      compositeType = Context.getObjCIdType();
5232    } else if (!(compositeType =
5233                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5234      ;
5235    else {
5236      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5237      << LHSTy << RHSTy
5238      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5239      QualType incompatTy = Context.getObjCIdType();
5240      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5241      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5242      return incompatTy;
5243    }
5244    // The object pointer types are compatible.
5245    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5246    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5247    return compositeType;
5248  }
5249  // Check Objective-C object pointer types and 'void *'
5250  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5251    if (getLangOpts().ObjCAutoRefCount) {
5252      // ARC forbids the implicit conversion of object pointers to 'void *',
5253      // so these types are not compatible.
5254      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5255          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5256      LHS = RHS = true;
5257      return QualType();
5258    }
5259    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5260    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5261    QualType destPointee
5262    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5263    QualType destType = Context.getPointerType(destPointee);
5264    // Add qualifiers if necessary.
5265    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5266    // Promote to void*.
5267    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5268    return destType;
5269  }
5270  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5271    if (getLangOpts().ObjCAutoRefCount) {
5272      // ARC forbids the implicit conversion of object pointers to 'void *',
5273      // so these types are not compatible.
5274      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5275          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5276      LHS = RHS = true;
5277      return QualType();
5278    }
5279    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5280    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5281    QualType destPointee
5282    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5283    QualType destType = Context.getPointerType(destPointee);
5284    // Add qualifiers if necessary.
5285    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5286    // Promote to void*.
5287    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5288    return destType;
5289  }
5290  return QualType();
5291}
5292
5293/// SuggestParentheses - Emit a note with a fixit hint that wraps
5294/// ParenRange in parentheses.
5295static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5296                               const PartialDiagnostic &Note,
5297                               SourceRange ParenRange) {
5298  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5299  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5300      EndLoc.isValid()) {
5301    Self.Diag(Loc, Note)
5302      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5303      << FixItHint::CreateInsertion(EndLoc, ")");
5304  } else {
5305    // We can't display the parentheses, so just show the bare note.
5306    Self.Diag(Loc, Note) << ParenRange;
5307  }
5308}
5309
5310static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5311  return Opc >= BO_Mul && Opc <= BO_Shr;
5312}
5313
5314/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5315/// expression, either using a built-in or overloaded operator,
5316/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5317/// expression.
5318static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5319                                   Expr **RHSExprs) {
5320  // Don't strip parenthesis: we should not warn if E is in parenthesis.
5321  E = E->IgnoreImpCasts();
5322  E = E->IgnoreConversionOperator();
5323  E = E->IgnoreImpCasts();
5324
5325  // Built-in binary operator.
5326  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5327    if (IsArithmeticOp(OP->getOpcode())) {
5328      *Opcode = OP->getOpcode();
5329      *RHSExprs = OP->getRHS();
5330      return true;
5331    }
5332  }
5333
5334  // Overloaded operator.
5335  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5336    if (Call->getNumArgs() != 2)
5337      return false;
5338
5339    // Make sure this is really a binary operator that is safe to pass into
5340    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5341    OverloadedOperatorKind OO = Call->getOperator();
5342    if (OO < OO_Plus || OO > OO_Arrow)
5343      return false;
5344
5345    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5346    if (IsArithmeticOp(OpKind)) {
5347      *Opcode = OpKind;
5348      *RHSExprs = Call->getArg(1);
5349      return true;
5350    }
5351  }
5352
5353  return false;
5354}
5355
5356static bool IsLogicOp(BinaryOperatorKind Opc) {
5357  return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5358}
5359
5360/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5361/// or is a logical expression such as (x==y) which has int type, but is
5362/// commonly interpreted as boolean.
5363static bool ExprLooksBoolean(Expr *E) {
5364  E = E->IgnoreParenImpCasts();
5365
5366  if (E->getType()->isBooleanType())
5367    return true;
5368  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5369    return IsLogicOp(OP->getOpcode());
5370  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5371    return OP->getOpcode() == UO_LNot;
5372
5373  return false;
5374}
5375
5376/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5377/// and binary operator are mixed in a way that suggests the programmer assumed
5378/// the conditional operator has higher precedence, for example:
5379/// "int x = a + someBinaryCondition ? 1 : 2".
5380static void DiagnoseConditionalPrecedence(Sema &Self,
5381                                          SourceLocation OpLoc,
5382                                          Expr *Condition,
5383                                          Expr *LHSExpr,
5384                                          Expr *RHSExpr) {
5385  BinaryOperatorKind CondOpcode;
5386  Expr *CondRHS;
5387
5388  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5389    return;
5390  if (!ExprLooksBoolean(CondRHS))
5391    return;
5392
5393  // The condition is an arithmetic binary expression, with a right-
5394  // hand side that looks boolean, so warn.
5395
5396  Self.Diag(OpLoc, diag::warn_precedence_conditional)
5397      << Condition->getSourceRange()
5398      << BinaryOperator::getOpcodeStr(CondOpcode);
5399
5400  SuggestParentheses(Self, OpLoc,
5401    Self.PDiag(diag::note_precedence_silence)
5402      << BinaryOperator::getOpcodeStr(CondOpcode),
5403    SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5404
5405  SuggestParentheses(Self, OpLoc,
5406    Self.PDiag(diag::note_precedence_conditional_first),
5407    SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5408}
5409
5410/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5411/// in the case of a the GNU conditional expr extension.
5412ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5413                                    SourceLocation ColonLoc,
5414                                    Expr *CondExpr, Expr *LHSExpr,
5415                                    Expr *RHSExpr) {
5416  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5417  // was the condition.
5418  OpaqueValueExpr *opaqueValue = 0;
5419  Expr *commonExpr = 0;
5420  if (LHSExpr == 0) {
5421    commonExpr = CondExpr;
5422
5423    // We usually want to apply unary conversions *before* saving, except
5424    // in the special case of a C++ l-value conditional.
5425    if (!(getLangOpts().CPlusPlus
5426          && !commonExpr->isTypeDependent()
5427          && commonExpr->getValueKind() == RHSExpr->getValueKind()
5428          && commonExpr->isGLValue()
5429          && commonExpr->isOrdinaryOrBitFieldObject()
5430          && RHSExpr->isOrdinaryOrBitFieldObject()
5431          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5432      ExprResult commonRes = UsualUnaryConversions(commonExpr);
5433      if (commonRes.isInvalid())
5434        return ExprError();
5435      commonExpr = commonRes.take();
5436    }
5437
5438    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5439                                                commonExpr->getType(),
5440                                                commonExpr->getValueKind(),
5441                                                commonExpr->getObjectKind(),
5442                                                commonExpr);
5443    LHSExpr = CondExpr = opaqueValue;
5444  }
5445
5446  ExprValueKind VK = VK_RValue;
5447  ExprObjectKind OK = OK_Ordinary;
5448  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5449  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5450                                             VK, OK, QuestionLoc);
5451  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5452      RHS.isInvalid())
5453    return ExprError();
5454
5455  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5456                                RHS.get());
5457
5458  if (!commonExpr)
5459    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5460                                                   LHS.take(), ColonLoc,
5461                                                   RHS.take(), result, VK, OK));
5462
5463  return Owned(new (Context)
5464    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5465                              RHS.take(), QuestionLoc, ColonLoc, result, VK,
5466                              OK));
5467}
5468
5469// checkPointerTypesForAssignment - This is a very tricky routine (despite
5470// being closely modeled after the C99 spec:-). The odd characteristic of this
5471// routine is it effectively iqnores the qualifiers on the top level pointee.
5472// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5473// FIXME: add a couple examples in this comment.
5474static Sema::AssignConvertType
5475checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5476  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5477  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5478
5479  // get the "pointed to" type (ignoring qualifiers at the top level)
5480  const Type *lhptee, *rhptee;
5481  Qualifiers lhq, rhq;
5482  llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5483  llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5484
5485  Sema::AssignConvertType ConvTy = Sema::Compatible;
5486
5487  // C99 6.5.16.1p1: This following citation is common to constraints
5488  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5489  // qualifiers of the type *pointed to* by the right;
5490  Qualifiers lq;
5491
5492  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5493  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5494      lhq.compatiblyIncludesObjCLifetime(rhq)) {
5495    // Ignore lifetime for further calculation.
5496    lhq.removeObjCLifetime();
5497    rhq.removeObjCLifetime();
5498  }
5499
5500  if (!lhq.compatiblyIncludes(rhq)) {
5501    // Treat address-space mismatches as fatal.  TODO: address subspaces
5502    if (lhq.getAddressSpace() != rhq.getAddressSpace())
5503      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5504
5505    // It's okay to add or remove GC or lifetime qualifiers when converting to
5506    // and from void*.
5507    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5508                        .compatiblyIncludes(
5509                                rhq.withoutObjCGCAttr().withoutObjCLifetime())
5510             && (lhptee->isVoidType() || rhptee->isVoidType()))
5511      ; // keep old
5512
5513    // Treat lifetime mismatches as fatal.
5514    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5515      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5516
5517    // For GCC compatibility, other qualifier mismatches are treated
5518    // as still compatible in C.
5519    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5520  }
5521
5522  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5523  // incomplete type and the other is a pointer to a qualified or unqualified
5524  // version of void...
5525  if (lhptee->isVoidType()) {
5526    if (rhptee->isIncompleteOrObjectType())
5527      return ConvTy;
5528
5529    // As an extension, we allow cast to/from void* to function pointer.
5530    assert(rhptee->isFunctionType());
5531    return Sema::FunctionVoidPointer;
5532  }
5533
5534  if (rhptee->isVoidType()) {
5535    if (lhptee->isIncompleteOrObjectType())
5536      return ConvTy;
5537
5538    // As an extension, we allow cast to/from void* to function pointer.
5539    assert(lhptee->isFunctionType());
5540    return Sema::FunctionVoidPointer;
5541  }
5542
5543  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5544  // unqualified versions of compatible types, ...
5545  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5546  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5547    // Check if the pointee types are compatible ignoring the sign.
5548    // We explicitly check for char so that we catch "char" vs
5549    // "unsigned char" on systems where "char" is unsigned.
5550    if (lhptee->isCharType())
5551      ltrans = S.Context.UnsignedCharTy;
5552    else if (lhptee->hasSignedIntegerRepresentation())
5553      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5554
5555    if (rhptee->isCharType())
5556      rtrans = S.Context.UnsignedCharTy;
5557    else if (rhptee->hasSignedIntegerRepresentation())
5558      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5559
5560    if (ltrans == rtrans) {
5561      // Types are compatible ignoring the sign. Qualifier incompatibility
5562      // takes priority over sign incompatibility because the sign
5563      // warning can be disabled.
5564      if (ConvTy != Sema::Compatible)
5565        return ConvTy;
5566
5567      return Sema::IncompatiblePointerSign;
5568    }
5569
5570    // If we are a multi-level pointer, it's possible that our issue is simply
5571    // one of qualification - e.g. char ** -> const char ** is not allowed. If
5572    // the eventual target type is the same and the pointers have the same
5573    // level of indirection, this must be the issue.
5574    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5575      do {
5576        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5577        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5578      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5579
5580      if (lhptee == rhptee)
5581        return Sema::IncompatibleNestedPointerQualifiers;
5582    }
5583
5584    // General pointer incompatibility takes priority over qualifiers.
5585    return Sema::IncompatiblePointer;
5586  }
5587  if (!S.getLangOpts().CPlusPlus &&
5588      S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5589    return Sema::IncompatiblePointer;
5590  return ConvTy;
5591}
5592
5593/// checkBlockPointerTypesForAssignment - This routine determines whether two
5594/// block pointer types are compatible or whether a block and normal pointer
5595/// are compatible. It is more restrict than comparing two function pointer
5596// types.
5597static Sema::AssignConvertType
5598checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5599                                    QualType RHSType) {
5600  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5601  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5602
5603  QualType lhptee, rhptee;
5604
5605  // get the "pointed to" type (ignoring qualifiers at the top level)
5606  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5607  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5608
5609  // In C++, the types have to match exactly.
5610  if (S.getLangOpts().CPlusPlus)
5611    return Sema::IncompatibleBlockPointer;
5612
5613  Sema::AssignConvertType ConvTy = Sema::Compatible;
5614
5615  // For blocks we enforce that qualifiers are identical.
5616  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5617    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5618
5619  if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5620    return Sema::IncompatibleBlockPointer;
5621
5622  return ConvTy;
5623}
5624
5625/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5626/// for assignment compatibility.
5627static Sema::AssignConvertType
5628checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5629                                   QualType RHSType) {
5630  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5631  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5632
5633  if (LHSType->isObjCBuiltinType()) {
5634    // Class is not compatible with ObjC object pointers.
5635    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5636        !RHSType->isObjCQualifiedClassType())
5637      return Sema::IncompatiblePointer;
5638    return Sema::Compatible;
5639  }
5640  if (RHSType->isObjCBuiltinType()) {
5641    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5642        !LHSType->isObjCQualifiedClassType())
5643      return Sema::IncompatiblePointer;
5644    return Sema::Compatible;
5645  }
5646  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5647  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5648
5649  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5650      // make an exception for id<P>
5651      !LHSType->isObjCQualifiedIdType())
5652    return Sema::CompatiblePointerDiscardsQualifiers;
5653
5654  if (S.Context.typesAreCompatible(LHSType, RHSType))
5655    return Sema::Compatible;
5656  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5657    return Sema::IncompatibleObjCQualifiedId;
5658  return Sema::IncompatiblePointer;
5659}
5660
5661Sema::AssignConvertType
5662Sema::CheckAssignmentConstraints(SourceLocation Loc,
5663                                 QualType LHSType, QualType RHSType) {
5664  // Fake up an opaque expression.  We don't actually care about what
5665  // cast operations are required, so if CheckAssignmentConstraints
5666  // adds casts to this they'll be wasted, but fortunately that doesn't
5667  // usually happen on valid code.
5668  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5669  ExprResult RHSPtr = &RHSExpr;
5670  CastKind K = CK_Invalid;
5671
5672  return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5673}
5674
5675/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5676/// has code to accommodate several GCC extensions when type checking
5677/// pointers. Here are some objectionable examples that GCC considers warnings:
5678///
5679///  int a, *pint;
5680///  short *pshort;
5681///  struct foo *pfoo;
5682///
5683///  pint = pshort; // warning: assignment from incompatible pointer type
5684///  a = pint; // warning: assignment makes integer from pointer without a cast
5685///  pint = a; // warning: assignment makes pointer from integer without a cast
5686///  pint = pfoo; // warning: assignment from incompatible pointer type
5687///
5688/// As a result, the code for dealing with pointers is more complex than the
5689/// C99 spec dictates.
5690///
5691/// Sets 'Kind' for any result kind except Incompatible.
5692Sema::AssignConvertType
5693Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5694                                 CastKind &Kind) {
5695  QualType RHSType = RHS.get()->getType();
5696  QualType OrigLHSType = LHSType;
5697
5698  // Get canonical types.  We're not formatting these types, just comparing
5699  // them.
5700  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5701  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5702
5703  // Common case: no conversion required.
5704  if (LHSType == RHSType) {
5705    Kind = CK_NoOp;
5706    return Compatible;
5707  }
5708
5709  // If we have an atomic type, try a non-atomic assignment, then just add an
5710  // atomic qualification step.
5711  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5712    Sema::AssignConvertType result =
5713      CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5714    if (result != Compatible)
5715      return result;
5716    if (Kind != CK_NoOp)
5717      RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5718    Kind = CK_NonAtomicToAtomic;
5719    return Compatible;
5720  }
5721
5722  // If the left-hand side is a reference type, then we are in a
5723  // (rare!) case where we've allowed the use of references in C,
5724  // e.g., as a parameter type in a built-in function. In this case,
5725  // just make sure that the type referenced is compatible with the
5726  // right-hand side type. The caller is responsible for adjusting
5727  // LHSType so that the resulting expression does not have reference
5728  // type.
5729  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5730    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5731      Kind = CK_LValueBitCast;
5732      return Compatible;
5733    }
5734    return Incompatible;
5735  }
5736
5737  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5738  // to the same ExtVector type.
5739  if (LHSType->isExtVectorType()) {
5740    if (RHSType->isExtVectorType())
5741      return Incompatible;
5742    if (RHSType->isArithmeticType()) {
5743      // CK_VectorSplat does T -> vector T, so first cast to the
5744      // element type.
5745      QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5746      if (elType != RHSType) {
5747        Kind = PrepareScalarCast(RHS, elType);
5748        RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5749      }
5750      Kind = CK_VectorSplat;
5751      return Compatible;
5752    }
5753  }
5754
5755  // Conversions to or from vector type.
5756  if (LHSType->isVectorType() || RHSType->isVectorType()) {
5757    if (LHSType->isVectorType() && RHSType->isVectorType()) {
5758      // Allow assignments of an AltiVec vector type to an equivalent GCC
5759      // vector type and vice versa
5760      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5761        Kind = CK_BitCast;
5762        return Compatible;
5763      }
5764
5765      // If we are allowing lax vector conversions, and LHS and RHS are both
5766      // vectors, the total size only needs to be the same. This is a bitcast;
5767      // no bits are changed but the result type is different.
5768      if (getLangOpts().LaxVectorConversions &&
5769          (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5770        Kind = CK_BitCast;
5771        return IncompatibleVectors;
5772      }
5773    }
5774    return Incompatible;
5775  }
5776
5777  // Arithmetic conversions.
5778  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5779      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5780    Kind = PrepareScalarCast(RHS, LHSType);
5781    return Compatible;
5782  }
5783
5784  // Conversions to normal pointers.
5785  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5786    // U* -> T*
5787    if (isa<PointerType>(RHSType)) {
5788      Kind = CK_BitCast;
5789      return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5790    }
5791
5792    // int -> T*
5793    if (RHSType->isIntegerType()) {
5794      Kind = CK_IntegralToPointer; // FIXME: null?
5795      return IntToPointer;
5796    }
5797
5798    // C pointers are not compatible with ObjC object pointers,
5799    // with two exceptions:
5800    if (isa<ObjCObjectPointerType>(RHSType)) {
5801      //  - conversions to void*
5802      if (LHSPointer->getPointeeType()->isVoidType()) {
5803        Kind = CK_BitCast;
5804        return Compatible;
5805      }
5806
5807      //  - conversions from 'Class' to the redefinition type
5808      if (RHSType->isObjCClassType() &&
5809          Context.hasSameType(LHSType,
5810                              Context.getObjCClassRedefinitionType())) {
5811        Kind = CK_BitCast;
5812        return Compatible;
5813      }
5814
5815      Kind = CK_BitCast;
5816      return IncompatiblePointer;
5817    }
5818
5819    // U^ -> void*
5820    if (RHSType->getAs<BlockPointerType>()) {
5821      if (LHSPointer->getPointeeType()->isVoidType()) {
5822        Kind = CK_BitCast;
5823        return Compatible;
5824      }
5825    }
5826
5827    return Incompatible;
5828  }
5829
5830  // Conversions to block pointers.
5831  if (isa<BlockPointerType>(LHSType)) {
5832    // U^ -> T^
5833    if (RHSType->isBlockPointerType()) {
5834      Kind = CK_BitCast;
5835      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5836    }
5837
5838    // int or null -> T^
5839    if (RHSType->isIntegerType()) {
5840      Kind = CK_IntegralToPointer; // FIXME: null
5841      return IntToBlockPointer;
5842    }
5843
5844    // id -> T^
5845    if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5846      Kind = CK_AnyPointerToBlockPointerCast;
5847      return Compatible;
5848    }
5849
5850    // void* -> T^
5851    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5852      if (RHSPT->getPointeeType()->isVoidType()) {
5853        Kind = CK_AnyPointerToBlockPointerCast;
5854        return Compatible;
5855      }
5856
5857    return Incompatible;
5858  }
5859
5860  // Conversions to Objective-C pointers.
5861  if (isa<ObjCObjectPointerType>(LHSType)) {
5862    // A* -> B*
5863    if (RHSType->isObjCObjectPointerType()) {
5864      Kind = CK_BitCast;
5865      Sema::AssignConvertType result =
5866        checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5867      if (getLangOpts().ObjCAutoRefCount &&
5868          result == Compatible &&
5869          !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5870        result = IncompatibleObjCWeakRef;
5871      return result;
5872    }
5873
5874    // int or null -> A*
5875    if (RHSType->isIntegerType()) {
5876      Kind = CK_IntegralToPointer; // FIXME: null
5877      return IntToPointer;
5878    }
5879
5880    // In general, C pointers are not compatible with ObjC object pointers,
5881    // with two exceptions:
5882    if (isa<PointerType>(RHSType)) {
5883      Kind = CK_CPointerToObjCPointerCast;
5884
5885      //  - conversions from 'void*'
5886      if (RHSType->isVoidPointerType()) {
5887        return Compatible;
5888      }
5889
5890      //  - conversions to 'Class' from its redefinition type
5891      if (LHSType->isObjCClassType() &&
5892          Context.hasSameType(RHSType,
5893                              Context.getObjCClassRedefinitionType())) {
5894        return Compatible;
5895      }
5896
5897      return IncompatiblePointer;
5898    }
5899
5900    // T^ -> A*
5901    if (RHSType->isBlockPointerType()) {
5902      maybeExtendBlockObject(*this, RHS);
5903      Kind = CK_BlockPointerToObjCPointerCast;
5904      return Compatible;
5905    }
5906
5907    return Incompatible;
5908  }
5909
5910  // Conversions from pointers that are not covered by the above.
5911  if (isa<PointerType>(RHSType)) {
5912    // T* -> _Bool
5913    if (LHSType == Context.BoolTy) {
5914      Kind = CK_PointerToBoolean;
5915      return Compatible;
5916    }
5917
5918    // T* -> int
5919    if (LHSType->isIntegerType()) {
5920      Kind = CK_PointerToIntegral;
5921      return PointerToInt;
5922    }
5923
5924    return Incompatible;
5925  }
5926
5927  // Conversions from Objective-C pointers that are not covered by the above.
5928  if (isa<ObjCObjectPointerType>(RHSType)) {
5929    // T* -> _Bool
5930    if (LHSType == Context.BoolTy) {
5931      Kind = CK_PointerToBoolean;
5932      return Compatible;
5933    }
5934
5935    // T* -> int
5936    if (LHSType->isIntegerType()) {
5937      Kind = CK_PointerToIntegral;
5938      return PointerToInt;
5939    }
5940
5941    return Incompatible;
5942  }
5943
5944  // struct A -> struct B
5945  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5946    if (Context.typesAreCompatible(LHSType, RHSType)) {
5947      Kind = CK_NoOp;
5948      return Compatible;
5949    }
5950  }
5951
5952  return Incompatible;
5953}
5954
5955/// \brief Constructs a transparent union from an expression that is
5956/// used to initialize the transparent union.
5957static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5958                                      ExprResult &EResult, QualType UnionType,
5959                                      FieldDecl *Field) {
5960  // Build an initializer list that designates the appropriate member
5961  // of the transparent union.
5962  Expr *E = EResult.take();
5963  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5964                                                   E, SourceLocation());
5965  Initializer->setType(UnionType);
5966  Initializer->setInitializedFieldInUnion(Field);
5967
5968  // Build a compound literal constructing a value of the transparent
5969  // union type from this initializer list.
5970  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5971  EResult = S.Owned(
5972    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5973                                VK_RValue, Initializer, false));
5974}
5975
5976Sema::AssignConvertType
5977Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5978                                               ExprResult &RHS) {
5979  QualType RHSType = RHS.get()->getType();
5980
5981  // If the ArgType is a Union type, we want to handle a potential
5982  // transparent_union GCC extension.
5983  const RecordType *UT = ArgType->getAsUnionType();
5984  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5985    return Incompatible;
5986
5987  // The field to initialize within the transparent union.
5988  RecordDecl *UD = UT->getDecl();
5989  FieldDecl *InitField = 0;
5990  // It's compatible if the expression matches any of the fields.
5991  for (RecordDecl::field_iterator it = UD->field_begin(),
5992         itend = UD->field_end();
5993       it != itend; ++it) {
5994    if (it->getType()->isPointerType()) {
5995      // If the transparent union contains a pointer type, we allow:
5996      // 1) void pointer
5997      // 2) null pointer constant
5998      if (RHSType->isPointerType())
5999        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6000          RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6001          InitField = *it;
6002          break;
6003        }
6004
6005      if (RHS.get()->isNullPointerConstant(Context,
6006                                           Expr::NPC_ValueDependentIsNull)) {
6007        RHS = ImpCastExprToType(RHS.take(), it->getType(),
6008                                CK_NullToPointer);
6009        InitField = *it;
6010        break;
6011      }
6012    }
6013
6014    CastKind Kind = CK_Invalid;
6015    if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6016          == Compatible) {
6017      RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6018      InitField = *it;
6019      break;
6020    }
6021  }
6022
6023  if (!InitField)
6024    return Incompatible;
6025
6026  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6027  return Compatible;
6028}
6029
6030Sema::AssignConvertType
6031Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6032                                       bool Diagnose) {
6033  if (getLangOpts().CPlusPlus) {
6034    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6035      // C++ 5.17p3: If the left operand is not of class type, the
6036      // expression is implicitly converted (C++ 4) to the
6037      // cv-unqualified type of the left operand.
6038      ExprResult Res;
6039      if (Diagnose) {
6040        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6041                                        AA_Assigning);
6042      } else {
6043        ImplicitConversionSequence ICS =
6044            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6045                                  /*SuppressUserConversions=*/false,
6046                                  /*AllowExplicit=*/false,
6047                                  /*InOverloadResolution=*/false,
6048                                  /*CStyle=*/false,
6049                                  /*AllowObjCWritebackConversion=*/false);
6050        if (ICS.isFailure())
6051          return Incompatible;
6052        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6053                                        ICS, AA_Assigning);
6054      }
6055      if (Res.isInvalid())
6056        return Incompatible;
6057      Sema::AssignConvertType result = Compatible;
6058      if (getLangOpts().ObjCAutoRefCount &&
6059          !CheckObjCARCUnavailableWeakConversion(LHSType,
6060                                                 RHS.get()->getType()))
6061        result = IncompatibleObjCWeakRef;
6062      RHS = Res;
6063      return result;
6064    }
6065
6066    // FIXME: Currently, we fall through and treat C++ classes like C
6067    // structures.
6068    // FIXME: We also fall through for atomics; not sure what should
6069    // happen there, though.
6070  }
6071
6072  // C99 6.5.16.1p1: the left operand is a pointer and the right is
6073  // a null pointer constant.
6074  if ((LHSType->isPointerType() ||
6075       LHSType->isObjCObjectPointerType() ||
6076       LHSType->isBlockPointerType())
6077      && RHS.get()->isNullPointerConstant(Context,
6078                                          Expr::NPC_ValueDependentIsNull)) {
6079    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6080    return Compatible;
6081  }
6082
6083  // This check seems unnatural, however it is necessary to ensure the proper
6084  // conversion of functions/arrays. If the conversion were done for all
6085  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6086  // expressions that suppress this implicit conversion (&, sizeof).
6087  //
6088  // Suppress this for references: C++ 8.5.3p5.
6089  if (!LHSType->isReferenceType()) {
6090    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6091    if (RHS.isInvalid())
6092      return Incompatible;
6093  }
6094
6095  CastKind Kind = CK_Invalid;
6096  Sema::AssignConvertType result =
6097    CheckAssignmentConstraints(LHSType, RHS, Kind);
6098
6099  // C99 6.5.16.1p2: The value of the right operand is converted to the
6100  // type of the assignment expression.
6101  // CheckAssignmentConstraints allows the left-hand side to be a reference,
6102  // so that we can use references in built-in functions even in C.
6103  // The getNonReferenceType() call makes sure that the resulting expression
6104  // does not have reference type.
6105  if (result != Incompatible && RHS.get()->getType() != LHSType)
6106    RHS = ImpCastExprToType(RHS.take(),
6107                            LHSType.getNonLValueExprType(Context), Kind);
6108  return result;
6109}
6110
6111QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6112                               ExprResult &RHS) {
6113  Diag(Loc, diag::err_typecheck_invalid_operands)
6114    << LHS.get()->getType() << RHS.get()->getType()
6115    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6116  return QualType();
6117}
6118
6119QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6120                                   SourceLocation Loc, bool IsCompAssign) {
6121  if (!IsCompAssign) {
6122    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6123    if (LHS.isInvalid())
6124      return QualType();
6125  }
6126  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6127  if (RHS.isInvalid())
6128    return QualType();
6129
6130  // For conversion purposes, we ignore any qualifiers.
6131  // For example, "const float" and "float" are equivalent.
6132  QualType LHSType =
6133    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6134  QualType RHSType =
6135    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6136
6137  // If the vector types are identical, return.
6138  if (LHSType == RHSType)
6139    return LHSType;
6140
6141  // Handle the case of equivalent AltiVec and GCC vector types
6142  if (LHSType->isVectorType() && RHSType->isVectorType() &&
6143      Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6144    if (LHSType->isExtVectorType()) {
6145      RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6146      return LHSType;
6147    }
6148
6149    if (!IsCompAssign)
6150      LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6151    return RHSType;
6152  }
6153
6154  if (getLangOpts().LaxVectorConversions &&
6155      Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6156    // If we are allowing lax vector conversions, and LHS and RHS are both
6157    // vectors, the total size only needs to be the same. This is a
6158    // bitcast; no bits are changed but the result type is different.
6159    // FIXME: Should we really be allowing this?
6160    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6161    return LHSType;
6162  }
6163
6164  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6165  // swap back (so that we don't reverse the inputs to a subtract, for instance.
6166  bool swapped = false;
6167  if (RHSType->isExtVectorType() && !IsCompAssign) {
6168    swapped = true;
6169    std::swap(RHS, LHS);
6170    std::swap(RHSType, LHSType);
6171  }
6172
6173  // Handle the case of an ext vector and scalar.
6174  if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6175    QualType EltTy = LV->getElementType();
6176    if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6177      int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6178      if (order > 0)
6179        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6180      if (order >= 0) {
6181        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6182        if (swapped) std::swap(RHS, LHS);
6183        return LHSType;
6184      }
6185    }
6186    if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6187        RHSType->isRealFloatingType()) {
6188      int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6189      if (order > 0)
6190        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6191      if (order >= 0) {
6192        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6193        if (swapped) std::swap(RHS, LHS);
6194        return LHSType;
6195      }
6196    }
6197  }
6198
6199  // Vectors of different size or scalar and non-ext-vector are errors.
6200  if (swapped) std::swap(RHS, LHS);
6201  Diag(Loc, diag::err_typecheck_vector_not_convertable)
6202    << LHS.get()->getType() << RHS.get()->getType()
6203    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6204  return QualType();
6205}
6206
6207// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6208// expression.  These are mainly cases where the null pointer is used as an
6209// integer instead of a pointer.
6210static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6211                                SourceLocation Loc, bool IsCompare) {
6212  // The canonical way to check for a GNU null is with isNullPointerConstant,
6213  // but we use a bit of a hack here for speed; this is a relatively
6214  // hot path, and isNullPointerConstant is slow.
6215  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6216  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6217
6218  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6219
6220  // Avoid analyzing cases where the result will either be invalid (and
6221  // diagnosed as such) or entirely valid and not something to warn about.
6222  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6223      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6224    return;
6225
6226  // Comparison operations would not make sense with a null pointer no matter
6227  // what the other expression is.
6228  if (!IsCompare) {
6229    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6230        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6231        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6232    return;
6233  }
6234
6235  // The rest of the operations only make sense with a null pointer
6236  // if the other expression is a pointer.
6237  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6238      NonNullType->canDecayToPointerType())
6239    return;
6240
6241  S.Diag(Loc, diag::warn_null_in_comparison_operation)
6242      << LHSNull /* LHS is NULL */ << NonNullType
6243      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6244}
6245
6246QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6247                                           SourceLocation Loc,
6248                                           bool IsCompAssign, bool IsDiv) {
6249  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6250
6251  if (LHS.get()->getType()->isVectorType() ||
6252      RHS.get()->getType()->isVectorType())
6253    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6254
6255  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6256  if (LHS.isInvalid() || RHS.isInvalid())
6257    return QualType();
6258
6259
6260  if (compType.isNull() || !compType->isArithmeticType())
6261    return InvalidOperands(Loc, LHS, RHS);
6262
6263  // Check for division by zero.
6264  if (IsDiv &&
6265      RHS.get()->isNullPointerConstant(Context,
6266                                       Expr::NPC_ValueDependentIsNotNull))
6267    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6268                                          << RHS.get()->getSourceRange());
6269
6270  return compType;
6271}
6272
6273QualType Sema::CheckRemainderOperands(
6274  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6275  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6276
6277  if (LHS.get()->getType()->isVectorType() ||
6278      RHS.get()->getType()->isVectorType()) {
6279    if (LHS.get()->getType()->hasIntegerRepresentation() &&
6280        RHS.get()->getType()->hasIntegerRepresentation())
6281      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6282    return InvalidOperands(Loc, LHS, RHS);
6283  }
6284
6285  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6286  if (LHS.isInvalid() || RHS.isInvalid())
6287    return QualType();
6288
6289  if (compType.isNull() || !compType->isIntegerType())
6290    return InvalidOperands(Loc, LHS, RHS);
6291
6292  // Check for remainder by zero.
6293  if (RHS.get()->isNullPointerConstant(Context,
6294                                       Expr::NPC_ValueDependentIsNotNull))
6295    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6296                                 << RHS.get()->getSourceRange());
6297
6298  return compType;
6299}
6300
6301/// \brief Diagnose invalid arithmetic on two void pointers.
6302static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6303                                                Expr *LHSExpr, Expr *RHSExpr) {
6304  S.Diag(Loc, S.getLangOpts().CPlusPlus
6305                ? diag::err_typecheck_pointer_arith_void_type
6306                : diag::ext_gnu_void_ptr)
6307    << 1 /* two pointers */ << LHSExpr->getSourceRange()
6308                            << RHSExpr->getSourceRange();
6309}
6310
6311/// \brief Diagnose invalid arithmetic on a void pointer.
6312static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6313                                            Expr *Pointer) {
6314  S.Diag(Loc, S.getLangOpts().CPlusPlus
6315                ? diag::err_typecheck_pointer_arith_void_type
6316                : diag::ext_gnu_void_ptr)
6317    << 0 /* one pointer */ << Pointer->getSourceRange();
6318}
6319
6320/// \brief Diagnose invalid arithmetic on two function pointers.
6321static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6322                                                    Expr *LHS, Expr *RHS) {
6323  assert(LHS->getType()->isAnyPointerType());
6324  assert(RHS->getType()->isAnyPointerType());
6325  S.Diag(Loc, S.getLangOpts().CPlusPlus
6326                ? diag::err_typecheck_pointer_arith_function_type
6327                : diag::ext_gnu_ptr_func_arith)
6328    << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6329    // We only show the second type if it differs from the first.
6330    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6331                                                   RHS->getType())
6332    << RHS->getType()->getPointeeType()
6333    << LHS->getSourceRange() << RHS->getSourceRange();
6334}
6335
6336/// \brief Diagnose invalid arithmetic on a function pointer.
6337static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6338                                                Expr *Pointer) {
6339  assert(Pointer->getType()->isAnyPointerType());
6340  S.Diag(Loc, S.getLangOpts().CPlusPlus
6341                ? diag::err_typecheck_pointer_arith_function_type
6342                : diag::ext_gnu_ptr_func_arith)
6343    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6344    << 0 /* one pointer, so only one type */
6345    << Pointer->getSourceRange();
6346}
6347
6348/// \brief Emit error if Operand is incomplete pointer type
6349///
6350/// \returns True if pointer has incomplete type
6351static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6352                                                 Expr *Operand) {
6353  assert(Operand->getType()->isAnyPointerType() &&
6354         !Operand->getType()->isDependentType());
6355  QualType PointeeTy = Operand->getType()->getPointeeType();
6356  return S.RequireCompleteType(Loc, PointeeTy,
6357                               diag::err_typecheck_arithmetic_incomplete_type,
6358                               PointeeTy, Operand->getSourceRange());
6359}
6360
6361/// \brief Check the validity of an arithmetic pointer operand.
6362///
6363/// If the operand has pointer type, this code will check for pointer types
6364/// which are invalid in arithmetic operations. These will be diagnosed
6365/// appropriately, including whether or not the use is supported as an
6366/// extension.
6367///
6368/// \returns True when the operand is valid to use (even if as an extension).
6369static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6370                                            Expr *Operand) {
6371  if (!Operand->getType()->isAnyPointerType()) return true;
6372
6373  QualType PointeeTy = Operand->getType()->getPointeeType();
6374  if (PointeeTy->isVoidType()) {
6375    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6376    return !S.getLangOpts().CPlusPlus;
6377  }
6378  if (PointeeTy->isFunctionType()) {
6379    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6380    return !S.getLangOpts().CPlusPlus;
6381  }
6382
6383  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6384
6385  return true;
6386}
6387
6388/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6389/// operands.
6390///
6391/// This routine will diagnose any invalid arithmetic on pointer operands much
6392/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6393/// for emitting a single diagnostic even for operations where both LHS and RHS
6394/// are (potentially problematic) pointers.
6395///
6396/// \returns True when the operand is valid to use (even if as an extension).
6397static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6398                                                Expr *LHSExpr, Expr *RHSExpr) {
6399  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6400  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6401  if (!isLHSPointer && !isRHSPointer) return true;
6402
6403  QualType LHSPointeeTy, RHSPointeeTy;
6404  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6405  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6406
6407  // Check for arithmetic on pointers to incomplete types.
6408  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6409  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6410  if (isLHSVoidPtr || isRHSVoidPtr) {
6411    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6412    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6413    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6414
6415    return !S.getLangOpts().CPlusPlus;
6416  }
6417
6418  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6419  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6420  if (isLHSFuncPtr || isRHSFuncPtr) {
6421    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6422    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6423                                                                RHSExpr);
6424    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6425
6426    return !S.getLangOpts().CPlusPlus;
6427  }
6428
6429  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6430    return false;
6431  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6432    return false;
6433
6434  return true;
6435}
6436
6437/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6438/// literal.
6439static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6440                                  Expr *LHSExpr, Expr *RHSExpr) {
6441  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6442  Expr* IndexExpr = RHSExpr;
6443  if (!StrExpr) {
6444    StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6445    IndexExpr = LHSExpr;
6446  }
6447
6448  bool IsStringPlusInt = StrExpr &&
6449      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6450  if (!IsStringPlusInt)
6451    return;
6452
6453  llvm::APSInt index;
6454  if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6455    unsigned StrLenWithNull = StrExpr->getLength() + 1;
6456    if (index.isNonNegative() &&
6457        index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6458                              index.isUnsigned()))
6459      return;
6460  }
6461
6462  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6463  Self.Diag(OpLoc, diag::warn_string_plus_int)
6464      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6465
6466  // Only print a fixit for "str" + int, not for int + "str".
6467  if (IndexExpr == RHSExpr) {
6468    SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6469    Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6470        << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6471        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6472        << FixItHint::CreateInsertion(EndLoc, "]");
6473  } else
6474    Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6475}
6476
6477/// \brief Emit error when two pointers are incompatible.
6478static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6479                                           Expr *LHSExpr, Expr *RHSExpr) {
6480  assert(LHSExpr->getType()->isAnyPointerType());
6481  assert(RHSExpr->getType()->isAnyPointerType());
6482  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6483    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6484    << RHSExpr->getSourceRange();
6485}
6486
6487QualType Sema::CheckAdditionOperands( // C99 6.5.6
6488    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6489    QualType* CompLHSTy) {
6490  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6491
6492  if (LHS.get()->getType()->isVectorType() ||
6493      RHS.get()->getType()->isVectorType()) {
6494    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6495    if (CompLHSTy) *CompLHSTy = compType;
6496    return compType;
6497  }
6498
6499  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6500  if (LHS.isInvalid() || RHS.isInvalid())
6501    return QualType();
6502
6503  // Diagnose "string literal" '+' int.
6504  if (Opc == BO_Add)
6505    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6506
6507  // handle the common case first (both operands are arithmetic).
6508  if (!compType.isNull() && compType->isArithmeticType()) {
6509    if (CompLHSTy) *CompLHSTy = compType;
6510    return compType;
6511  }
6512
6513  // Type-checking.  Ultimately the pointer's going to be in PExp;
6514  // note that we bias towards the LHS being the pointer.
6515  Expr *PExp = LHS.get(), *IExp = RHS.get();
6516
6517  bool isObjCPointer;
6518  if (PExp->getType()->isPointerType()) {
6519    isObjCPointer = false;
6520  } else if (PExp->getType()->isObjCObjectPointerType()) {
6521    isObjCPointer = true;
6522  } else {
6523    std::swap(PExp, IExp);
6524    if (PExp->getType()->isPointerType()) {
6525      isObjCPointer = false;
6526    } else if (PExp->getType()->isObjCObjectPointerType()) {
6527      isObjCPointer = true;
6528    } else {
6529      return InvalidOperands(Loc, LHS, RHS);
6530    }
6531  }
6532  assert(PExp->getType()->isAnyPointerType());
6533
6534  if (!IExp->getType()->isIntegerType())
6535    return InvalidOperands(Loc, LHS, RHS);
6536
6537  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6538    return QualType();
6539
6540  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6541    return QualType();
6542
6543  // Check array bounds for pointer arithemtic
6544  CheckArrayAccess(PExp, IExp);
6545
6546  if (CompLHSTy) {
6547    QualType LHSTy = Context.isPromotableBitField(LHS.get());
6548    if (LHSTy.isNull()) {
6549      LHSTy = LHS.get()->getType();
6550      if (LHSTy->isPromotableIntegerType())
6551        LHSTy = Context.getPromotedIntegerType(LHSTy);
6552    }
6553    *CompLHSTy = LHSTy;
6554  }
6555
6556  return PExp->getType();
6557}
6558
6559// C99 6.5.6
6560QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6561                                        SourceLocation Loc,
6562                                        QualType* CompLHSTy) {
6563  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6564
6565  if (LHS.get()->getType()->isVectorType() ||
6566      RHS.get()->getType()->isVectorType()) {
6567    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6568    if (CompLHSTy) *CompLHSTy = compType;
6569    return compType;
6570  }
6571
6572  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6573  if (LHS.isInvalid() || RHS.isInvalid())
6574    return QualType();
6575
6576  // Enforce type constraints: C99 6.5.6p3.
6577
6578  // Handle the common case first (both operands are arithmetic).
6579  if (!compType.isNull() && compType->isArithmeticType()) {
6580    if (CompLHSTy) *CompLHSTy = compType;
6581    return compType;
6582  }
6583
6584  // Either ptr - int   or   ptr - ptr.
6585  if (LHS.get()->getType()->isAnyPointerType()) {
6586    QualType lpointee = LHS.get()->getType()->getPointeeType();
6587
6588    // Diagnose bad cases where we step over interface counts.
6589    if (LHS.get()->getType()->isObjCObjectPointerType() &&
6590        checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6591      return QualType();
6592
6593    // The result type of a pointer-int computation is the pointer type.
6594    if (RHS.get()->getType()->isIntegerType()) {
6595      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6596        return QualType();
6597
6598      // Check array bounds for pointer arithemtic
6599      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6600                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6601
6602      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6603      return LHS.get()->getType();
6604    }
6605
6606    // Handle pointer-pointer subtractions.
6607    if (const PointerType *RHSPTy
6608          = RHS.get()->getType()->getAs<PointerType>()) {
6609      QualType rpointee = RHSPTy->getPointeeType();
6610
6611      if (getLangOpts().CPlusPlus) {
6612        // Pointee types must be the same: C++ [expr.add]
6613        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6614          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6615        }
6616      } else {
6617        // Pointee types must be compatible C99 6.5.6p3
6618        if (!Context.typesAreCompatible(
6619                Context.getCanonicalType(lpointee).getUnqualifiedType(),
6620                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6621          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6622          return QualType();
6623        }
6624      }
6625
6626      if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6627                                               LHS.get(), RHS.get()))
6628        return QualType();
6629
6630      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6631      return Context.getPointerDiffType();
6632    }
6633  }
6634
6635  return InvalidOperands(Loc, LHS, RHS);
6636}
6637
6638static bool isScopedEnumerationType(QualType T) {
6639  if (const EnumType *ET = dyn_cast<EnumType>(T))
6640    return ET->getDecl()->isScoped();
6641  return false;
6642}
6643
6644static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6645                                   SourceLocation Loc, unsigned Opc,
6646                                   QualType LHSType) {
6647  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6648  // so skip remaining warnings as we don't want to modify values within Sema.
6649  if (S.getLangOpts().OpenCL)
6650    return;
6651
6652  llvm::APSInt Right;
6653  // Check right/shifter operand
6654  if (RHS.get()->isValueDependent() ||
6655      !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6656    return;
6657
6658  if (Right.isNegative()) {
6659    S.DiagRuntimeBehavior(Loc, RHS.get(),
6660                          S.PDiag(diag::warn_shift_negative)
6661                            << RHS.get()->getSourceRange());
6662    return;
6663  }
6664  llvm::APInt LeftBits(Right.getBitWidth(),
6665                       S.Context.getTypeSize(LHS.get()->getType()));
6666  if (Right.uge(LeftBits)) {
6667    S.DiagRuntimeBehavior(Loc, RHS.get(),
6668                          S.PDiag(diag::warn_shift_gt_typewidth)
6669                            << RHS.get()->getSourceRange());
6670    return;
6671  }
6672  if (Opc != BO_Shl)
6673    return;
6674
6675  // When left shifting an ICE which is signed, we can check for overflow which
6676  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6677  // integers have defined behavior modulo one more than the maximum value
6678  // representable in the result type, so never warn for those.
6679  llvm::APSInt Left;
6680  if (LHS.get()->isValueDependent() ||
6681      !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6682      LHSType->hasUnsignedIntegerRepresentation())
6683    return;
6684  llvm::APInt ResultBits =
6685      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6686  if (LeftBits.uge(ResultBits))
6687    return;
6688  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6689  Result = Result.shl(Right);
6690
6691  // Print the bit representation of the signed integer as an unsigned
6692  // hexadecimal number.
6693  SmallString<40> HexResult;
6694  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6695
6696  // If we are only missing a sign bit, this is less likely to result in actual
6697  // bugs -- if the result is cast back to an unsigned type, it will have the
6698  // expected value. Thus we place this behind a different warning that can be
6699  // turned off separately if needed.
6700  if (LeftBits == ResultBits - 1) {
6701    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6702        << HexResult.str() << LHSType
6703        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6704    return;
6705  }
6706
6707  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6708    << HexResult.str() << Result.getMinSignedBits() << LHSType
6709    << Left.getBitWidth() << LHS.get()->getSourceRange()
6710    << RHS.get()->getSourceRange();
6711}
6712
6713// C99 6.5.7
6714QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6715                                  SourceLocation Loc, unsigned Opc,
6716                                  bool IsCompAssign) {
6717  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6718
6719  // C99 6.5.7p2: Each of the operands shall have integer type.
6720  if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6721      !RHS.get()->getType()->hasIntegerRepresentation())
6722    return InvalidOperands(Loc, LHS, RHS);
6723
6724  // C++0x: Don't allow scoped enums. FIXME: Use something better than
6725  // hasIntegerRepresentation() above instead of this.
6726  if (isScopedEnumerationType(LHS.get()->getType()) ||
6727      isScopedEnumerationType(RHS.get()->getType())) {
6728    return InvalidOperands(Loc, LHS, RHS);
6729  }
6730
6731  // Vector shifts promote their scalar inputs to vector type.
6732  if (LHS.get()->getType()->isVectorType() ||
6733      RHS.get()->getType()->isVectorType())
6734    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6735
6736  // Shifts don't perform usual arithmetic conversions, they just do integer
6737  // promotions on each operand. C99 6.5.7p3
6738
6739  // For the LHS, do usual unary conversions, but then reset them away
6740  // if this is a compound assignment.
6741  ExprResult OldLHS = LHS;
6742  LHS = UsualUnaryConversions(LHS.take());
6743  if (LHS.isInvalid())
6744    return QualType();
6745  QualType LHSType = LHS.get()->getType();
6746  if (IsCompAssign) LHS = OldLHS;
6747
6748  // The RHS is simpler.
6749  RHS = UsualUnaryConversions(RHS.take());
6750  if (RHS.isInvalid())
6751    return QualType();
6752
6753  // Sanity-check shift operands
6754  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6755
6756  // "The type of the result is that of the promoted left operand."
6757  return LHSType;
6758}
6759
6760static bool IsWithinTemplateSpecialization(Decl *D) {
6761  if (DeclContext *DC = D->getDeclContext()) {
6762    if (isa<ClassTemplateSpecializationDecl>(DC))
6763      return true;
6764    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6765      return FD->isFunctionTemplateSpecialization();
6766  }
6767  return false;
6768}
6769
6770/// If two different enums are compared, raise a warning.
6771static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6772                                Expr *RHS) {
6773  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6774  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
6775
6776  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6777  if (!LHSEnumType)
6778    return;
6779  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6780  if (!RHSEnumType)
6781    return;
6782
6783  // Ignore anonymous enums.
6784  if (!LHSEnumType->getDecl()->getIdentifier())
6785    return;
6786  if (!RHSEnumType->getDecl()->getIdentifier())
6787    return;
6788
6789  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6790    return;
6791
6792  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6793      << LHSStrippedType << RHSStrippedType
6794      << LHS->getSourceRange() << RHS->getSourceRange();
6795}
6796
6797/// \brief Diagnose bad pointer comparisons.
6798static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6799                                              ExprResult &LHS, ExprResult &RHS,
6800                                              bool IsError) {
6801  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6802                      : diag::ext_typecheck_comparison_of_distinct_pointers)
6803    << LHS.get()->getType() << RHS.get()->getType()
6804    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6805}
6806
6807/// \brief Returns false if the pointers are converted to a composite type,
6808/// true otherwise.
6809static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6810                                           ExprResult &LHS, ExprResult &RHS) {
6811  // C++ [expr.rel]p2:
6812  //   [...] Pointer conversions (4.10) and qualification
6813  //   conversions (4.4) are performed on pointer operands (or on
6814  //   a pointer operand and a null pointer constant) to bring
6815  //   them to their composite pointer type. [...]
6816  //
6817  // C++ [expr.eq]p1 uses the same notion for (in)equality
6818  // comparisons of pointers.
6819
6820  // C++ [expr.eq]p2:
6821  //   In addition, pointers to members can be compared, or a pointer to
6822  //   member and a null pointer constant. Pointer to member conversions
6823  //   (4.11) and qualification conversions (4.4) are performed to bring
6824  //   them to a common type. If one operand is a null pointer constant,
6825  //   the common type is the type of the other operand. Otherwise, the
6826  //   common type is a pointer to member type similar (4.4) to the type
6827  //   of one of the operands, with a cv-qualification signature (4.4)
6828  //   that is the union of the cv-qualification signatures of the operand
6829  //   types.
6830
6831  QualType LHSType = LHS.get()->getType();
6832  QualType RHSType = RHS.get()->getType();
6833  assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6834         (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6835
6836  bool NonStandardCompositeType = false;
6837  bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6838  QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6839  if (T.isNull()) {
6840    diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6841    return true;
6842  }
6843
6844  if (NonStandardCompositeType)
6845    S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6846      << LHSType << RHSType << T << LHS.get()->getSourceRange()
6847      << RHS.get()->getSourceRange();
6848
6849  LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6850  RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6851  return false;
6852}
6853
6854static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6855                                                    ExprResult &LHS,
6856                                                    ExprResult &RHS,
6857                                                    bool IsError) {
6858  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6859                      : diag::ext_typecheck_comparison_of_fptr_to_void)
6860    << LHS.get()->getType() << RHS.get()->getType()
6861    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6862}
6863
6864static bool isObjCObjectLiteral(ExprResult &E) {
6865  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6866  case Stmt::ObjCArrayLiteralClass:
6867  case Stmt::ObjCDictionaryLiteralClass:
6868  case Stmt::ObjCStringLiteralClass:
6869  case Stmt::ObjCBoxedExprClass:
6870    return true;
6871  default:
6872    // Note that ObjCBoolLiteral is NOT an object literal!
6873    return false;
6874  }
6875}
6876
6877static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6878  const ObjCObjectPointerType *Type =
6879    LHS->getType()->getAs<ObjCObjectPointerType>();
6880
6881  // If this is not actually an Objective-C object, bail out.
6882  if (!Type)
6883    return false;
6884
6885  // Get the LHS object's interface type.
6886  QualType InterfaceType = Type->getPointeeType();
6887  if (const ObjCObjectType *iQFaceTy =
6888      InterfaceType->getAsObjCQualifiedInterfaceType())
6889    InterfaceType = iQFaceTy->getBaseType();
6890
6891  // If the RHS isn't an Objective-C object, bail out.
6892  if (!RHS->getType()->isObjCObjectPointerType())
6893    return false;
6894
6895  // Try to find the -isEqual: method.
6896  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6897  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6898                                                      InterfaceType,
6899                                                      /*instance=*/true);
6900  if (!Method) {
6901    if (Type->isObjCIdType()) {
6902      // For 'id', just check the global pool.
6903      Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6904                                                  /*receiverId=*/true,
6905                                                  /*warn=*/false);
6906    } else {
6907      // Check protocols.
6908      Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
6909                                             /*instance=*/true);
6910    }
6911  }
6912
6913  if (!Method)
6914    return false;
6915
6916  QualType T = Method->param_begin()[0]->getType();
6917  if (!T->isObjCObjectPointerType())
6918    return false;
6919
6920  QualType R = Method->getResultType();
6921  if (!R->isScalarType())
6922    return false;
6923
6924  return true;
6925}
6926
6927Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
6928  FromE = FromE->IgnoreParenImpCasts();
6929  switch (FromE->getStmtClass()) {
6930    default:
6931      break;
6932    case Stmt::ObjCStringLiteralClass:
6933      // "string literal"
6934      return LK_String;
6935    case Stmt::ObjCArrayLiteralClass:
6936      // "array literal"
6937      return LK_Array;
6938    case Stmt::ObjCDictionaryLiteralClass:
6939      // "dictionary literal"
6940      return LK_Dictionary;
6941    case Stmt::BlockExprClass:
6942      return LK_Block;
6943    case Stmt::ObjCBoxedExprClass: {
6944      Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
6945      switch (Inner->getStmtClass()) {
6946        case Stmt::IntegerLiteralClass:
6947        case Stmt::FloatingLiteralClass:
6948        case Stmt::CharacterLiteralClass:
6949        case Stmt::ObjCBoolLiteralExprClass:
6950        case Stmt::CXXBoolLiteralExprClass:
6951          // "numeric literal"
6952          return LK_Numeric;
6953        case Stmt::ImplicitCastExprClass: {
6954          CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6955          // Boolean literals can be represented by implicit casts.
6956          if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
6957            return LK_Numeric;
6958          break;
6959        }
6960        default:
6961          break;
6962      }
6963      return LK_Boxed;
6964    }
6965  }
6966  return LK_None;
6967}
6968
6969static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6970                                          ExprResult &LHS, ExprResult &RHS,
6971                                          BinaryOperator::Opcode Opc){
6972  Expr *Literal;
6973  Expr *Other;
6974  if (isObjCObjectLiteral(LHS)) {
6975    Literal = LHS.get();
6976    Other = RHS.get();
6977  } else {
6978    Literal = RHS.get();
6979    Other = LHS.get();
6980  }
6981
6982  // Don't warn on comparisons against nil.
6983  Other = Other->IgnoreParenCasts();
6984  if (Other->isNullPointerConstant(S.getASTContext(),
6985                                   Expr::NPC_ValueDependentIsNotNull))
6986    return;
6987
6988  // This should be kept in sync with warn_objc_literal_comparison.
6989  // LK_String should always be after the other literals, since it has its own
6990  // warning flag.
6991  Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
6992  assert(LiteralKind != Sema::LK_Block);
6993  if (LiteralKind == Sema::LK_None) {
6994    llvm_unreachable("Unknown Objective-C object literal kind");
6995  }
6996
6997  if (LiteralKind == Sema::LK_String)
6998    S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6999      << Literal->getSourceRange();
7000  else
7001    S.Diag(Loc, diag::warn_objc_literal_comparison)
7002      << LiteralKind << Literal->getSourceRange();
7003
7004  if (BinaryOperator::isEqualityOp(Opc) &&
7005      hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7006    SourceLocation Start = LHS.get()->getLocStart();
7007    SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7008    CharSourceRange OpRange =
7009      CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7010
7011    S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7012      << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7013      << FixItHint::CreateReplacement(OpRange, " isEqual:")
7014      << FixItHint::CreateInsertion(End, "]");
7015  }
7016}
7017
7018// C99 6.5.8, C++ [expr.rel]
7019QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7020                                    SourceLocation Loc, unsigned OpaqueOpc,
7021                                    bool IsRelational) {
7022  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7023
7024  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7025
7026  // Handle vector comparisons separately.
7027  if (LHS.get()->getType()->isVectorType() ||
7028      RHS.get()->getType()->isVectorType())
7029    return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7030
7031  QualType LHSType = LHS.get()->getType();
7032  QualType RHSType = RHS.get()->getType();
7033
7034  Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7035  Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7036
7037  checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7038
7039  if (!LHSType->hasFloatingRepresentation() &&
7040      !(LHSType->isBlockPointerType() && IsRelational) &&
7041      !LHS.get()->getLocStart().isMacroID() &&
7042      !RHS.get()->getLocStart().isMacroID()) {
7043    // For non-floating point types, check for self-comparisons of the form
7044    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7045    // often indicate logic errors in the program.
7046    //
7047    // NOTE: Don't warn about comparison expressions resulting from macro
7048    // expansion. Also don't warn about comparisons which are only self
7049    // comparisons within a template specialization. The warnings should catch
7050    // obvious cases in the definition of the template anyways. The idea is to
7051    // warn when the typed comparison operator will always evaluate to the same
7052    // result.
7053    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7054      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7055        if (DRL->getDecl() == DRR->getDecl() &&
7056            !IsWithinTemplateSpecialization(DRL->getDecl())) {
7057          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7058                              << 0 // self-
7059                              << (Opc == BO_EQ
7060                                  || Opc == BO_LE
7061                                  || Opc == BO_GE));
7062        } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7063                   !DRL->getDecl()->getType()->isReferenceType() &&
7064                   !DRR->getDecl()->getType()->isReferenceType()) {
7065            // what is it always going to eval to?
7066            char always_evals_to;
7067            switch(Opc) {
7068            case BO_EQ: // e.g. array1 == array2
7069              always_evals_to = 0; // false
7070              break;
7071            case BO_NE: // e.g. array1 != array2
7072              always_evals_to = 1; // true
7073              break;
7074            default:
7075              // best we can say is 'a constant'
7076              always_evals_to = 2; // e.g. array1 <= array2
7077              break;
7078            }
7079            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7080                                << 1 // array
7081                                << always_evals_to);
7082        }
7083      }
7084    }
7085
7086    if (isa<CastExpr>(LHSStripped))
7087      LHSStripped = LHSStripped->IgnoreParenCasts();
7088    if (isa<CastExpr>(RHSStripped))
7089      RHSStripped = RHSStripped->IgnoreParenCasts();
7090
7091    // Warn about comparisons against a string constant (unless the other
7092    // operand is null), the user probably wants strcmp.
7093    Expr *literalString = 0;
7094    Expr *literalStringStripped = 0;
7095    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7096        !RHSStripped->isNullPointerConstant(Context,
7097                                            Expr::NPC_ValueDependentIsNull)) {
7098      literalString = LHS.get();
7099      literalStringStripped = LHSStripped;
7100    } else if ((isa<StringLiteral>(RHSStripped) ||
7101                isa<ObjCEncodeExpr>(RHSStripped)) &&
7102               !LHSStripped->isNullPointerConstant(Context,
7103                                            Expr::NPC_ValueDependentIsNull)) {
7104      literalString = RHS.get();
7105      literalStringStripped = RHSStripped;
7106    }
7107
7108    if (literalString) {
7109      std::string resultComparison;
7110      switch (Opc) {
7111      case BO_LT: resultComparison = ") < 0"; break;
7112      case BO_GT: resultComparison = ") > 0"; break;
7113      case BO_LE: resultComparison = ") <= 0"; break;
7114      case BO_GE: resultComparison = ") >= 0"; break;
7115      case BO_EQ: resultComparison = ") == 0"; break;
7116      case BO_NE: resultComparison = ") != 0"; break;
7117      default: llvm_unreachable("Invalid comparison operator");
7118      }
7119
7120      DiagRuntimeBehavior(Loc, 0,
7121        PDiag(diag::warn_stringcompare)
7122          << isa<ObjCEncodeExpr>(literalStringStripped)
7123          << literalString->getSourceRange());
7124    }
7125  }
7126
7127  // C99 6.5.8p3 / C99 6.5.9p4
7128  if (LHS.get()->getType()->isArithmeticType() &&
7129      RHS.get()->getType()->isArithmeticType()) {
7130    UsualArithmeticConversions(LHS, RHS);
7131    if (LHS.isInvalid() || RHS.isInvalid())
7132      return QualType();
7133  }
7134  else {
7135    LHS = UsualUnaryConversions(LHS.take());
7136    if (LHS.isInvalid())
7137      return QualType();
7138
7139    RHS = UsualUnaryConversions(RHS.take());
7140    if (RHS.isInvalid())
7141      return QualType();
7142  }
7143
7144  LHSType = LHS.get()->getType();
7145  RHSType = RHS.get()->getType();
7146
7147  // The result of comparisons is 'bool' in C++, 'int' in C.
7148  QualType ResultTy = Context.getLogicalOperationType();
7149
7150  if (IsRelational) {
7151    if (LHSType->isRealType() && RHSType->isRealType())
7152      return ResultTy;
7153  } else {
7154    // Check for comparisons of floating point operands using != and ==.
7155    if (LHSType->hasFloatingRepresentation())
7156      CheckFloatComparison(Loc, LHS.get(), RHS.get());
7157
7158    if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7159      return ResultTy;
7160  }
7161
7162  bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7163                                              Expr::NPC_ValueDependentIsNull);
7164  bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7165                                              Expr::NPC_ValueDependentIsNull);
7166
7167  // All of the following pointer-related warnings are GCC extensions, except
7168  // when handling null pointer constants.
7169  if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7170    QualType LCanPointeeTy =
7171      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7172    QualType RCanPointeeTy =
7173      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7174
7175    if (getLangOpts().CPlusPlus) {
7176      if (LCanPointeeTy == RCanPointeeTy)
7177        return ResultTy;
7178      if (!IsRelational &&
7179          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7180        // Valid unless comparison between non-null pointer and function pointer
7181        // This is a gcc extension compatibility comparison.
7182        // In a SFINAE context, we treat this as a hard error to maintain
7183        // conformance with the C++ standard.
7184        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7185            && !LHSIsNull && !RHSIsNull) {
7186          diagnoseFunctionPointerToVoidComparison(
7187              *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7188
7189          if (isSFINAEContext())
7190            return QualType();
7191
7192          RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7193          return ResultTy;
7194        }
7195      }
7196
7197      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7198        return QualType();
7199      else
7200        return ResultTy;
7201    }
7202    // C99 6.5.9p2 and C99 6.5.8p2
7203    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7204                                   RCanPointeeTy.getUnqualifiedType())) {
7205      // Valid unless a relational comparison of function pointers
7206      if (IsRelational && LCanPointeeTy->isFunctionType()) {
7207        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7208          << LHSType << RHSType << LHS.get()->getSourceRange()
7209          << RHS.get()->getSourceRange();
7210      }
7211    } else if (!IsRelational &&
7212               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7213      // Valid unless comparison between non-null pointer and function pointer
7214      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7215          && !LHSIsNull && !RHSIsNull)
7216        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7217                                                /*isError*/false);
7218    } else {
7219      // Invalid
7220      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7221    }
7222    if (LCanPointeeTy != RCanPointeeTy) {
7223      if (LHSIsNull && !RHSIsNull)
7224        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7225      else
7226        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7227    }
7228    return ResultTy;
7229  }
7230
7231  if (getLangOpts().CPlusPlus) {
7232    // Comparison of nullptr_t with itself.
7233    if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7234      return ResultTy;
7235
7236    // Comparison of pointers with null pointer constants and equality
7237    // comparisons of member pointers to null pointer constants.
7238    if (RHSIsNull &&
7239        ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7240         (!IsRelational &&
7241          (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7242      RHS = ImpCastExprToType(RHS.take(), LHSType,
7243                        LHSType->isMemberPointerType()
7244                          ? CK_NullToMemberPointer
7245                          : CK_NullToPointer);
7246      return ResultTy;
7247    }
7248    if (LHSIsNull &&
7249        ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7250         (!IsRelational &&
7251          (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7252      LHS = ImpCastExprToType(LHS.take(), RHSType,
7253                        RHSType->isMemberPointerType()
7254                          ? CK_NullToMemberPointer
7255                          : CK_NullToPointer);
7256      return ResultTy;
7257    }
7258
7259    // Comparison of member pointers.
7260    if (!IsRelational &&
7261        LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7262      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7263        return QualType();
7264      else
7265        return ResultTy;
7266    }
7267
7268    // Handle scoped enumeration types specifically, since they don't promote
7269    // to integers.
7270    if (LHS.get()->getType()->isEnumeralType() &&
7271        Context.hasSameUnqualifiedType(LHS.get()->getType(),
7272                                       RHS.get()->getType()))
7273      return ResultTy;
7274  }
7275
7276  // Handle block pointer types.
7277  if (!IsRelational && LHSType->isBlockPointerType() &&
7278      RHSType->isBlockPointerType()) {
7279    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7280    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7281
7282    if (!LHSIsNull && !RHSIsNull &&
7283        !Context.typesAreCompatible(lpointee, rpointee)) {
7284      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7285        << LHSType << RHSType << LHS.get()->getSourceRange()
7286        << RHS.get()->getSourceRange();
7287    }
7288    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7289    return ResultTy;
7290  }
7291
7292  // Allow block pointers to be compared with null pointer constants.
7293  if (!IsRelational
7294      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7295          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7296    if (!LHSIsNull && !RHSIsNull) {
7297      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7298             ->getPointeeType()->isVoidType())
7299            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7300                ->getPointeeType()->isVoidType())))
7301        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7302          << LHSType << RHSType << LHS.get()->getSourceRange()
7303          << RHS.get()->getSourceRange();
7304    }
7305    if (LHSIsNull && !RHSIsNull)
7306      LHS = ImpCastExprToType(LHS.take(), RHSType,
7307                              RHSType->isPointerType() ? CK_BitCast
7308                                : CK_AnyPointerToBlockPointerCast);
7309    else
7310      RHS = ImpCastExprToType(RHS.take(), LHSType,
7311                              LHSType->isPointerType() ? CK_BitCast
7312                                : CK_AnyPointerToBlockPointerCast);
7313    return ResultTy;
7314  }
7315
7316  if (LHSType->isObjCObjectPointerType() ||
7317      RHSType->isObjCObjectPointerType()) {
7318    const PointerType *LPT = LHSType->getAs<PointerType>();
7319    const PointerType *RPT = RHSType->getAs<PointerType>();
7320    if (LPT || RPT) {
7321      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7322      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7323
7324      if (!LPtrToVoid && !RPtrToVoid &&
7325          !Context.typesAreCompatible(LHSType, RHSType)) {
7326        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7327                                          /*isError*/false);
7328      }
7329      if (LHSIsNull && !RHSIsNull)
7330        LHS = ImpCastExprToType(LHS.take(), RHSType,
7331                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7332      else
7333        RHS = ImpCastExprToType(RHS.take(), LHSType,
7334                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7335      return ResultTy;
7336    }
7337    if (LHSType->isObjCObjectPointerType() &&
7338        RHSType->isObjCObjectPointerType()) {
7339      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7340        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7341                                          /*isError*/false);
7342      if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7343        diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7344
7345      if (LHSIsNull && !RHSIsNull)
7346        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7347      else
7348        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7349      return ResultTy;
7350    }
7351  }
7352  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7353      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7354    unsigned DiagID = 0;
7355    bool isError = false;
7356    if (LangOpts.DebuggerSupport) {
7357      // Under a debugger, allow the comparison of pointers to integers,
7358      // since users tend to want to compare addresses.
7359    } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7360        (RHSIsNull && RHSType->isIntegerType())) {
7361      if (IsRelational && !getLangOpts().CPlusPlus)
7362        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7363    } else if (IsRelational && !getLangOpts().CPlusPlus)
7364      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7365    else if (getLangOpts().CPlusPlus) {
7366      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7367      isError = true;
7368    } else
7369      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7370
7371    if (DiagID) {
7372      Diag(Loc, DiagID)
7373        << LHSType << RHSType << LHS.get()->getSourceRange()
7374        << RHS.get()->getSourceRange();
7375      if (isError)
7376        return QualType();
7377    }
7378
7379    if (LHSType->isIntegerType())
7380      LHS = ImpCastExprToType(LHS.take(), RHSType,
7381                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7382    else
7383      RHS = ImpCastExprToType(RHS.take(), LHSType,
7384                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7385    return ResultTy;
7386  }
7387
7388  // Handle block pointers.
7389  if (!IsRelational && RHSIsNull
7390      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7391    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7392    return ResultTy;
7393  }
7394  if (!IsRelational && LHSIsNull
7395      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7396    LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7397    return ResultTy;
7398  }
7399
7400  return InvalidOperands(Loc, LHS, RHS);
7401}
7402
7403
7404// Return a signed type that is of identical size and number of elements.
7405// For floating point vectors, return an integer type of identical size
7406// and number of elements.
7407QualType Sema::GetSignedVectorType(QualType V) {
7408  const VectorType *VTy = V->getAs<VectorType>();
7409  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7410  if (TypeSize == Context.getTypeSize(Context.CharTy))
7411    return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7412  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7413    return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7414  else if (TypeSize == Context.getTypeSize(Context.IntTy))
7415    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7416  else if (TypeSize == Context.getTypeSize(Context.LongTy))
7417    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7418  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7419         "Unhandled vector element size in vector compare");
7420  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7421}
7422
7423/// CheckVectorCompareOperands - vector comparisons are a clang extension that
7424/// operates on extended vector types.  Instead of producing an IntTy result,
7425/// like a scalar comparison, a vector comparison produces a vector of integer
7426/// types.
7427QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7428                                          SourceLocation Loc,
7429                                          bool IsRelational) {
7430  // Check to make sure we're operating on vectors of the same type and width,
7431  // Allowing one side to be a scalar of element type.
7432  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7433  if (vType.isNull())
7434    return vType;
7435
7436  QualType LHSType = LHS.get()->getType();
7437
7438  // If AltiVec, the comparison results in a numeric type, i.e.
7439  // bool for C++, int for C
7440  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7441    return Context.getLogicalOperationType();
7442
7443  // For non-floating point types, check for self-comparisons of the form
7444  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7445  // often indicate logic errors in the program.
7446  if (!LHSType->hasFloatingRepresentation()) {
7447    if (DeclRefExpr* DRL
7448          = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7449      if (DeclRefExpr* DRR
7450            = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7451        if (DRL->getDecl() == DRR->getDecl())
7452          DiagRuntimeBehavior(Loc, 0,
7453                              PDiag(diag::warn_comparison_always)
7454                                << 0 // self-
7455                                << 2 // "a constant"
7456                              );
7457  }
7458
7459  // Check for comparisons of floating point operands using != and ==.
7460  if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7461    assert (RHS.get()->getType()->hasFloatingRepresentation());
7462    CheckFloatComparison(Loc, LHS.get(), RHS.get());
7463  }
7464
7465  // Return a signed type for the vector.
7466  return GetSignedVectorType(LHSType);
7467}
7468
7469QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7470                                          SourceLocation Loc) {
7471  // Ensure that either both operands are of the same vector type, or
7472  // one operand is of a vector type and the other is of its element type.
7473  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7474  if (vType.isNull())
7475    return InvalidOperands(Loc, LHS, RHS);
7476  if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7477      vType->hasFloatingRepresentation())
7478    return InvalidOperands(Loc, LHS, RHS);
7479
7480  return GetSignedVectorType(LHS.get()->getType());
7481}
7482
7483inline QualType Sema::CheckBitwiseOperands(
7484  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7485  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7486
7487  if (LHS.get()->getType()->isVectorType() ||
7488      RHS.get()->getType()->isVectorType()) {
7489    if (LHS.get()->getType()->hasIntegerRepresentation() &&
7490        RHS.get()->getType()->hasIntegerRepresentation())
7491      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7492
7493    return InvalidOperands(Loc, LHS, RHS);
7494  }
7495
7496  ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7497  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7498                                                 IsCompAssign);
7499  if (LHSResult.isInvalid() || RHSResult.isInvalid())
7500    return QualType();
7501  LHS = LHSResult.take();
7502  RHS = RHSResult.take();
7503
7504  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7505    return compType;
7506  return InvalidOperands(Loc, LHS, RHS);
7507}
7508
7509inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7510  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7511
7512  // Check vector operands differently.
7513  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7514    return CheckVectorLogicalOperands(LHS, RHS, Loc);
7515
7516  // Diagnose cases where the user write a logical and/or but probably meant a
7517  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7518  // is a constant.
7519  if (LHS.get()->getType()->isIntegerType() &&
7520      !LHS.get()->getType()->isBooleanType() &&
7521      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7522      // Don't warn in macros or template instantiations.
7523      !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7524    // If the RHS can be constant folded, and if it constant folds to something
7525    // that isn't 0 or 1 (which indicate a potential logical operation that
7526    // happened to fold to true/false) then warn.
7527    // Parens on the RHS are ignored.
7528    llvm::APSInt Result;
7529    if (RHS.get()->EvaluateAsInt(Result, Context))
7530      if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7531          (Result != 0 && Result != 1)) {
7532        Diag(Loc, diag::warn_logical_instead_of_bitwise)
7533          << RHS.get()->getSourceRange()
7534          << (Opc == BO_LAnd ? "&&" : "||");
7535        // Suggest replacing the logical operator with the bitwise version
7536        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7537            << (Opc == BO_LAnd ? "&" : "|")
7538            << FixItHint::CreateReplacement(SourceRange(
7539                Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7540                                                getLangOpts())),
7541                                            Opc == BO_LAnd ? "&" : "|");
7542        if (Opc == BO_LAnd)
7543          // Suggest replacing "Foo() && kNonZero" with "Foo()"
7544          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7545              << FixItHint::CreateRemoval(
7546                  SourceRange(
7547                      Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7548                                                 0, getSourceManager(),
7549                                                 getLangOpts()),
7550                      RHS.get()->getLocEnd()));
7551      }
7552  }
7553
7554  if (!Context.getLangOpts().CPlusPlus) {
7555    // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7556    // not operate on the built-in scalar and vector float types.
7557    if (Context.getLangOpts().OpenCL &&
7558        Context.getLangOpts().OpenCLVersion < 120) {
7559      if (LHS.get()->getType()->isFloatingType() ||
7560          RHS.get()->getType()->isFloatingType())
7561        return InvalidOperands(Loc, LHS, RHS);
7562    }
7563
7564    LHS = UsualUnaryConversions(LHS.take());
7565    if (LHS.isInvalid())
7566      return QualType();
7567
7568    RHS = UsualUnaryConversions(RHS.take());
7569    if (RHS.isInvalid())
7570      return QualType();
7571
7572    if (!LHS.get()->getType()->isScalarType() ||
7573        !RHS.get()->getType()->isScalarType())
7574      return InvalidOperands(Loc, LHS, RHS);
7575
7576    return Context.IntTy;
7577  }
7578
7579  // The following is safe because we only use this method for
7580  // non-overloadable operands.
7581
7582  // C++ [expr.log.and]p1
7583  // C++ [expr.log.or]p1
7584  // The operands are both contextually converted to type bool.
7585  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7586  if (LHSRes.isInvalid())
7587    return InvalidOperands(Loc, LHS, RHS);
7588  LHS = LHSRes;
7589
7590  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7591  if (RHSRes.isInvalid())
7592    return InvalidOperands(Loc, LHS, RHS);
7593  RHS = RHSRes;
7594
7595  // C++ [expr.log.and]p2
7596  // C++ [expr.log.or]p2
7597  // The result is a bool.
7598  return Context.BoolTy;
7599}
7600
7601/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7602/// is a read-only property; return true if so. A readonly property expression
7603/// depends on various declarations and thus must be treated specially.
7604///
7605static bool IsReadonlyProperty(Expr *E, Sema &S) {
7606  const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7607  if (!PropExpr) return false;
7608  if (PropExpr->isImplicitProperty()) return false;
7609
7610  ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7611  QualType BaseType = PropExpr->isSuperReceiver() ?
7612                            PropExpr->getSuperReceiverType() :
7613                            PropExpr->getBase()->getType();
7614
7615  if (const ObjCObjectPointerType *OPT =
7616      BaseType->getAsObjCInterfacePointerType())
7617    if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7618      if (S.isPropertyReadonly(PDecl, IFace))
7619        return true;
7620  return false;
7621}
7622
7623static bool IsReadonlyMessage(Expr *E, Sema &S) {
7624  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7625  if (!ME) return false;
7626  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7627  ObjCMessageExpr *Base =
7628    dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7629  if (!Base) return false;
7630  return Base->getMethodDecl() != 0;
7631}
7632
7633/// Is the given expression (which must be 'const') a reference to a
7634/// variable which was originally non-const, but which has become
7635/// 'const' due to being captured within a block?
7636enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7637static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7638  assert(E->isLValue() && E->getType().isConstQualified());
7639  E = E->IgnoreParens();
7640
7641  // Must be a reference to a declaration from an enclosing scope.
7642  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7643  if (!DRE) return NCCK_None;
7644  if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7645
7646  // The declaration must be a variable which is not declared 'const'.
7647  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7648  if (!var) return NCCK_None;
7649  if (var->getType().isConstQualified()) return NCCK_None;
7650  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7651
7652  // Decide whether the first capture was for a block or a lambda.
7653  DeclContext *DC = S.CurContext;
7654  while (DC->getParent() != var->getDeclContext())
7655    DC = DC->getParent();
7656  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7657}
7658
7659/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7660/// emit an error and return true.  If so, return false.
7661static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7662  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7663  SourceLocation OrigLoc = Loc;
7664  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7665                                                              &Loc);
7666  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7667    IsLV = Expr::MLV_ReadonlyProperty;
7668  else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7669    IsLV = Expr::MLV_InvalidMessageExpression;
7670  if (IsLV == Expr::MLV_Valid)
7671    return false;
7672
7673  unsigned Diag = 0;
7674  bool NeedType = false;
7675  switch (IsLV) { // C99 6.5.16p2
7676  case Expr::MLV_ConstQualified:
7677    Diag = diag::err_typecheck_assign_const;
7678
7679    // Use a specialized diagnostic when we're assigning to an object
7680    // from an enclosing function or block.
7681    if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7682      if (NCCK == NCCK_Block)
7683        Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7684      else
7685        Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7686      break;
7687    }
7688
7689    // In ARC, use some specialized diagnostics for occasions where we
7690    // infer 'const'.  These are always pseudo-strong variables.
7691    if (S.getLangOpts().ObjCAutoRefCount) {
7692      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7693      if (declRef && isa<VarDecl>(declRef->getDecl())) {
7694        VarDecl *var = cast<VarDecl>(declRef->getDecl());
7695
7696        // Use the normal diagnostic if it's pseudo-__strong but the
7697        // user actually wrote 'const'.
7698        if (var->isARCPseudoStrong() &&
7699            (!var->getTypeSourceInfo() ||
7700             !var->getTypeSourceInfo()->getType().isConstQualified())) {
7701          // There are two pseudo-strong cases:
7702          //  - self
7703          ObjCMethodDecl *method = S.getCurMethodDecl();
7704          if (method && var == method->getSelfDecl())
7705            Diag = method->isClassMethod()
7706              ? diag::err_typecheck_arc_assign_self_class_method
7707              : diag::err_typecheck_arc_assign_self;
7708
7709          //  - fast enumeration variables
7710          else
7711            Diag = diag::err_typecheck_arr_assign_enumeration;
7712
7713          SourceRange Assign;
7714          if (Loc != OrigLoc)
7715            Assign = SourceRange(OrigLoc, OrigLoc);
7716          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7717          // We need to preserve the AST regardless, so migration tool
7718          // can do its job.
7719          return false;
7720        }
7721      }
7722    }
7723
7724    break;
7725  case Expr::MLV_ArrayType:
7726  case Expr::MLV_ArrayTemporary:
7727    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7728    NeedType = true;
7729    break;
7730  case Expr::MLV_NotObjectType:
7731    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7732    NeedType = true;
7733    break;
7734  case Expr::MLV_LValueCast:
7735    Diag = diag::err_typecheck_lvalue_casts_not_supported;
7736    break;
7737  case Expr::MLV_Valid:
7738    llvm_unreachable("did not take early return for MLV_Valid");
7739  case Expr::MLV_InvalidExpression:
7740  case Expr::MLV_MemberFunction:
7741  case Expr::MLV_ClassTemporary:
7742    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7743    break;
7744  case Expr::MLV_IncompleteType:
7745  case Expr::MLV_IncompleteVoidType:
7746    return S.RequireCompleteType(Loc, E->getType(),
7747             diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7748  case Expr::MLV_DuplicateVectorComponents:
7749    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7750    break;
7751  case Expr::MLV_ReadonlyProperty:
7752  case Expr::MLV_NoSetterProperty:
7753    llvm_unreachable("readonly properties should be processed differently");
7754  case Expr::MLV_InvalidMessageExpression:
7755    Diag = diag::error_readonly_message_assignment;
7756    break;
7757  case Expr::MLV_SubObjCPropertySetting:
7758    Diag = diag::error_no_subobject_property_setting;
7759    break;
7760  }
7761
7762  SourceRange Assign;
7763  if (Loc != OrigLoc)
7764    Assign = SourceRange(OrigLoc, OrigLoc);
7765  if (NeedType)
7766    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7767  else
7768    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7769  return true;
7770}
7771
7772static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7773                                         SourceLocation Loc,
7774                                         Sema &Sema) {
7775  // C / C++ fields
7776  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7777  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7778  if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7779    if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7780      Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7781  }
7782
7783  // Objective-C instance variables
7784  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7785  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7786  if (OL && OR && OL->getDecl() == OR->getDecl()) {
7787    DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7788    DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7789    if (RL && RR && RL->getDecl() == RR->getDecl())
7790      Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7791  }
7792}
7793
7794// C99 6.5.16.1
7795QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7796                                       SourceLocation Loc,
7797                                       QualType CompoundType) {
7798  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7799
7800  // Verify that LHS is a modifiable lvalue, and emit error if not.
7801  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7802    return QualType();
7803
7804  QualType LHSType = LHSExpr->getType();
7805  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7806                                             CompoundType;
7807  AssignConvertType ConvTy;
7808  if (CompoundType.isNull()) {
7809    Expr *RHSCheck = RHS.get();
7810
7811    CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7812
7813    QualType LHSTy(LHSType);
7814    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7815    if (RHS.isInvalid())
7816      return QualType();
7817    // Special case of NSObject attributes on c-style pointer types.
7818    if (ConvTy == IncompatiblePointer &&
7819        ((Context.isObjCNSObjectType(LHSType) &&
7820          RHSType->isObjCObjectPointerType()) ||
7821         (Context.isObjCNSObjectType(RHSType) &&
7822          LHSType->isObjCObjectPointerType())))
7823      ConvTy = Compatible;
7824
7825    if (ConvTy == Compatible &&
7826        LHSType->isObjCObjectType())
7827        Diag(Loc, diag::err_objc_object_assignment)
7828          << LHSType;
7829
7830    // If the RHS is a unary plus or minus, check to see if they = and + are
7831    // right next to each other.  If so, the user may have typo'd "x =+ 4"
7832    // instead of "x += 4".
7833    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7834      RHSCheck = ICE->getSubExpr();
7835    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7836      if ((UO->getOpcode() == UO_Plus ||
7837           UO->getOpcode() == UO_Minus) &&
7838          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7839          // Only if the two operators are exactly adjacent.
7840          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7841          // And there is a space or other character before the subexpr of the
7842          // unary +/-.  We don't want to warn on "x=-1".
7843          Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7844          UO->getSubExpr()->getLocStart().isFileID()) {
7845        Diag(Loc, diag::warn_not_compound_assign)
7846          << (UO->getOpcode() == UO_Plus ? "+" : "-")
7847          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7848      }
7849    }
7850
7851    if (ConvTy == Compatible) {
7852      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7853        // Warn about retain cycles where a block captures the LHS, but
7854        // not if the LHS is a simple variable into which the block is
7855        // being stored...unless that variable can be captured by reference!
7856        const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7857        const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7858        if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7859          checkRetainCycles(LHSExpr, RHS.get());
7860
7861        // It is safe to assign a weak reference into a strong variable.
7862        // Although this code can still have problems:
7863        //   id x = self.weakProp;
7864        //   id y = self.weakProp;
7865        // we do not warn to warn spuriously when 'x' and 'y' are on separate
7866        // paths through the function. This should be revisited if
7867        // -Wrepeated-use-of-weak is made flow-sensitive.
7868        DiagnosticsEngine::Level Level =
7869          Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7870                                   RHS.get()->getLocStart());
7871        if (Level != DiagnosticsEngine::Ignored)
7872          getCurFunction()->markSafeWeakUse(RHS.get());
7873
7874      } else if (getLangOpts().ObjCAutoRefCount) {
7875        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7876      }
7877    }
7878  } else {
7879    // Compound assignment "x += y"
7880    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7881  }
7882
7883  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7884                               RHS.get(), AA_Assigning))
7885    return QualType();
7886
7887  CheckForNullPointerDereference(*this, LHSExpr);
7888
7889  // C99 6.5.16p3: The type of an assignment expression is the type of the
7890  // left operand unless the left operand has qualified type, in which case
7891  // it is the unqualified version of the type of the left operand.
7892  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7893  // is converted to the type of the assignment expression (above).
7894  // C++ 5.17p1: the type of the assignment expression is that of its left
7895  // operand.
7896  return (getLangOpts().CPlusPlus
7897          ? LHSType : LHSType.getUnqualifiedType());
7898}
7899
7900// C99 6.5.17
7901static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7902                                   SourceLocation Loc) {
7903  LHS = S.CheckPlaceholderExpr(LHS.take());
7904  RHS = S.CheckPlaceholderExpr(RHS.take());
7905  if (LHS.isInvalid() || RHS.isInvalid())
7906    return QualType();
7907
7908  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7909  // operands, but not unary promotions.
7910  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7911
7912  // So we treat the LHS as a ignored value, and in C++ we allow the
7913  // containing site to determine what should be done with the RHS.
7914  LHS = S.IgnoredValueConversions(LHS.take());
7915  if (LHS.isInvalid())
7916    return QualType();
7917
7918  S.DiagnoseUnusedExprResult(LHS.get());
7919
7920  if (!S.getLangOpts().CPlusPlus) {
7921    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7922    if (RHS.isInvalid())
7923      return QualType();
7924    if (!RHS.get()->getType()->isVoidType())
7925      S.RequireCompleteType(Loc, RHS.get()->getType(),
7926                            diag::err_incomplete_type);
7927  }
7928
7929  return RHS.get()->getType();
7930}
7931
7932/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7933/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7934static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7935                                               ExprValueKind &VK,
7936                                               SourceLocation OpLoc,
7937                                               bool IsInc, bool IsPrefix) {
7938  if (Op->isTypeDependent())
7939    return S.Context.DependentTy;
7940
7941  QualType ResType = Op->getType();
7942  // Atomic types can be used for increment / decrement where the non-atomic
7943  // versions can, so ignore the _Atomic() specifier for the purpose of
7944  // checking.
7945  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7946    ResType = ResAtomicType->getValueType();
7947
7948  assert(!ResType.isNull() && "no type for increment/decrement expression");
7949
7950  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7951    // Decrement of bool is not allowed.
7952    if (!IsInc) {
7953      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7954      return QualType();
7955    }
7956    // Increment of bool sets it to true, but is deprecated.
7957    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7958  } else if (ResType->isRealType()) {
7959    // OK!
7960  } else if (ResType->isPointerType()) {
7961    // C99 6.5.2.4p2, 6.5.6p2
7962    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7963      return QualType();
7964  } else if (ResType->isObjCObjectPointerType()) {
7965    // On modern runtimes, ObjC pointer arithmetic is forbidden.
7966    // Otherwise, we just need a complete type.
7967    if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7968        checkArithmeticOnObjCPointer(S, OpLoc, Op))
7969      return QualType();
7970  } else if (ResType->isAnyComplexType()) {
7971    // C99 does not support ++/-- on complex types, we allow as an extension.
7972    S.Diag(OpLoc, diag::ext_integer_increment_complex)
7973      << ResType << Op->getSourceRange();
7974  } else if (ResType->isPlaceholderType()) {
7975    ExprResult PR = S.CheckPlaceholderExpr(Op);
7976    if (PR.isInvalid()) return QualType();
7977    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7978                                          IsInc, IsPrefix);
7979  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7980    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7981  } else {
7982    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7983      << ResType << int(IsInc) << Op->getSourceRange();
7984    return QualType();
7985  }
7986  // At this point, we know we have a real, complex or pointer type.
7987  // Now make sure the operand is a modifiable lvalue.
7988  if (CheckForModifiableLvalue(Op, OpLoc, S))
7989    return QualType();
7990  // In C++, a prefix increment is the same type as the operand. Otherwise
7991  // (in C or with postfix), the increment is the unqualified type of the
7992  // operand.
7993  if (IsPrefix && S.getLangOpts().CPlusPlus) {
7994    VK = VK_LValue;
7995    return ResType;
7996  } else {
7997    VK = VK_RValue;
7998    return ResType.getUnqualifiedType();
7999  }
8000}
8001
8002
8003/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8004/// This routine allows us to typecheck complex/recursive expressions
8005/// where the declaration is needed for type checking. We only need to
8006/// handle cases when the expression references a function designator
8007/// or is an lvalue. Here are some examples:
8008///  - &(x) => x
8009///  - &*****f => f for f a function designator.
8010///  - &s.xx => s
8011///  - &s.zz[1].yy -> s, if zz is an array
8012///  - *(x + 1) -> x, if x is an array
8013///  - &"123"[2] -> 0
8014///  - & __real__ x -> x
8015static ValueDecl *getPrimaryDecl(Expr *E) {
8016  switch (E->getStmtClass()) {
8017  case Stmt::DeclRefExprClass:
8018    return cast<DeclRefExpr>(E)->getDecl();
8019  case Stmt::MemberExprClass:
8020    // If this is an arrow operator, the address is an offset from
8021    // the base's value, so the object the base refers to is
8022    // irrelevant.
8023    if (cast<MemberExpr>(E)->isArrow())
8024      return 0;
8025    // Otherwise, the expression refers to a part of the base
8026    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8027  case Stmt::ArraySubscriptExprClass: {
8028    // FIXME: This code shouldn't be necessary!  We should catch the implicit
8029    // promotion of register arrays earlier.
8030    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8031    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8032      if (ICE->getSubExpr()->getType()->isArrayType())
8033        return getPrimaryDecl(ICE->getSubExpr());
8034    }
8035    return 0;
8036  }
8037  case Stmt::UnaryOperatorClass: {
8038    UnaryOperator *UO = cast<UnaryOperator>(E);
8039
8040    switch(UO->getOpcode()) {
8041    case UO_Real:
8042    case UO_Imag:
8043    case UO_Extension:
8044      return getPrimaryDecl(UO->getSubExpr());
8045    default:
8046      return 0;
8047    }
8048  }
8049  case Stmt::ParenExprClass:
8050    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8051  case Stmt::ImplicitCastExprClass:
8052    // If the result of an implicit cast is an l-value, we care about
8053    // the sub-expression; otherwise, the result here doesn't matter.
8054    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8055  default:
8056    return 0;
8057  }
8058}
8059
8060namespace {
8061  enum {
8062    AO_Bit_Field = 0,
8063    AO_Vector_Element = 1,
8064    AO_Property_Expansion = 2,
8065    AO_Register_Variable = 3,
8066    AO_No_Error = 4
8067  };
8068}
8069/// \brief Diagnose invalid operand for address of operations.
8070///
8071/// \param Type The type of operand which cannot have its address taken.
8072static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8073                                         Expr *E, unsigned Type) {
8074  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8075}
8076
8077/// CheckAddressOfOperand - The operand of & must be either a function
8078/// designator or an lvalue designating an object. If it is an lvalue, the
8079/// object cannot be declared with storage class register or be a bit field.
8080/// Note: The usual conversions are *not* applied to the operand of the &
8081/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8082/// In C++, the operand might be an overloaded function name, in which case
8083/// we allow the '&' but retain the overloaded-function type.
8084static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
8085                                      SourceLocation OpLoc) {
8086  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8087    if (PTy->getKind() == BuiltinType::Overload) {
8088      if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8089        assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8090                 == UO_AddrOf);
8091        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8092          << OrigOp.get()->getSourceRange();
8093        return QualType();
8094      }
8095
8096      return S.Context.OverloadTy;
8097    }
8098
8099    if (PTy->getKind() == BuiltinType::UnknownAny)
8100      return S.Context.UnknownAnyTy;
8101
8102    if (PTy->getKind() == BuiltinType::BoundMember) {
8103      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8104        << OrigOp.get()->getSourceRange();
8105      return QualType();
8106    }
8107
8108    OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8109    if (OrigOp.isInvalid()) return QualType();
8110  }
8111
8112  if (OrigOp.get()->isTypeDependent())
8113    return S.Context.DependentTy;
8114
8115  assert(!OrigOp.get()->getType()->isPlaceholderType());
8116
8117  // Make sure to ignore parentheses in subsequent checks
8118  Expr *op = OrigOp.get()->IgnoreParens();
8119
8120  if (S.getLangOpts().C99) {
8121    // Implement C99-only parts of addressof rules.
8122    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8123      if (uOp->getOpcode() == UO_Deref)
8124        // Per C99 6.5.3.2, the address of a deref always returns a valid result
8125        // (assuming the deref expression is valid).
8126        return uOp->getSubExpr()->getType();
8127    }
8128    // Technically, there should be a check for array subscript
8129    // expressions here, but the result of one is always an lvalue anyway.
8130  }
8131  ValueDecl *dcl = getPrimaryDecl(op);
8132  Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8133  unsigned AddressOfError = AO_No_Error;
8134
8135  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8136    bool sfinae = (bool)S.isSFINAEContext();
8137    S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8138                         : diag::ext_typecheck_addrof_temporary)
8139      << op->getType() << op->getSourceRange();
8140    if (sfinae)
8141      return QualType();
8142  } else if (isa<ObjCSelectorExpr>(op)) {
8143    return S.Context.getPointerType(op->getType());
8144  } else if (lval == Expr::LV_MemberFunction) {
8145    // If it's an instance method, make a member pointer.
8146    // The expression must have exactly the form &A::foo.
8147
8148    // If the underlying expression isn't a decl ref, give up.
8149    if (!isa<DeclRefExpr>(op)) {
8150      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8151        << OrigOp.get()->getSourceRange();
8152      return QualType();
8153    }
8154    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8155    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8156
8157    // The id-expression was parenthesized.
8158    if (OrigOp.get() != DRE) {
8159      S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8160        << OrigOp.get()->getSourceRange();
8161
8162    // The method was named without a qualifier.
8163    } else if (!DRE->getQualifier()) {
8164      if (MD->getParent()->getName().empty())
8165        S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8166          << op->getSourceRange();
8167      else {
8168        SmallString<32> Str;
8169        StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8170        S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8171          << op->getSourceRange()
8172          << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8173      }
8174    }
8175
8176    return S.Context.getMemberPointerType(op->getType(),
8177              S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8178  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8179    // C99 6.5.3.2p1
8180    // The operand must be either an l-value or a function designator
8181    if (!op->getType()->isFunctionType()) {
8182      // Use a special diagnostic for loads from property references.
8183      if (isa<PseudoObjectExpr>(op)) {
8184        AddressOfError = AO_Property_Expansion;
8185      } else {
8186        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8187          << op->getType() << op->getSourceRange();
8188        return QualType();
8189      }
8190    }
8191  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8192    // The operand cannot be a bit-field
8193    AddressOfError = AO_Bit_Field;
8194  } else if (op->getObjectKind() == OK_VectorComponent) {
8195    // The operand cannot be an element of a vector
8196    AddressOfError = AO_Vector_Element;
8197  } else if (dcl) { // C99 6.5.3.2p1
8198    // We have an lvalue with a decl. Make sure the decl is not declared
8199    // with the register storage-class specifier.
8200    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8201      // in C++ it is not error to take address of a register
8202      // variable (c++03 7.1.1P3)
8203      if (vd->getStorageClass() == SC_Register &&
8204          !S.getLangOpts().CPlusPlus) {
8205        AddressOfError = AO_Register_Variable;
8206      }
8207    } else if (isa<FunctionTemplateDecl>(dcl)) {
8208      return S.Context.OverloadTy;
8209    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8210      // Okay: we can take the address of a field.
8211      // Could be a pointer to member, though, if there is an explicit
8212      // scope qualifier for the class.
8213      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8214        DeclContext *Ctx = dcl->getDeclContext();
8215        if (Ctx && Ctx->isRecord()) {
8216          if (dcl->getType()->isReferenceType()) {
8217            S.Diag(OpLoc,
8218                   diag::err_cannot_form_pointer_to_member_of_reference_type)
8219              << dcl->getDeclName() << dcl->getType();
8220            return QualType();
8221          }
8222
8223          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8224            Ctx = Ctx->getParent();
8225          return S.Context.getMemberPointerType(op->getType(),
8226                S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8227        }
8228      }
8229    } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8230      llvm_unreachable("Unknown/unexpected decl type");
8231  }
8232
8233  if (AddressOfError != AO_No_Error) {
8234    diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8235    return QualType();
8236  }
8237
8238  if (lval == Expr::LV_IncompleteVoidType) {
8239    // Taking the address of a void variable is technically illegal, but we
8240    // allow it in cases which are otherwise valid.
8241    // Example: "extern void x; void* y = &x;".
8242    S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8243  }
8244
8245  // If the operand has type "type", the result has type "pointer to type".
8246  if (op->getType()->isObjCObjectType())
8247    return S.Context.getObjCObjectPointerType(op->getType());
8248  return S.Context.getPointerType(op->getType());
8249}
8250
8251/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8252static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8253                                        SourceLocation OpLoc) {
8254  if (Op->isTypeDependent())
8255    return S.Context.DependentTy;
8256
8257  ExprResult ConvResult = S.UsualUnaryConversions(Op);
8258  if (ConvResult.isInvalid())
8259    return QualType();
8260  Op = ConvResult.take();
8261  QualType OpTy = Op->getType();
8262  QualType Result;
8263
8264  if (isa<CXXReinterpretCastExpr>(Op)) {
8265    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8266    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8267                                     Op->getSourceRange());
8268  }
8269
8270  // Note that per both C89 and C99, indirection is always legal, even if OpTy
8271  // is an incomplete type or void.  It would be possible to warn about
8272  // dereferencing a void pointer, but it's completely well-defined, and such a
8273  // warning is unlikely to catch any mistakes.
8274  if (const PointerType *PT = OpTy->getAs<PointerType>())
8275    Result = PT->getPointeeType();
8276  else if (const ObjCObjectPointerType *OPT =
8277             OpTy->getAs<ObjCObjectPointerType>())
8278    Result = OPT->getPointeeType();
8279  else {
8280    ExprResult PR = S.CheckPlaceholderExpr(Op);
8281    if (PR.isInvalid()) return QualType();
8282    if (PR.take() != Op)
8283      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8284  }
8285
8286  if (Result.isNull()) {
8287    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8288      << OpTy << Op->getSourceRange();
8289    return QualType();
8290  }
8291
8292  // Dereferences are usually l-values...
8293  VK = VK_LValue;
8294
8295  // ...except that certain expressions are never l-values in C.
8296  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8297    VK = VK_RValue;
8298
8299  return Result;
8300}
8301
8302static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8303  tok::TokenKind Kind) {
8304  BinaryOperatorKind Opc;
8305  switch (Kind) {
8306  default: llvm_unreachable("Unknown binop!");
8307  case tok::periodstar:           Opc = BO_PtrMemD; break;
8308  case tok::arrowstar:            Opc = BO_PtrMemI; break;
8309  case tok::star:                 Opc = BO_Mul; break;
8310  case tok::slash:                Opc = BO_Div; break;
8311  case tok::percent:              Opc = BO_Rem; break;
8312  case tok::plus:                 Opc = BO_Add; break;
8313  case tok::minus:                Opc = BO_Sub; break;
8314  case tok::lessless:             Opc = BO_Shl; break;
8315  case tok::greatergreater:       Opc = BO_Shr; break;
8316  case tok::lessequal:            Opc = BO_LE; break;
8317  case tok::less:                 Opc = BO_LT; break;
8318  case tok::greaterequal:         Opc = BO_GE; break;
8319  case tok::greater:              Opc = BO_GT; break;
8320  case tok::exclaimequal:         Opc = BO_NE; break;
8321  case tok::equalequal:           Opc = BO_EQ; break;
8322  case tok::amp:                  Opc = BO_And; break;
8323  case tok::caret:                Opc = BO_Xor; break;
8324  case tok::pipe:                 Opc = BO_Or; break;
8325  case tok::ampamp:               Opc = BO_LAnd; break;
8326  case tok::pipepipe:             Opc = BO_LOr; break;
8327  case tok::equal:                Opc = BO_Assign; break;
8328  case tok::starequal:            Opc = BO_MulAssign; break;
8329  case tok::slashequal:           Opc = BO_DivAssign; break;
8330  case tok::percentequal:         Opc = BO_RemAssign; break;
8331  case tok::plusequal:            Opc = BO_AddAssign; break;
8332  case tok::minusequal:           Opc = BO_SubAssign; break;
8333  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8334  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8335  case tok::ampequal:             Opc = BO_AndAssign; break;
8336  case tok::caretequal:           Opc = BO_XorAssign; break;
8337  case tok::pipeequal:            Opc = BO_OrAssign; break;
8338  case tok::comma:                Opc = BO_Comma; break;
8339  }
8340  return Opc;
8341}
8342
8343static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8344  tok::TokenKind Kind) {
8345  UnaryOperatorKind Opc;
8346  switch (Kind) {
8347  default: llvm_unreachable("Unknown unary op!");
8348  case tok::plusplus:     Opc = UO_PreInc; break;
8349  case tok::minusminus:   Opc = UO_PreDec; break;
8350  case tok::amp:          Opc = UO_AddrOf; break;
8351  case tok::star:         Opc = UO_Deref; break;
8352  case tok::plus:         Opc = UO_Plus; break;
8353  case tok::minus:        Opc = UO_Minus; break;
8354  case tok::tilde:        Opc = UO_Not; break;
8355  case tok::exclaim:      Opc = UO_LNot; break;
8356  case tok::kw___real:    Opc = UO_Real; break;
8357  case tok::kw___imag:    Opc = UO_Imag; break;
8358  case tok::kw___extension__: Opc = UO_Extension; break;
8359  }
8360  return Opc;
8361}
8362
8363/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8364/// This warning is only emitted for builtin assignment operations. It is also
8365/// suppressed in the event of macro expansions.
8366static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8367                                   SourceLocation OpLoc) {
8368  if (!S.ActiveTemplateInstantiations.empty())
8369    return;
8370  if (OpLoc.isInvalid() || OpLoc.isMacroID())
8371    return;
8372  LHSExpr = LHSExpr->IgnoreParenImpCasts();
8373  RHSExpr = RHSExpr->IgnoreParenImpCasts();
8374  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8375  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8376  if (!LHSDeclRef || !RHSDeclRef ||
8377      LHSDeclRef->getLocation().isMacroID() ||
8378      RHSDeclRef->getLocation().isMacroID())
8379    return;
8380  const ValueDecl *LHSDecl =
8381    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8382  const ValueDecl *RHSDecl =
8383    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8384  if (LHSDecl != RHSDecl)
8385    return;
8386  if (LHSDecl->getType().isVolatileQualified())
8387    return;
8388  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8389    if (RefTy->getPointeeType().isVolatileQualified())
8390      return;
8391
8392  S.Diag(OpLoc, diag::warn_self_assignment)
8393      << LHSDeclRef->getType()
8394      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8395}
8396
8397/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8398/// operator @p Opc at location @c TokLoc. This routine only supports
8399/// built-in operations; ActOnBinOp handles overloaded operators.
8400ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8401                                    BinaryOperatorKind Opc,
8402                                    Expr *LHSExpr, Expr *RHSExpr) {
8403  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8404    // The syntax only allows initializer lists on the RHS of assignment,
8405    // so we don't need to worry about accepting invalid code for
8406    // non-assignment operators.
8407    // C++11 5.17p9:
8408    //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8409    //   of x = {} is x = T().
8410    InitializationKind Kind =
8411        InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8412    InitializedEntity Entity =
8413        InitializedEntity::InitializeTemporary(LHSExpr->getType());
8414    InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8415    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8416    if (Init.isInvalid())
8417      return Init;
8418    RHSExpr = Init.take();
8419  }
8420
8421  ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8422  QualType ResultTy;     // Result type of the binary operator.
8423  // The following two variables are used for compound assignment operators
8424  QualType CompLHSTy;    // Type of LHS after promotions for computation
8425  QualType CompResultTy; // Type of computation result
8426  ExprValueKind VK = VK_RValue;
8427  ExprObjectKind OK = OK_Ordinary;
8428
8429  switch (Opc) {
8430  case BO_Assign:
8431    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8432    if (getLangOpts().CPlusPlus &&
8433        LHS.get()->getObjectKind() != OK_ObjCProperty) {
8434      VK = LHS.get()->getValueKind();
8435      OK = LHS.get()->getObjectKind();
8436    }
8437    if (!ResultTy.isNull())
8438      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8439    break;
8440  case BO_PtrMemD:
8441  case BO_PtrMemI:
8442    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8443                                            Opc == BO_PtrMemI);
8444    break;
8445  case BO_Mul:
8446  case BO_Div:
8447    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8448                                           Opc == BO_Div);
8449    break;
8450  case BO_Rem:
8451    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8452    break;
8453  case BO_Add:
8454    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8455    break;
8456  case BO_Sub:
8457    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8458    break;
8459  case BO_Shl:
8460  case BO_Shr:
8461    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8462    break;
8463  case BO_LE:
8464  case BO_LT:
8465  case BO_GE:
8466  case BO_GT:
8467    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8468    break;
8469  case BO_EQ:
8470  case BO_NE:
8471    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8472    break;
8473  case BO_And:
8474  case BO_Xor:
8475  case BO_Or:
8476    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8477    break;
8478  case BO_LAnd:
8479  case BO_LOr:
8480    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8481    break;
8482  case BO_MulAssign:
8483  case BO_DivAssign:
8484    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8485                                               Opc == BO_DivAssign);
8486    CompLHSTy = CompResultTy;
8487    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8488      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8489    break;
8490  case BO_RemAssign:
8491    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8492    CompLHSTy = CompResultTy;
8493    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8494      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8495    break;
8496  case BO_AddAssign:
8497    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8498    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8499      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8500    break;
8501  case BO_SubAssign:
8502    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8503    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8504      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8505    break;
8506  case BO_ShlAssign:
8507  case BO_ShrAssign:
8508    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8509    CompLHSTy = CompResultTy;
8510    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8511      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8512    break;
8513  case BO_AndAssign:
8514  case BO_XorAssign:
8515  case BO_OrAssign:
8516    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8517    CompLHSTy = CompResultTy;
8518    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8519      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8520    break;
8521  case BO_Comma:
8522    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8523    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8524      VK = RHS.get()->getValueKind();
8525      OK = RHS.get()->getObjectKind();
8526    }
8527    break;
8528  }
8529  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8530    return ExprError();
8531
8532  // Check for array bounds violations for both sides of the BinaryOperator
8533  CheckArrayAccess(LHS.get());
8534  CheckArrayAccess(RHS.get());
8535
8536  if (CompResultTy.isNull())
8537    return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8538                                              ResultTy, VK, OK, OpLoc,
8539                                              FPFeatures.fp_contract));
8540  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8541      OK_ObjCProperty) {
8542    VK = VK_LValue;
8543    OK = LHS.get()->getObjectKind();
8544  }
8545  return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8546                                                    ResultTy, VK, OK, CompLHSTy,
8547                                                    CompResultTy, OpLoc,
8548                                                    FPFeatures.fp_contract));
8549}
8550
8551/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8552/// operators are mixed in a way that suggests that the programmer forgot that
8553/// comparison operators have higher precedence. The most typical example of
8554/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8555static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8556                                      SourceLocation OpLoc, Expr *LHSExpr,
8557                                      Expr *RHSExpr) {
8558  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8559  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
8560
8561  // Check that one of the sides is a comparison operator.
8562  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8563  bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8564  if (!isLeftComp && !isRightComp)
8565    return;
8566
8567  // Bitwise operations are sometimes used as eager logical ops.
8568  // Don't diagnose this.
8569  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8570  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8571  if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
8572    return;
8573
8574  SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8575                                                   OpLoc)
8576                                     : SourceRange(OpLoc, RHSExpr->getLocEnd());
8577  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
8578  SourceRange ParensRange = isLeftComp ?
8579      SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8580    : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
8581
8582  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8583    << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
8584  SuggestParentheses(Self, OpLoc,
8585    Self.PDiag(diag::note_precedence_silence) << OpStr,
8586    (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8587  SuggestParentheses(Self, OpLoc,
8588    Self.PDiag(diag::note_precedence_bitwise_first)
8589      << BinaryOperator::getOpcodeStr(Opc),
8590    ParensRange);
8591}
8592
8593/// \brief It accepts a '&' expr that is inside a '|' one.
8594/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8595/// in parentheses.
8596static void
8597EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8598                                       BinaryOperator *Bop) {
8599  assert(Bop->getOpcode() == BO_And);
8600  Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8601      << Bop->getSourceRange() << OpLoc;
8602  SuggestParentheses(Self, Bop->getOperatorLoc(),
8603    Self.PDiag(diag::note_precedence_silence)
8604      << Bop->getOpcodeStr(),
8605    Bop->getSourceRange());
8606}
8607
8608/// \brief It accepts a '&&' expr that is inside a '||' one.
8609/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8610/// in parentheses.
8611static void
8612EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8613                                       BinaryOperator *Bop) {
8614  assert(Bop->getOpcode() == BO_LAnd);
8615  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8616      << Bop->getSourceRange() << OpLoc;
8617  SuggestParentheses(Self, Bop->getOperatorLoc(),
8618    Self.PDiag(diag::note_precedence_silence)
8619      << Bop->getOpcodeStr(),
8620    Bop->getSourceRange());
8621}
8622
8623/// \brief Returns true if the given expression can be evaluated as a constant
8624/// 'true'.
8625static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8626  bool Res;
8627  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8628}
8629
8630/// \brief Returns true if the given expression can be evaluated as a constant
8631/// 'false'.
8632static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8633  bool Res;
8634  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8635}
8636
8637/// \brief Look for '&&' in the left hand of a '||' expr.
8638static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8639                                             Expr *LHSExpr, Expr *RHSExpr) {
8640  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8641    if (Bop->getOpcode() == BO_LAnd) {
8642      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8643      if (EvaluatesAsFalse(S, RHSExpr))
8644        return;
8645      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8646      if (!EvaluatesAsTrue(S, Bop->getLHS()))
8647        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8648    } else if (Bop->getOpcode() == BO_LOr) {
8649      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8650        // If it's "a || b && 1 || c" we didn't warn earlier for
8651        // "a || b && 1", but warn now.
8652        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8653          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8654      }
8655    }
8656  }
8657}
8658
8659/// \brief Look for '&&' in the right hand of a '||' expr.
8660static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8661                                             Expr *LHSExpr, Expr *RHSExpr) {
8662  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8663    if (Bop->getOpcode() == BO_LAnd) {
8664      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8665      if (EvaluatesAsFalse(S, LHSExpr))
8666        return;
8667      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8668      if (!EvaluatesAsTrue(S, Bop->getRHS()))
8669        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8670    }
8671  }
8672}
8673
8674/// \brief Look for '&' in the left or right hand of a '|' expr.
8675static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8676                                             Expr *OrArg) {
8677  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8678    if (Bop->getOpcode() == BO_And)
8679      return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8680  }
8681}
8682
8683static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8684                                    Expr *SubExpr, StringRef Shift) {
8685  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8686    if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8687      StringRef Op = Bop->getOpcodeStr();
8688      S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8689          << Bop->getSourceRange() << OpLoc << Shift << Op;
8690      SuggestParentheses(S, Bop->getOperatorLoc(),
8691          S.PDiag(diag::note_precedence_silence) << Op,
8692          Bop->getSourceRange());
8693    }
8694  }
8695}
8696
8697/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8698/// precedence.
8699static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8700                                    SourceLocation OpLoc, Expr *LHSExpr,
8701                                    Expr *RHSExpr){
8702  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8703  if (BinaryOperator::isBitwiseOp(Opc))
8704    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8705
8706  // Diagnose "arg1 & arg2 | arg3"
8707  if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8708    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8709    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8710  }
8711
8712  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8713  // We don't warn for 'assert(a || b && "bad")' since this is safe.
8714  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8715    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8716    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8717  }
8718
8719  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8720      || Opc == BO_Shr) {
8721    StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8722    DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8723    DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8724  }
8725}
8726
8727// Binary Operators.  'Tok' is the token for the operator.
8728ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8729                            tok::TokenKind Kind,
8730                            Expr *LHSExpr, Expr *RHSExpr) {
8731  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8732  assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8733  assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8734
8735  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8736  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8737
8738  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8739}
8740
8741/// Build an overloaded binary operator expression in the given scope.
8742static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8743                                       BinaryOperatorKind Opc,
8744                                       Expr *LHS, Expr *RHS) {
8745  // Find all of the overloaded operators visible from this
8746  // point. We perform both an operator-name lookup from the local
8747  // scope and an argument-dependent lookup based on the types of
8748  // the arguments.
8749  UnresolvedSet<16> Functions;
8750  OverloadedOperatorKind OverOp
8751    = BinaryOperator::getOverloadedOperator(Opc);
8752  if (Sc && OverOp != OO_None)
8753    S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8754                                   RHS->getType(), Functions);
8755
8756  // Build the (potentially-overloaded, potentially-dependent)
8757  // binary operation.
8758  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8759}
8760
8761ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8762                            BinaryOperatorKind Opc,
8763                            Expr *LHSExpr, Expr *RHSExpr) {
8764  // We want to end up calling one of checkPseudoObjectAssignment
8765  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8766  // both expressions are overloadable or either is type-dependent),
8767  // or CreateBuiltinBinOp (in any other case).  We also want to get
8768  // any placeholder types out of the way.
8769
8770  // Handle pseudo-objects in the LHS.
8771  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8772    // Assignments with a pseudo-object l-value need special analysis.
8773    if (pty->getKind() == BuiltinType::PseudoObject &&
8774        BinaryOperator::isAssignmentOp(Opc))
8775      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8776
8777    // Don't resolve overloads if the other type is overloadable.
8778    if (pty->getKind() == BuiltinType::Overload) {
8779      // We can't actually test that if we still have a placeholder,
8780      // though.  Fortunately, none of the exceptions we see in that
8781      // code below are valid when the LHS is an overload set.  Note
8782      // that an overload set can be dependently-typed, but it never
8783      // instantiates to having an overloadable type.
8784      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8785      if (resolvedRHS.isInvalid()) return ExprError();
8786      RHSExpr = resolvedRHS.take();
8787
8788      if (RHSExpr->isTypeDependent() ||
8789          RHSExpr->getType()->isOverloadableType())
8790        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8791    }
8792
8793    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8794    if (LHS.isInvalid()) return ExprError();
8795    LHSExpr = LHS.take();
8796  }
8797
8798  // Handle pseudo-objects in the RHS.
8799  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8800    // An overload in the RHS can potentially be resolved by the type
8801    // being assigned to.
8802    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8803      if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8804        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8805
8806      if (LHSExpr->getType()->isOverloadableType())
8807        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8808
8809      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8810    }
8811
8812    // Don't resolve overloads if the other type is overloadable.
8813    if (pty->getKind() == BuiltinType::Overload &&
8814        LHSExpr->getType()->isOverloadableType())
8815      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8816
8817    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8818    if (!resolvedRHS.isUsable()) return ExprError();
8819    RHSExpr = resolvedRHS.take();
8820  }
8821
8822  if (getLangOpts().CPlusPlus) {
8823    // If either expression is type-dependent, always build an
8824    // overloaded op.
8825    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8826      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8827
8828    // Otherwise, build an overloaded op if either expression has an
8829    // overloadable type.
8830    if (LHSExpr->getType()->isOverloadableType() ||
8831        RHSExpr->getType()->isOverloadableType())
8832      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8833  }
8834
8835  // Build a built-in binary operation.
8836  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8837}
8838
8839ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8840                                      UnaryOperatorKind Opc,
8841                                      Expr *InputExpr) {
8842  ExprResult Input = Owned(InputExpr);
8843  ExprValueKind VK = VK_RValue;
8844  ExprObjectKind OK = OK_Ordinary;
8845  QualType resultType;
8846  switch (Opc) {
8847  case UO_PreInc:
8848  case UO_PreDec:
8849  case UO_PostInc:
8850  case UO_PostDec:
8851    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8852                                                Opc == UO_PreInc ||
8853                                                Opc == UO_PostInc,
8854                                                Opc == UO_PreInc ||
8855                                                Opc == UO_PreDec);
8856    break;
8857  case UO_AddrOf:
8858    resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8859    break;
8860  case UO_Deref: {
8861    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8862    if (Input.isInvalid()) return ExprError();
8863    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8864    break;
8865  }
8866  case UO_Plus:
8867  case UO_Minus:
8868    Input = UsualUnaryConversions(Input.take());
8869    if (Input.isInvalid()) return ExprError();
8870    resultType = Input.get()->getType();
8871    if (resultType->isDependentType())
8872      break;
8873    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8874        resultType->isVectorType())
8875      break;
8876    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8877             resultType->isEnumeralType())
8878      break;
8879    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8880             Opc == UO_Plus &&
8881             resultType->isPointerType())
8882      break;
8883
8884    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8885      << resultType << Input.get()->getSourceRange());
8886
8887  case UO_Not: // bitwise complement
8888    Input = UsualUnaryConversions(Input.take());
8889    if (Input.isInvalid())
8890      return ExprError();
8891    resultType = Input.get()->getType();
8892    if (resultType->isDependentType())
8893      break;
8894    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8895    if (resultType->isComplexType() || resultType->isComplexIntegerType())
8896      // C99 does not support '~' for complex conjugation.
8897      Diag(OpLoc, diag::ext_integer_complement_complex)
8898          << resultType << Input.get()->getSourceRange();
8899    else if (resultType->hasIntegerRepresentation())
8900      break;
8901    else if (resultType->isExtVectorType()) {
8902      if (Context.getLangOpts().OpenCL) {
8903        // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
8904        // on vector float types.
8905        QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8906        if (!T->isIntegerType())
8907          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8908                           << resultType << Input.get()->getSourceRange());
8909      }
8910      break;
8911    } else {
8912      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8913                       << resultType << Input.get()->getSourceRange());
8914    }
8915    break;
8916
8917  case UO_LNot: // logical negation
8918    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8919    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8920    if (Input.isInvalid()) return ExprError();
8921    resultType = Input.get()->getType();
8922
8923    // Though we still have to promote half FP to float...
8924    if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
8925      Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8926      resultType = Context.FloatTy;
8927    }
8928
8929    if (resultType->isDependentType())
8930      break;
8931    if (resultType->isScalarType()) {
8932      // C99 6.5.3.3p1: ok, fallthrough;
8933      if (Context.getLangOpts().CPlusPlus) {
8934        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8935        // operand contextually converted to bool.
8936        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8937                                  ScalarTypeToBooleanCastKind(resultType));
8938      } else if (Context.getLangOpts().OpenCL &&
8939                 Context.getLangOpts().OpenCLVersion < 120) {
8940        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8941        // operate on scalar float types.
8942        if (!resultType->isIntegerType())
8943          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8944                           << resultType << Input.get()->getSourceRange());
8945      }
8946    } else if (resultType->isExtVectorType()) {
8947      if (Context.getLangOpts().OpenCL &&
8948          Context.getLangOpts().OpenCLVersion < 120) {
8949        // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8950        // operate on vector float types.
8951        QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8952        if (!T->isIntegerType())
8953          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8954                           << resultType << Input.get()->getSourceRange());
8955      }
8956      // Vector logical not returns the signed variant of the operand type.
8957      resultType = GetSignedVectorType(resultType);
8958      break;
8959    } else {
8960      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8961        << resultType << Input.get()->getSourceRange());
8962    }
8963
8964    // LNot always has type int. C99 6.5.3.3p5.
8965    // In C++, it's bool. C++ 5.3.1p8
8966    resultType = Context.getLogicalOperationType();
8967    break;
8968  case UO_Real:
8969  case UO_Imag:
8970    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8971    // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8972    // complex l-values to ordinary l-values and all other values to r-values.
8973    if (Input.isInvalid()) return ExprError();
8974    if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8975      if (Input.get()->getValueKind() != VK_RValue &&
8976          Input.get()->getObjectKind() == OK_Ordinary)
8977        VK = Input.get()->getValueKind();
8978    } else if (!getLangOpts().CPlusPlus) {
8979      // In C, a volatile scalar is read by __imag. In C++, it is not.
8980      Input = DefaultLvalueConversion(Input.take());
8981    }
8982    break;
8983  case UO_Extension:
8984    resultType = Input.get()->getType();
8985    VK = Input.get()->getValueKind();
8986    OK = Input.get()->getObjectKind();
8987    break;
8988  }
8989  if (resultType.isNull() || Input.isInvalid())
8990    return ExprError();
8991
8992  // Check for array bounds violations in the operand of the UnaryOperator,
8993  // except for the '*' and '&' operators that have to be handled specially
8994  // by CheckArrayAccess (as there are special cases like &array[arraysize]
8995  // that are explicitly defined as valid by the standard).
8996  if (Opc != UO_AddrOf && Opc != UO_Deref)
8997    CheckArrayAccess(Input.get());
8998
8999  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9000                                           VK, OK, OpLoc));
9001}
9002
9003/// \brief Determine whether the given expression is a qualified member
9004/// access expression, of a form that could be turned into a pointer to member
9005/// with the address-of operator.
9006static bool isQualifiedMemberAccess(Expr *E) {
9007  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9008    if (!DRE->getQualifier())
9009      return false;
9010
9011    ValueDecl *VD = DRE->getDecl();
9012    if (!VD->isCXXClassMember())
9013      return false;
9014
9015    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9016      return true;
9017    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9018      return Method->isInstance();
9019
9020    return false;
9021  }
9022
9023  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9024    if (!ULE->getQualifier())
9025      return false;
9026
9027    for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9028                                           DEnd = ULE->decls_end();
9029         D != DEnd; ++D) {
9030      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9031        if (Method->isInstance())
9032          return true;
9033      } else {
9034        // Overload set does not contain methods.
9035        break;
9036      }
9037    }
9038
9039    return false;
9040  }
9041
9042  return false;
9043}
9044
9045ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9046                              UnaryOperatorKind Opc, Expr *Input) {
9047  // First things first: handle placeholders so that the
9048  // overloaded-operator check considers the right type.
9049  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9050    // Increment and decrement of pseudo-object references.
9051    if (pty->getKind() == BuiltinType::PseudoObject &&
9052        UnaryOperator::isIncrementDecrementOp(Opc))
9053      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9054
9055    // extension is always a builtin operator.
9056    if (Opc == UO_Extension)
9057      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9058
9059    // & gets special logic for several kinds of placeholder.
9060    // The builtin code knows what to do.
9061    if (Opc == UO_AddrOf &&
9062        (pty->getKind() == BuiltinType::Overload ||
9063         pty->getKind() == BuiltinType::UnknownAny ||
9064         pty->getKind() == BuiltinType::BoundMember))
9065      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9066
9067    // Anything else needs to be handled now.
9068    ExprResult Result = CheckPlaceholderExpr(Input);
9069    if (Result.isInvalid()) return ExprError();
9070    Input = Result.take();
9071  }
9072
9073  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9074      UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9075      !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9076    // Find all of the overloaded operators visible from this
9077    // point. We perform both an operator-name lookup from the local
9078    // scope and an argument-dependent lookup based on the types of
9079    // the arguments.
9080    UnresolvedSet<16> Functions;
9081    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9082    if (S && OverOp != OO_None)
9083      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9084                                   Functions);
9085
9086    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9087  }
9088
9089  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9090}
9091
9092// Unary Operators.  'Tok' is the token for the operator.
9093ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9094                              tok::TokenKind Op, Expr *Input) {
9095  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9096}
9097
9098/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9099ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9100                                LabelDecl *TheDecl) {
9101  TheDecl->setUsed();
9102  // Create the AST node.  The address of a label always has type 'void*'.
9103  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9104                                       Context.getPointerType(Context.VoidTy)));
9105}
9106
9107/// Given the last statement in a statement-expression, check whether
9108/// the result is a producing expression (like a call to an
9109/// ns_returns_retained function) and, if so, rebuild it to hoist the
9110/// release out of the full-expression.  Otherwise, return null.
9111/// Cannot fail.
9112static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9113  // Should always be wrapped with one of these.
9114  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9115  if (!cleanups) return 0;
9116
9117  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9118  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9119    return 0;
9120
9121  // Splice out the cast.  This shouldn't modify any interesting
9122  // features of the statement.
9123  Expr *producer = cast->getSubExpr();
9124  assert(producer->getType() == cast->getType());
9125  assert(producer->getValueKind() == cast->getValueKind());
9126  cleanups->setSubExpr(producer);
9127  return cleanups;
9128}
9129
9130void Sema::ActOnStartStmtExpr() {
9131  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9132}
9133
9134void Sema::ActOnStmtExprError() {
9135  // Note that function is also called by TreeTransform when leaving a
9136  // StmtExpr scope without rebuilding anything.
9137
9138  DiscardCleanupsInEvaluationContext();
9139  PopExpressionEvaluationContext();
9140}
9141
9142ExprResult
9143Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9144                    SourceLocation RPLoc) { // "({..})"
9145  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9146  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9147
9148  if (hasAnyUnrecoverableErrorsInThisFunction())
9149    DiscardCleanupsInEvaluationContext();
9150  assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9151  PopExpressionEvaluationContext();
9152
9153  bool isFileScope
9154    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9155  if (isFileScope)
9156    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9157
9158  // FIXME: there are a variety of strange constraints to enforce here, for
9159  // example, it is not possible to goto into a stmt expression apparently.
9160  // More semantic analysis is needed.
9161
9162  // If there are sub stmts in the compound stmt, take the type of the last one
9163  // as the type of the stmtexpr.
9164  QualType Ty = Context.VoidTy;
9165  bool StmtExprMayBindToTemp = false;
9166  if (!Compound->body_empty()) {
9167    Stmt *LastStmt = Compound->body_back();
9168    LabelStmt *LastLabelStmt = 0;
9169    // If LastStmt is a label, skip down through into the body.
9170    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9171      LastLabelStmt = Label;
9172      LastStmt = Label->getSubStmt();
9173    }
9174
9175    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9176      // Do function/array conversion on the last expression, but not
9177      // lvalue-to-rvalue.  However, initialize an unqualified type.
9178      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9179      if (LastExpr.isInvalid())
9180        return ExprError();
9181      Ty = LastExpr.get()->getType().getUnqualifiedType();
9182
9183      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9184        // In ARC, if the final expression ends in a consume, splice
9185        // the consume out and bind it later.  In the alternate case
9186        // (when dealing with a retainable type), the result
9187        // initialization will create a produce.  In both cases the
9188        // result will be +1, and we'll need to balance that out with
9189        // a bind.
9190        if (Expr *rebuiltLastStmt
9191              = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9192          LastExpr = rebuiltLastStmt;
9193        } else {
9194          LastExpr = PerformCopyInitialization(
9195                            InitializedEntity::InitializeResult(LPLoc,
9196                                                                Ty,
9197                                                                false),
9198                                                   SourceLocation(),
9199                                               LastExpr);
9200        }
9201
9202        if (LastExpr.isInvalid())
9203          return ExprError();
9204        if (LastExpr.get() != 0) {
9205          if (!LastLabelStmt)
9206            Compound->setLastStmt(LastExpr.take());
9207          else
9208            LastLabelStmt->setSubStmt(LastExpr.take());
9209          StmtExprMayBindToTemp = true;
9210        }
9211      }
9212    }
9213  }
9214
9215  // FIXME: Check that expression type is complete/non-abstract; statement
9216  // expressions are not lvalues.
9217  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9218  if (StmtExprMayBindToTemp)
9219    return MaybeBindToTemporary(ResStmtExpr);
9220  return Owned(ResStmtExpr);
9221}
9222
9223ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9224                                      TypeSourceInfo *TInfo,
9225                                      OffsetOfComponent *CompPtr,
9226                                      unsigned NumComponents,
9227                                      SourceLocation RParenLoc) {
9228  QualType ArgTy = TInfo->getType();
9229  bool Dependent = ArgTy->isDependentType();
9230  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9231
9232  // We must have at least one component that refers to the type, and the first
9233  // one is known to be a field designator.  Verify that the ArgTy represents
9234  // a struct/union/class.
9235  if (!Dependent && !ArgTy->isRecordType())
9236    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9237                       << ArgTy << TypeRange);
9238
9239  // Type must be complete per C99 7.17p3 because a declaring a variable
9240  // with an incomplete type would be ill-formed.
9241  if (!Dependent
9242      && RequireCompleteType(BuiltinLoc, ArgTy,
9243                             diag::err_offsetof_incomplete_type, TypeRange))
9244    return ExprError();
9245
9246  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9247  // GCC extension, diagnose them.
9248  // FIXME: This diagnostic isn't actually visible because the location is in
9249  // a system header!
9250  if (NumComponents != 1)
9251    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9252      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9253
9254  bool DidWarnAboutNonPOD = false;
9255  QualType CurrentType = ArgTy;
9256  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9257  SmallVector<OffsetOfNode, 4> Comps;
9258  SmallVector<Expr*, 4> Exprs;
9259  for (unsigned i = 0; i != NumComponents; ++i) {
9260    const OffsetOfComponent &OC = CompPtr[i];
9261    if (OC.isBrackets) {
9262      // Offset of an array sub-field.  TODO: Should we allow vector elements?
9263      if (!CurrentType->isDependentType()) {
9264        const ArrayType *AT = Context.getAsArrayType(CurrentType);
9265        if(!AT)
9266          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9267                           << CurrentType);
9268        CurrentType = AT->getElementType();
9269      } else
9270        CurrentType = Context.DependentTy;
9271
9272      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9273      if (IdxRval.isInvalid())
9274        return ExprError();
9275      Expr *Idx = IdxRval.take();
9276
9277      // The expression must be an integral expression.
9278      // FIXME: An integral constant expression?
9279      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9280          !Idx->getType()->isIntegerType())
9281        return ExprError(Diag(Idx->getLocStart(),
9282                              diag::err_typecheck_subscript_not_integer)
9283                         << Idx->getSourceRange());
9284
9285      // Record this array index.
9286      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9287      Exprs.push_back(Idx);
9288      continue;
9289    }
9290
9291    // Offset of a field.
9292    if (CurrentType->isDependentType()) {
9293      // We have the offset of a field, but we can't look into the dependent
9294      // type. Just record the identifier of the field.
9295      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9296      CurrentType = Context.DependentTy;
9297      continue;
9298    }
9299
9300    // We need to have a complete type to look into.
9301    if (RequireCompleteType(OC.LocStart, CurrentType,
9302                            diag::err_offsetof_incomplete_type))
9303      return ExprError();
9304
9305    // Look for the designated field.
9306    const RecordType *RC = CurrentType->getAs<RecordType>();
9307    if (!RC)
9308      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9309                       << CurrentType);
9310    RecordDecl *RD = RC->getDecl();
9311
9312    // C++ [lib.support.types]p5:
9313    //   The macro offsetof accepts a restricted set of type arguments in this
9314    //   International Standard. type shall be a POD structure or a POD union
9315    //   (clause 9).
9316    // C++11 [support.types]p4:
9317    //   If type is not a standard-layout class (Clause 9), the results are
9318    //   undefined.
9319    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9320      bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9321      unsigned DiagID =
9322        LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9323                            : diag::warn_offsetof_non_pod_type;
9324
9325      if (!IsSafe && !DidWarnAboutNonPOD &&
9326          DiagRuntimeBehavior(BuiltinLoc, 0,
9327                              PDiag(DiagID)
9328                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9329                              << CurrentType))
9330        DidWarnAboutNonPOD = true;
9331    }
9332
9333    // Look for the field.
9334    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9335    LookupQualifiedName(R, RD);
9336    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9337    IndirectFieldDecl *IndirectMemberDecl = 0;
9338    if (!MemberDecl) {
9339      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9340        MemberDecl = IndirectMemberDecl->getAnonField();
9341    }
9342
9343    if (!MemberDecl)
9344      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9345                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9346                                                              OC.LocEnd));
9347
9348    // C99 7.17p3:
9349    //   (If the specified member is a bit-field, the behavior is undefined.)
9350    //
9351    // We diagnose this as an error.
9352    if (MemberDecl->isBitField()) {
9353      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9354        << MemberDecl->getDeclName()
9355        << SourceRange(BuiltinLoc, RParenLoc);
9356      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9357      return ExprError();
9358    }
9359
9360    RecordDecl *Parent = MemberDecl->getParent();
9361    if (IndirectMemberDecl)
9362      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9363
9364    // If the member was found in a base class, introduce OffsetOfNodes for
9365    // the base class indirections.
9366    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9367                       /*DetectVirtual=*/false);
9368    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9369      CXXBasePath &Path = Paths.front();
9370      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9371           B != BEnd; ++B)
9372        Comps.push_back(OffsetOfNode(B->Base));
9373    }
9374
9375    if (IndirectMemberDecl) {
9376      for (IndirectFieldDecl::chain_iterator FI =
9377           IndirectMemberDecl->chain_begin(),
9378           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9379        assert(isa<FieldDecl>(*FI));
9380        Comps.push_back(OffsetOfNode(OC.LocStart,
9381                                     cast<FieldDecl>(*FI), OC.LocEnd));
9382      }
9383    } else
9384      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9385
9386    CurrentType = MemberDecl->getType().getNonReferenceType();
9387  }
9388
9389  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9390                                    TInfo, Comps, Exprs, RParenLoc));
9391}
9392
9393ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9394                                      SourceLocation BuiltinLoc,
9395                                      SourceLocation TypeLoc,
9396                                      ParsedType ParsedArgTy,
9397                                      OffsetOfComponent *CompPtr,
9398                                      unsigned NumComponents,
9399                                      SourceLocation RParenLoc) {
9400
9401  TypeSourceInfo *ArgTInfo;
9402  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9403  if (ArgTy.isNull())
9404    return ExprError();
9405
9406  if (!ArgTInfo)
9407    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9408
9409  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9410                              RParenLoc);
9411}
9412
9413
9414ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9415                                 Expr *CondExpr,
9416                                 Expr *LHSExpr, Expr *RHSExpr,
9417                                 SourceLocation RPLoc) {
9418  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9419
9420  ExprValueKind VK = VK_RValue;
9421  ExprObjectKind OK = OK_Ordinary;
9422  QualType resType;
9423  bool ValueDependent = false;
9424  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9425    resType = Context.DependentTy;
9426    ValueDependent = true;
9427  } else {
9428    // The conditional expression is required to be a constant expression.
9429    llvm::APSInt condEval(32);
9430    ExprResult CondICE
9431      = VerifyIntegerConstantExpression(CondExpr, &condEval,
9432          diag::err_typecheck_choose_expr_requires_constant, false);
9433    if (CondICE.isInvalid())
9434      return ExprError();
9435    CondExpr = CondICE.take();
9436
9437    // If the condition is > zero, then the AST type is the same as the LSHExpr.
9438    Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9439
9440    resType = ActiveExpr->getType();
9441    ValueDependent = ActiveExpr->isValueDependent();
9442    VK = ActiveExpr->getValueKind();
9443    OK = ActiveExpr->getObjectKind();
9444  }
9445
9446  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9447                                        resType, VK, OK, RPLoc,
9448                                        resType->isDependentType(),
9449                                        ValueDependent));
9450}
9451
9452//===----------------------------------------------------------------------===//
9453// Clang Extensions.
9454//===----------------------------------------------------------------------===//
9455
9456/// ActOnBlockStart - This callback is invoked when a block literal is started.
9457void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9458  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9459  PushBlockScope(CurScope, Block);
9460  CurContext->addDecl(Block);
9461  if (CurScope)
9462    PushDeclContext(CurScope, Block);
9463  else
9464    CurContext = Block;
9465
9466  getCurBlock()->HasImplicitReturnType = true;
9467
9468  // Enter a new evaluation context to insulate the block from any
9469  // cleanups from the enclosing full-expression.
9470  PushExpressionEvaluationContext(PotentiallyEvaluated);
9471}
9472
9473void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9474                               Scope *CurScope) {
9475  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9476  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9477  BlockScopeInfo *CurBlock = getCurBlock();
9478
9479  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9480  QualType T = Sig->getType();
9481
9482  // FIXME: We should allow unexpanded parameter packs here, but that would,
9483  // in turn, make the block expression contain unexpanded parameter packs.
9484  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9485    // Drop the parameters.
9486    FunctionProtoType::ExtProtoInfo EPI;
9487    EPI.HasTrailingReturn = false;
9488    EPI.TypeQuals |= DeclSpec::TQ_const;
9489    T = Context.getFunctionType(Context.DependentTy, ArrayRef<QualType>(), EPI);
9490    Sig = Context.getTrivialTypeSourceInfo(T);
9491  }
9492
9493  // GetTypeForDeclarator always produces a function type for a block
9494  // literal signature.  Furthermore, it is always a FunctionProtoType
9495  // unless the function was written with a typedef.
9496  assert(T->isFunctionType() &&
9497         "GetTypeForDeclarator made a non-function block signature");
9498
9499  // Look for an explicit signature in that function type.
9500  FunctionProtoTypeLoc ExplicitSignature;
9501
9502  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9503  if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
9504
9505    // Check whether that explicit signature was synthesized by
9506    // GetTypeForDeclarator.  If so, don't save that as part of the
9507    // written signature.
9508    if (ExplicitSignature.getLocalRangeBegin() ==
9509        ExplicitSignature.getLocalRangeEnd()) {
9510      // This would be much cheaper if we stored TypeLocs instead of
9511      // TypeSourceInfos.
9512      TypeLoc Result = ExplicitSignature.getResultLoc();
9513      unsigned Size = Result.getFullDataSize();
9514      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9515      Sig->getTypeLoc().initializeFullCopy(Result, Size);
9516
9517      ExplicitSignature = FunctionProtoTypeLoc();
9518    }
9519  }
9520
9521  CurBlock->TheDecl->setSignatureAsWritten(Sig);
9522  CurBlock->FunctionType = T;
9523
9524  const FunctionType *Fn = T->getAs<FunctionType>();
9525  QualType RetTy = Fn->getResultType();
9526  bool isVariadic =
9527    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9528
9529  CurBlock->TheDecl->setIsVariadic(isVariadic);
9530
9531  // Don't allow returning a objc interface by value.
9532  if (RetTy->isObjCObjectType()) {
9533    Diag(ParamInfo.getLocStart(),
9534         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9535    return;
9536  }
9537
9538  // Context.DependentTy is used as a placeholder for a missing block
9539  // return type.  TODO:  what should we do with declarators like:
9540  //   ^ * { ... }
9541  // If the answer is "apply template argument deduction"....
9542  if (RetTy != Context.DependentTy) {
9543    CurBlock->ReturnType = RetTy;
9544    CurBlock->TheDecl->setBlockMissingReturnType(false);
9545    CurBlock->HasImplicitReturnType = false;
9546  }
9547
9548  // Push block parameters from the declarator if we had them.
9549  SmallVector<ParmVarDecl*, 8> Params;
9550  if (ExplicitSignature) {
9551    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9552      ParmVarDecl *Param = ExplicitSignature.getArg(I);
9553      if (Param->getIdentifier() == 0 &&
9554          !Param->isImplicit() &&
9555          !Param->isInvalidDecl() &&
9556          !getLangOpts().CPlusPlus)
9557        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9558      Params.push_back(Param);
9559    }
9560
9561  // Fake up parameter variables if we have a typedef, like
9562  //   ^ fntype { ... }
9563  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9564    for (FunctionProtoType::arg_type_iterator
9565           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9566      ParmVarDecl *Param =
9567        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9568                                   ParamInfo.getLocStart(),
9569                                   *I);
9570      Params.push_back(Param);
9571    }
9572  }
9573
9574  // Set the parameters on the block decl.
9575  if (!Params.empty()) {
9576    CurBlock->TheDecl->setParams(Params);
9577    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9578                             CurBlock->TheDecl->param_end(),
9579                             /*CheckParameterNames=*/false);
9580  }
9581
9582  // Finally we can process decl attributes.
9583  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9584
9585  // Put the parameter variables in scope.  We can bail out immediately
9586  // if we don't have any.
9587  if (Params.empty())
9588    return;
9589
9590  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9591         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9592    (*AI)->setOwningFunction(CurBlock->TheDecl);
9593
9594    // If this has an identifier, add it to the scope stack.
9595    if ((*AI)->getIdentifier()) {
9596      CheckShadow(CurBlock->TheScope, *AI);
9597
9598      PushOnScopeChains(*AI, CurBlock->TheScope);
9599    }
9600  }
9601}
9602
9603/// ActOnBlockError - If there is an error parsing a block, this callback
9604/// is invoked to pop the information about the block from the action impl.
9605void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9606  // Leave the expression-evaluation context.
9607  DiscardCleanupsInEvaluationContext();
9608  PopExpressionEvaluationContext();
9609
9610  // Pop off CurBlock, handle nested blocks.
9611  PopDeclContext();
9612  PopFunctionScopeInfo();
9613}
9614
9615/// ActOnBlockStmtExpr - This is called when the body of a block statement
9616/// literal was successfully completed.  ^(int x){...}
9617ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9618                                    Stmt *Body, Scope *CurScope) {
9619  // If blocks are disabled, emit an error.
9620  if (!LangOpts.Blocks)
9621    Diag(CaretLoc, diag::err_blocks_disable);
9622
9623  // Leave the expression-evaluation context.
9624  if (hasAnyUnrecoverableErrorsInThisFunction())
9625    DiscardCleanupsInEvaluationContext();
9626  assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9627  PopExpressionEvaluationContext();
9628
9629  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9630
9631  if (BSI->HasImplicitReturnType)
9632    deduceClosureReturnType(*BSI);
9633
9634  PopDeclContext();
9635
9636  QualType RetTy = Context.VoidTy;
9637  if (!BSI->ReturnType.isNull())
9638    RetTy = BSI->ReturnType;
9639
9640  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9641  QualType BlockTy;
9642
9643  // Set the captured variables on the block.
9644  // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9645  SmallVector<BlockDecl::Capture, 4> Captures;
9646  for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9647    CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9648    if (Cap.isThisCapture())
9649      continue;
9650    BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9651                              Cap.isNested(), Cap.getCopyExpr());
9652    Captures.push_back(NewCap);
9653  }
9654  BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9655                            BSI->CXXThisCaptureIndex != 0);
9656
9657  // If the user wrote a function type in some form, try to use that.
9658  if (!BSI->FunctionType.isNull()) {
9659    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9660
9661    FunctionType::ExtInfo Ext = FTy->getExtInfo();
9662    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9663
9664    // Turn protoless block types into nullary block types.
9665    if (isa<FunctionNoProtoType>(FTy)) {
9666      FunctionProtoType::ExtProtoInfo EPI;
9667      EPI.ExtInfo = Ext;
9668      BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9669
9670    // Otherwise, if we don't need to change anything about the function type,
9671    // preserve its sugar structure.
9672    } else if (FTy->getResultType() == RetTy &&
9673               (!NoReturn || FTy->getNoReturnAttr())) {
9674      BlockTy = BSI->FunctionType;
9675
9676    // Otherwise, make the minimal modifications to the function type.
9677    } else {
9678      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9679      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9680      EPI.TypeQuals = 0; // FIXME: silently?
9681      EPI.ExtInfo = Ext;
9682      BlockTy =
9683        Context.getFunctionType(RetTy,
9684                                ArrayRef<QualType>(FPT->arg_type_begin(),
9685                                                   FPT->getNumArgs()),
9686                                EPI);
9687    }
9688
9689  // If we don't have a function type, just build one from nothing.
9690  } else {
9691    FunctionProtoType::ExtProtoInfo EPI;
9692    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9693    BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9694  }
9695
9696  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9697                           BSI->TheDecl->param_end());
9698  BlockTy = Context.getBlockPointerType(BlockTy);
9699
9700  // If needed, diagnose invalid gotos and switches in the block.
9701  if (getCurFunction()->NeedsScopeChecking() &&
9702      !hasAnyUnrecoverableErrorsInThisFunction() &&
9703      !PP.isCodeCompletionEnabled())
9704    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9705
9706  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9707
9708  // Try to apply the named return value optimization. We have to check again
9709  // if we can do this, though, because blocks keep return statements around
9710  // to deduce an implicit return type.
9711  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9712      !BSI->TheDecl->isDependentContext())
9713    computeNRVO(Body, getCurBlock());
9714
9715  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9716  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9717  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9718
9719  // If the block isn't obviously global, i.e. it captures anything at
9720  // all, then we need to do a few things in the surrounding context:
9721  if (Result->getBlockDecl()->hasCaptures()) {
9722    // First, this expression has a new cleanup object.
9723    ExprCleanupObjects.push_back(Result->getBlockDecl());
9724    ExprNeedsCleanups = true;
9725
9726    // It also gets a branch-protected scope if any of the captured
9727    // variables needs destruction.
9728    for (BlockDecl::capture_const_iterator
9729           ci = Result->getBlockDecl()->capture_begin(),
9730           ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9731      const VarDecl *var = ci->getVariable();
9732      if (var->getType().isDestructedType() != QualType::DK_none) {
9733        getCurFunction()->setHasBranchProtectedScope();
9734        break;
9735      }
9736    }
9737  }
9738
9739  return Owned(Result);
9740}
9741
9742ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9743                                        Expr *E, ParsedType Ty,
9744                                        SourceLocation RPLoc) {
9745  TypeSourceInfo *TInfo;
9746  GetTypeFromParser(Ty, &TInfo);
9747  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9748}
9749
9750ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9751                                Expr *E, TypeSourceInfo *TInfo,
9752                                SourceLocation RPLoc) {
9753  Expr *OrigExpr = E;
9754
9755  // Get the va_list type
9756  QualType VaListType = Context.getBuiltinVaListType();
9757  if (VaListType->isArrayType()) {
9758    // Deal with implicit array decay; for example, on x86-64,
9759    // va_list is an array, but it's supposed to decay to
9760    // a pointer for va_arg.
9761    VaListType = Context.getArrayDecayedType(VaListType);
9762    // Make sure the input expression also decays appropriately.
9763    ExprResult Result = UsualUnaryConversions(E);
9764    if (Result.isInvalid())
9765      return ExprError();
9766    E = Result.take();
9767  } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9768    // If va_list is a record type and we are compiling in C++ mode,
9769    // check the argument using reference binding.
9770    InitializedEntity Entity
9771      = InitializedEntity::InitializeParameter(Context,
9772          Context.getLValueReferenceType(VaListType), false);
9773    ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9774    if (Init.isInvalid())
9775      return ExprError();
9776    E = Init.takeAs<Expr>();
9777  } else {
9778    // Otherwise, the va_list argument must be an l-value because
9779    // it is modified by va_arg.
9780    if (!E->isTypeDependent() &&
9781        CheckForModifiableLvalue(E, BuiltinLoc, *this))
9782      return ExprError();
9783  }
9784
9785  if (!E->isTypeDependent() &&
9786      !Context.hasSameType(VaListType, E->getType())) {
9787    return ExprError(Diag(E->getLocStart(),
9788                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
9789      << OrigExpr->getType() << E->getSourceRange());
9790  }
9791
9792  if (!TInfo->getType()->isDependentType()) {
9793    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9794                            diag::err_second_parameter_to_va_arg_incomplete,
9795                            TInfo->getTypeLoc()))
9796      return ExprError();
9797
9798    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9799                               TInfo->getType(),
9800                               diag::err_second_parameter_to_va_arg_abstract,
9801                               TInfo->getTypeLoc()))
9802      return ExprError();
9803
9804    if (!TInfo->getType().isPODType(Context)) {
9805      Diag(TInfo->getTypeLoc().getBeginLoc(),
9806           TInfo->getType()->isObjCLifetimeType()
9807             ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9808             : diag::warn_second_parameter_to_va_arg_not_pod)
9809        << TInfo->getType()
9810        << TInfo->getTypeLoc().getSourceRange();
9811    }
9812
9813    // Check for va_arg where arguments of the given type will be promoted
9814    // (i.e. this va_arg is guaranteed to have undefined behavior).
9815    QualType PromoteType;
9816    if (TInfo->getType()->isPromotableIntegerType()) {
9817      PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9818      if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9819        PromoteType = QualType();
9820    }
9821    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9822      PromoteType = Context.DoubleTy;
9823    if (!PromoteType.isNull())
9824      DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9825                  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9826                          << TInfo->getType()
9827                          << PromoteType
9828                          << TInfo->getTypeLoc().getSourceRange());
9829  }
9830
9831  QualType T = TInfo->getType().getNonLValueExprType(Context);
9832  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9833}
9834
9835ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9836  // The type of __null will be int or long, depending on the size of
9837  // pointers on the target.
9838  QualType Ty;
9839  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9840  if (pw == Context.getTargetInfo().getIntWidth())
9841    Ty = Context.IntTy;
9842  else if (pw == Context.getTargetInfo().getLongWidth())
9843    Ty = Context.LongTy;
9844  else if (pw == Context.getTargetInfo().getLongLongWidth())
9845    Ty = Context.LongLongTy;
9846  else {
9847    llvm_unreachable("I don't know size of pointer!");
9848  }
9849
9850  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9851}
9852
9853static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9854                                           Expr *SrcExpr, FixItHint &Hint) {
9855  if (!SemaRef.getLangOpts().ObjC1)
9856    return;
9857
9858  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9859  if (!PT)
9860    return;
9861
9862  // Check if the destination is of type 'id'.
9863  if (!PT->isObjCIdType()) {
9864    // Check if the destination is the 'NSString' interface.
9865    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9866    if (!ID || !ID->getIdentifier()->isStr("NSString"))
9867      return;
9868  }
9869
9870  // Ignore any parens, implicit casts (should only be
9871  // array-to-pointer decays), and not-so-opaque values.  The last is
9872  // important for making this trigger for property assignments.
9873  SrcExpr = SrcExpr->IgnoreParenImpCasts();
9874  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9875    if (OV->getSourceExpr())
9876      SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9877
9878  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9879  if (!SL || !SL->isAscii())
9880    return;
9881
9882  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9883}
9884
9885bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9886                                    SourceLocation Loc,
9887                                    QualType DstType, QualType SrcType,
9888                                    Expr *SrcExpr, AssignmentAction Action,
9889                                    bool *Complained) {
9890  if (Complained)
9891    *Complained = false;
9892
9893  // Decode the result (notice that AST's are still created for extensions).
9894  bool CheckInferredResultType = false;
9895  bool isInvalid = false;
9896  unsigned DiagKind = 0;
9897  FixItHint Hint;
9898  ConversionFixItGenerator ConvHints;
9899  bool MayHaveConvFixit = false;
9900  bool MayHaveFunctionDiff = false;
9901
9902  switch (ConvTy) {
9903  case Compatible:
9904      DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9905      return false;
9906
9907  case PointerToInt:
9908    DiagKind = diag::ext_typecheck_convert_pointer_int;
9909    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9910    MayHaveConvFixit = true;
9911    break;
9912  case IntToPointer:
9913    DiagKind = diag::ext_typecheck_convert_int_pointer;
9914    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9915    MayHaveConvFixit = true;
9916    break;
9917  case IncompatiblePointer:
9918    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9919    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9920    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9921      SrcType->isObjCObjectPointerType();
9922    if (Hint.isNull() && !CheckInferredResultType) {
9923      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9924    }
9925    MayHaveConvFixit = true;
9926    break;
9927  case IncompatiblePointerSign:
9928    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9929    break;
9930  case FunctionVoidPointer:
9931    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9932    break;
9933  case IncompatiblePointerDiscardsQualifiers: {
9934    // Perform array-to-pointer decay if necessary.
9935    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9936
9937    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9938    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9939    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9940      DiagKind = diag::err_typecheck_incompatible_address_space;
9941      break;
9942
9943
9944    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9945      DiagKind = diag::err_typecheck_incompatible_ownership;
9946      break;
9947    }
9948
9949    llvm_unreachable("unknown error case for discarding qualifiers!");
9950    // fallthrough
9951  }
9952  case CompatiblePointerDiscardsQualifiers:
9953    // If the qualifiers lost were because we were applying the
9954    // (deprecated) C++ conversion from a string literal to a char*
9955    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9956    // Ideally, this check would be performed in
9957    // checkPointerTypesForAssignment. However, that would require a
9958    // bit of refactoring (so that the second argument is an
9959    // expression, rather than a type), which should be done as part
9960    // of a larger effort to fix checkPointerTypesForAssignment for
9961    // C++ semantics.
9962    if (getLangOpts().CPlusPlus &&
9963        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9964      return false;
9965    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9966    break;
9967  case IncompatibleNestedPointerQualifiers:
9968    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9969    break;
9970  case IntToBlockPointer:
9971    DiagKind = diag::err_int_to_block_pointer;
9972    break;
9973  case IncompatibleBlockPointer:
9974    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9975    break;
9976  case IncompatibleObjCQualifiedId:
9977    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9978    // it can give a more specific diagnostic.
9979    DiagKind = diag::warn_incompatible_qualified_id;
9980    break;
9981  case IncompatibleVectors:
9982    DiagKind = diag::warn_incompatible_vectors;
9983    break;
9984  case IncompatibleObjCWeakRef:
9985    DiagKind = diag::err_arc_weak_unavailable_assign;
9986    break;
9987  case Incompatible:
9988    DiagKind = diag::err_typecheck_convert_incompatible;
9989    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9990    MayHaveConvFixit = true;
9991    isInvalid = true;
9992    MayHaveFunctionDiff = true;
9993    break;
9994  }
9995
9996  QualType FirstType, SecondType;
9997  switch (Action) {
9998  case AA_Assigning:
9999  case AA_Initializing:
10000    // The destination type comes first.
10001    FirstType = DstType;
10002    SecondType = SrcType;
10003    break;
10004
10005  case AA_Returning:
10006  case AA_Passing:
10007  case AA_Converting:
10008  case AA_Sending:
10009  case AA_Casting:
10010    // The source type comes first.
10011    FirstType = SrcType;
10012    SecondType = DstType;
10013    break;
10014  }
10015
10016  PartialDiagnostic FDiag = PDiag(DiagKind);
10017  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10018
10019  // If we can fix the conversion, suggest the FixIts.
10020  assert(ConvHints.isNull() || Hint.isNull());
10021  if (!ConvHints.isNull()) {
10022    for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10023         HE = ConvHints.Hints.end(); HI != HE; ++HI)
10024      FDiag << *HI;
10025  } else {
10026    FDiag << Hint;
10027  }
10028  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10029
10030  if (MayHaveFunctionDiff)
10031    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10032
10033  Diag(Loc, FDiag);
10034
10035  if (SecondType == Context.OverloadTy)
10036    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10037                              FirstType);
10038
10039  if (CheckInferredResultType)
10040    EmitRelatedResultTypeNote(SrcExpr);
10041
10042  if (Complained)
10043    *Complained = true;
10044  return isInvalid;
10045}
10046
10047ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10048                                                 llvm::APSInt *Result) {
10049  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10050  public:
10051    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10052      S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10053    }
10054  } Diagnoser;
10055
10056  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10057}
10058
10059ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10060                                                 llvm::APSInt *Result,
10061                                                 unsigned DiagID,
10062                                                 bool AllowFold) {
10063  class IDDiagnoser : public VerifyICEDiagnoser {
10064    unsigned DiagID;
10065
10066  public:
10067    IDDiagnoser(unsigned DiagID)
10068      : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10069
10070    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10071      S.Diag(Loc, DiagID) << SR;
10072    }
10073  } Diagnoser(DiagID);
10074
10075  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10076}
10077
10078void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10079                                            SourceRange SR) {
10080  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10081}
10082
10083ExprResult
10084Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10085                                      VerifyICEDiagnoser &Diagnoser,
10086                                      bool AllowFold) {
10087  SourceLocation DiagLoc = E->getLocStart();
10088
10089  if (getLangOpts().CPlusPlus11) {
10090    // C++11 [expr.const]p5:
10091    //   If an expression of literal class type is used in a context where an
10092    //   integral constant expression is required, then that class type shall
10093    //   have a single non-explicit conversion function to an integral or
10094    //   unscoped enumeration type
10095    ExprResult Converted;
10096    if (!Diagnoser.Suppress) {
10097      class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10098      public:
10099        CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10100
10101        virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10102                                                 QualType T) {
10103          return S.Diag(Loc, diag::err_ice_not_integral) << T;
10104        }
10105
10106        virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10107                                                     SourceLocation Loc,
10108                                                     QualType T) {
10109          return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10110        }
10111
10112        virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10113                                                       SourceLocation Loc,
10114                                                       QualType T,
10115                                                       QualType ConvTy) {
10116          return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10117        }
10118
10119        virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10120                                                   CXXConversionDecl *Conv,
10121                                                   QualType ConvTy) {
10122          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10123                   << ConvTy->isEnumeralType() << ConvTy;
10124        }
10125
10126        virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10127                                                    QualType T) {
10128          return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10129        }
10130
10131        virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10132                                                CXXConversionDecl *Conv,
10133                                                QualType ConvTy) {
10134          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10135                   << ConvTy->isEnumeralType() << ConvTy;
10136        }
10137
10138        virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10139                                                     SourceLocation Loc,
10140                                                     QualType T,
10141                                                     QualType ConvTy) {
10142          return DiagnosticBuilder::getEmpty();
10143        }
10144      } ConvertDiagnoser;
10145
10146      Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10147                                                     ConvertDiagnoser,
10148                                             /*AllowScopedEnumerations*/ false);
10149    } else {
10150      // The caller wants to silently enquire whether this is an ICE. Don't
10151      // produce any diagnostics if it isn't.
10152      class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10153      public:
10154        SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10155
10156        virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10157                                                 QualType T) {
10158          return DiagnosticBuilder::getEmpty();
10159        }
10160
10161        virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10162                                                     SourceLocation Loc,
10163                                                     QualType T) {
10164          return DiagnosticBuilder::getEmpty();
10165        }
10166
10167        virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10168                                                       SourceLocation Loc,
10169                                                       QualType T,
10170                                                       QualType ConvTy) {
10171          return DiagnosticBuilder::getEmpty();
10172        }
10173
10174        virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10175                                                   CXXConversionDecl *Conv,
10176                                                   QualType ConvTy) {
10177          return DiagnosticBuilder::getEmpty();
10178        }
10179
10180        virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10181                                                    QualType T) {
10182          return DiagnosticBuilder::getEmpty();
10183        }
10184
10185        virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10186                                                CXXConversionDecl *Conv,
10187                                                QualType ConvTy) {
10188          return DiagnosticBuilder::getEmpty();
10189        }
10190
10191        virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10192                                                     SourceLocation Loc,
10193                                                     QualType T,
10194                                                     QualType ConvTy) {
10195          return DiagnosticBuilder::getEmpty();
10196        }
10197      } ConvertDiagnoser;
10198
10199      Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10200                                                     ConvertDiagnoser, false);
10201    }
10202    if (Converted.isInvalid())
10203      return Converted;
10204    E = Converted.take();
10205    if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10206      return ExprError();
10207  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10208    // An ICE must be of integral or unscoped enumeration type.
10209    if (!Diagnoser.Suppress)
10210      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10211    return ExprError();
10212  }
10213
10214  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10215  // in the non-ICE case.
10216  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10217    if (Result)
10218      *Result = E->EvaluateKnownConstInt(Context);
10219    return Owned(E);
10220  }
10221
10222  Expr::EvalResult EvalResult;
10223  SmallVector<PartialDiagnosticAt, 8> Notes;
10224  EvalResult.Diag = &Notes;
10225
10226  // Try to evaluate the expression, and produce diagnostics explaining why it's
10227  // not a constant expression as a side-effect.
10228  bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10229                EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10230
10231  // In C++11, we can rely on diagnostics being produced for any expression
10232  // which is not a constant expression. If no diagnostics were produced, then
10233  // this is a constant expression.
10234  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10235    if (Result)
10236      *Result = EvalResult.Val.getInt();
10237    return Owned(E);
10238  }
10239
10240  // If our only note is the usual "invalid subexpression" note, just point
10241  // the caret at its location rather than producing an essentially
10242  // redundant note.
10243  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10244        diag::note_invalid_subexpr_in_const_expr) {
10245    DiagLoc = Notes[0].first;
10246    Notes.clear();
10247  }
10248
10249  if (!Folded || !AllowFold) {
10250    if (!Diagnoser.Suppress) {
10251      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10252      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10253        Diag(Notes[I].first, Notes[I].second);
10254    }
10255
10256    return ExprError();
10257  }
10258
10259  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10260  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10261    Diag(Notes[I].first, Notes[I].second);
10262
10263  if (Result)
10264    *Result = EvalResult.Val.getInt();
10265  return Owned(E);
10266}
10267
10268namespace {
10269  // Handle the case where we conclude a expression which we speculatively
10270  // considered to be unevaluated is actually evaluated.
10271  class TransformToPE : public TreeTransform<TransformToPE> {
10272    typedef TreeTransform<TransformToPE> BaseTransform;
10273
10274  public:
10275    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10276
10277    // Make sure we redo semantic analysis
10278    bool AlwaysRebuild() { return true; }
10279
10280    // Make sure we handle LabelStmts correctly.
10281    // FIXME: This does the right thing, but maybe we need a more general
10282    // fix to TreeTransform?
10283    StmtResult TransformLabelStmt(LabelStmt *S) {
10284      S->getDecl()->setStmt(0);
10285      return BaseTransform::TransformLabelStmt(S);
10286    }
10287
10288    // We need to special-case DeclRefExprs referring to FieldDecls which
10289    // are not part of a member pointer formation; normal TreeTransforming
10290    // doesn't catch this case because of the way we represent them in the AST.
10291    // FIXME: This is a bit ugly; is it really the best way to handle this
10292    // case?
10293    //
10294    // Error on DeclRefExprs referring to FieldDecls.
10295    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10296      if (isa<FieldDecl>(E->getDecl()) &&
10297          !SemaRef.isUnevaluatedContext())
10298        return SemaRef.Diag(E->getLocation(),
10299                            diag::err_invalid_non_static_member_use)
10300            << E->getDecl() << E->getSourceRange();
10301
10302      return BaseTransform::TransformDeclRefExpr(E);
10303    }
10304
10305    // Exception: filter out member pointer formation
10306    ExprResult TransformUnaryOperator(UnaryOperator *E) {
10307      if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10308        return E;
10309
10310      return BaseTransform::TransformUnaryOperator(E);
10311    }
10312
10313    ExprResult TransformLambdaExpr(LambdaExpr *E) {
10314      // Lambdas never need to be transformed.
10315      return E;
10316    }
10317  };
10318}
10319
10320ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10321  assert(ExprEvalContexts.back().Context == Unevaluated &&
10322         "Should only transform unevaluated expressions");
10323  ExprEvalContexts.back().Context =
10324      ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10325  if (ExprEvalContexts.back().Context == Unevaluated)
10326    return E;
10327  return TransformToPE(*this).TransformExpr(E);
10328}
10329
10330void
10331Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10332                                      Decl *LambdaContextDecl,
10333                                      bool IsDecltype) {
10334  ExprEvalContexts.push_back(
10335             ExpressionEvaluationContextRecord(NewContext,
10336                                               ExprCleanupObjects.size(),
10337                                               ExprNeedsCleanups,
10338                                               LambdaContextDecl,
10339                                               IsDecltype));
10340  ExprNeedsCleanups = false;
10341  if (!MaybeODRUseExprs.empty())
10342    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10343}
10344
10345void
10346Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10347                                      ReuseLambdaContextDecl_t,
10348                                      bool IsDecltype) {
10349  Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10350  PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10351}
10352
10353void Sema::PopExpressionEvaluationContext() {
10354  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10355
10356  if (!Rec.Lambdas.empty()) {
10357    if (Rec.Context == Unevaluated) {
10358      // C++11 [expr.prim.lambda]p2:
10359      //   A lambda-expression shall not appear in an unevaluated operand
10360      //   (Clause 5).
10361      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10362        Diag(Rec.Lambdas[I]->getLocStart(),
10363             diag::err_lambda_unevaluated_operand);
10364    } else {
10365      // Mark the capture expressions odr-used. This was deferred
10366      // during lambda expression creation.
10367      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10368        LambdaExpr *Lambda = Rec.Lambdas[I];
10369        for (LambdaExpr::capture_init_iterator
10370                  C = Lambda->capture_init_begin(),
10371               CEnd = Lambda->capture_init_end();
10372             C != CEnd; ++C) {
10373          MarkDeclarationsReferencedInExpr(*C);
10374        }
10375      }
10376    }
10377  }
10378
10379  // When are coming out of an unevaluated context, clear out any
10380  // temporaries that we may have created as part of the evaluation of
10381  // the expression in that context: they aren't relevant because they
10382  // will never be constructed.
10383  if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10384    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10385                             ExprCleanupObjects.end());
10386    ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10387    CleanupVarDeclMarking();
10388    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10389  // Otherwise, merge the contexts together.
10390  } else {
10391    ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10392    MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10393                            Rec.SavedMaybeODRUseExprs.end());
10394  }
10395
10396  // Pop the current expression evaluation context off the stack.
10397  ExprEvalContexts.pop_back();
10398}
10399
10400void Sema::DiscardCleanupsInEvaluationContext() {
10401  ExprCleanupObjects.erase(
10402         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10403         ExprCleanupObjects.end());
10404  ExprNeedsCleanups = false;
10405  MaybeODRUseExprs.clear();
10406}
10407
10408ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10409  if (!E->getType()->isVariablyModifiedType())
10410    return E;
10411  return TransformToPotentiallyEvaluated(E);
10412}
10413
10414static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10415  // Do not mark anything as "used" within a dependent context; wait for
10416  // an instantiation.
10417  if (SemaRef.CurContext->isDependentContext())
10418    return false;
10419
10420  switch (SemaRef.ExprEvalContexts.back().Context) {
10421    case Sema::Unevaluated:
10422      // We are in an expression that is not potentially evaluated; do nothing.
10423      // (Depending on how you read the standard, we actually do need to do
10424      // something here for null pointer constants, but the standard's
10425      // definition of a null pointer constant is completely crazy.)
10426      return false;
10427
10428    case Sema::ConstantEvaluated:
10429    case Sema::PotentiallyEvaluated:
10430      // We are in a potentially evaluated expression (or a constant-expression
10431      // in C++03); we need to do implicit template instantiation, implicitly
10432      // define class members, and mark most declarations as used.
10433      return true;
10434
10435    case Sema::PotentiallyEvaluatedIfUsed:
10436      // Referenced declarations will only be used if the construct in the
10437      // containing expression is used.
10438      return false;
10439  }
10440  llvm_unreachable("Invalid context");
10441}
10442
10443/// \brief Mark a function referenced, and check whether it is odr-used
10444/// (C++ [basic.def.odr]p2, C99 6.9p3)
10445void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10446  assert(Func && "No function?");
10447
10448  Func->setReferenced();
10449
10450  // C++11 [basic.def.odr]p3:
10451  //   A function whose name appears as a potentially-evaluated expression is
10452  //   odr-used if it is the unique lookup result or the selected member of a
10453  //   set of overloaded functions [...].
10454  //
10455  // We (incorrectly) mark overload resolution as an unevaluated context, so we
10456  // can just check that here. Skip the rest of this function if we've already
10457  // marked the function as used.
10458  if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10459    // C++11 [temp.inst]p3:
10460    //   Unless a function template specialization has been explicitly
10461    //   instantiated or explicitly specialized, the function template
10462    //   specialization is implicitly instantiated when the specialization is
10463    //   referenced in a context that requires a function definition to exist.
10464    //
10465    // We consider constexpr function templates to be referenced in a context
10466    // that requires a definition to exist whenever they are referenced.
10467    //
10468    // FIXME: This instantiates constexpr functions too frequently. If this is
10469    // really an unevaluated context (and we're not just in the definition of a
10470    // function template or overload resolution or other cases which we
10471    // incorrectly consider to be unevaluated contexts), and we're not in a
10472    // subexpression which we actually need to evaluate (for instance, a
10473    // template argument, array bound or an expression in a braced-init-list),
10474    // we are not permitted to instantiate this constexpr function definition.
10475    //
10476    // FIXME: This also implicitly defines special members too frequently. They
10477    // are only supposed to be implicitly defined if they are odr-used, but they
10478    // are not odr-used from constant expressions in unevaluated contexts.
10479    // However, they cannot be referenced if they are deleted, and they are
10480    // deleted whenever the implicit definition of the special member would
10481    // fail.
10482    if (!Func->isConstexpr() || Func->getBody())
10483      return;
10484    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10485    if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10486      return;
10487  }
10488
10489  // Note that this declaration has been used.
10490  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10491    if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10492      if (Constructor->isDefaultConstructor()) {
10493        if (Constructor->isTrivial())
10494          return;
10495        if (!Constructor->isUsed(false))
10496          DefineImplicitDefaultConstructor(Loc, Constructor);
10497      } else if (Constructor->isCopyConstructor()) {
10498        if (!Constructor->isUsed(false))
10499          DefineImplicitCopyConstructor(Loc, Constructor);
10500      } else if (Constructor->isMoveConstructor()) {
10501        if (!Constructor->isUsed(false))
10502          DefineImplicitMoveConstructor(Loc, Constructor);
10503      }
10504    } else if (Constructor->getInheritedConstructor()) {
10505      if (!Constructor->isUsed(false))
10506        DefineInheritingConstructor(Loc, Constructor);
10507    }
10508
10509    MarkVTableUsed(Loc, Constructor->getParent());
10510  } else if (CXXDestructorDecl *Destructor =
10511                 dyn_cast<CXXDestructorDecl>(Func)) {
10512    if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10513        !Destructor->isUsed(false))
10514      DefineImplicitDestructor(Loc, Destructor);
10515    if (Destructor->isVirtual())
10516      MarkVTableUsed(Loc, Destructor->getParent());
10517  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10518    if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10519        MethodDecl->isOverloadedOperator() &&
10520        MethodDecl->getOverloadedOperator() == OO_Equal) {
10521      if (!MethodDecl->isUsed(false)) {
10522        if (MethodDecl->isCopyAssignmentOperator())
10523          DefineImplicitCopyAssignment(Loc, MethodDecl);
10524        else
10525          DefineImplicitMoveAssignment(Loc, MethodDecl);
10526      }
10527    } else if (isa<CXXConversionDecl>(MethodDecl) &&
10528               MethodDecl->getParent()->isLambda()) {
10529      CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10530      if (Conversion->isLambdaToBlockPointerConversion())
10531        DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10532      else
10533        DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10534    } else if (MethodDecl->isVirtual())
10535      MarkVTableUsed(Loc, MethodDecl->getParent());
10536  }
10537
10538  // Recursive functions should be marked when used from another function.
10539  // FIXME: Is this really right?
10540  if (CurContext == Func) return;
10541
10542  // Resolve the exception specification for any function which is
10543  // used: CodeGen will need it.
10544  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10545  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10546    ResolveExceptionSpec(Loc, FPT);
10547
10548  // Implicit instantiation of function templates and member functions of
10549  // class templates.
10550  if (Func->isImplicitlyInstantiable()) {
10551    bool AlreadyInstantiated = false;
10552    SourceLocation PointOfInstantiation = Loc;
10553    if (FunctionTemplateSpecializationInfo *SpecInfo
10554                              = Func->getTemplateSpecializationInfo()) {
10555      if (SpecInfo->getPointOfInstantiation().isInvalid())
10556        SpecInfo->setPointOfInstantiation(Loc);
10557      else if (SpecInfo->getTemplateSpecializationKind()
10558                 == TSK_ImplicitInstantiation) {
10559        AlreadyInstantiated = true;
10560        PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10561      }
10562    } else if (MemberSpecializationInfo *MSInfo
10563                                = Func->getMemberSpecializationInfo()) {
10564      if (MSInfo->getPointOfInstantiation().isInvalid())
10565        MSInfo->setPointOfInstantiation(Loc);
10566      else if (MSInfo->getTemplateSpecializationKind()
10567                 == TSK_ImplicitInstantiation) {
10568        AlreadyInstantiated = true;
10569        PointOfInstantiation = MSInfo->getPointOfInstantiation();
10570      }
10571    }
10572
10573    if (!AlreadyInstantiated || Func->isConstexpr()) {
10574      if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10575          cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10576        PendingLocalImplicitInstantiations.push_back(
10577            std::make_pair(Func, PointOfInstantiation));
10578      else if (Func->isConstexpr())
10579        // Do not defer instantiations of constexpr functions, to avoid the
10580        // expression evaluator needing to call back into Sema if it sees a
10581        // call to such a function.
10582        InstantiateFunctionDefinition(PointOfInstantiation, Func);
10583      else {
10584        PendingInstantiations.push_back(std::make_pair(Func,
10585                                                       PointOfInstantiation));
10586        // Notify the consumer that a function was implicitly instantiated.
10587        Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10588      }
10589    }
10590  } else {
10591    // Walk redefinitions, as some of them may be instantiable.
10592    for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10593         e(Func->redecls_end()); i != e; ++i) {
10594      if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10595        MarkFunctionReferenced(Loc, *i);
10596    }
10597  }
10598
10599  // Keep track of used but undefined functions.
10600  if (!Func->isDefined()) {
10601    if (mightHaveNonExternalLinkage(Func))
10602      UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10603    else if (Func->getMostRecentDecl()->isInlined() &&
10604             (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10605             !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10606      UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10607  }
10608
10609  // Normally the must current decl is marked used while processing the use and
10610  // any subsequent decls are marked used by decl merging. This fails with
10611  // template instantiation since marking can happen at the end of the file
10612  // and, because of the two phase lookup, this function is called with at
10613  // decl in the middle of a decl chain. We loop to maintain the invariant
10614  // that once a decl is used, all decls after it are also used.
10615  for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
10616    F->setUsed(true);
10617    if (F == Func)
10618      break;
10619  }
10620}
10621
10622static void
10623diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10624                                   VarDecl *var, DeclContext *DC) {
10625  DeclContext *VarDC = var->getDeclContext();
10626
10627  //  If the parameter still belongs to the translation unit, then
10628  //  we're actually just using one parameter in the declaration of
10629  //  the next.
10630  if (isa<ParmVarDecl>(var) &&
10631      isa<TranslationUnitDecl>(VarDC))
10632    return;
10633
10634  // For C code, don't diagnose about capture if we're not actually in code
10635  // right now; it's impossible to write a non-constant expression outside of
10636  // function context, so we'll get other (more useful) diagnostics later.
10637  //
10638  // For C++, things get a bit more nasty... it would be nice to suppress this
10639  // diagnostic for certain cases like using a local variable in an array bound
10640  // for a member of a local class, but the correct predicate is not obvious.
10641  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10642    return;
10643
10644  if (isa<CXXMethodDecl>(VarDC) &&
10645      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10646    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10647      << var->getIdentifier();
10648  } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10649    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10650      << var->getIdentifier() << fn->getDeclName();
10651  } else if (isa<BlockDecl>(VarDC)) {
10652    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10653      << var->getIdentifier();
10654  } else {
10655    // FIXME: Is there any other context where a local variable can be
10656    // declared?
10657    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10658      << var->getIdentifier();
10659  }
10660
10661  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10662    << var->getIdentifier();
10663
10664  // FIXME: Add additional diagnostic info about class etc. which prevents
10665  // capture.
10666}
10667
10668/// \brief Capture the given variable in the given lambda expression.
10669static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10670                                  VarDecl *Var, QualType FieldType,
10671                                  QualType DeclRefType,
10672                                  SourceLocation Loc,
10673                                  bool RefersToEnclosingLocal) {
10674  CXXRecordDecl *Lambda = LSI->Lambda;
10675
10676  // Build the non-static data member.
10677  FieldDecl *Field
10678    = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10679                        S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10680                        0, false, ICIS_NoInit);
10681  Field->setImplicit(true);
10682  Field->setAccess(AS_private);
10683  Lambda->addDecl(Field);
10684
10685  // C++11 [expr.prim.lambda]p21:
10686  //   When the lambda-expression is evaluated, the entities that
10687  //   are captured by copy are used to direct-initialize each
10688  //   corresponding non-static data member of the resulting closure
10689  //   object. (For array members, the array elements are
10690  //   direct-initialized in increasing subscript order.) These
10691  //   initializations are performed in the (unspecified) order in
10692  //   which the non-static data members are declared.
10693
10694  // Introduce a new evaluation context for the initialization, so
10695  // that temporaries introduced as part of the capture are retained
10696  // to be re-"exported" from the lambda expression itself.
10697  S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10698
10699  // C++ [expr.prim.labda]p12:
10700  //   An entity captured by a lambda-expression is odr-used (3.2) in
10701  //   the scope containing the lambda-expression.
10702  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10703                                          DeclRefType, VK_LValue, Loc);
10704  Var->setReferenced(true);
10705  Var->setUsed(true);
10706
10707  // When the field has array type, create index variables for each
10708  // dimension of the array. We use these index variables to subscript
10709  // the source array, and other clients (e.g., CodeGen) will perform
10710  // the necessary iteration with these index variables.
10711  SmallVector<VarDecl *, 4> IndexVariables;
10712  QualType BaseType = FieldType;
10713  QualType SizeType = S.Context.getSizeType();
10714  LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10715  while (const ConstantArrayType *Array
10716                        = S.Context.getAsConstantArrayType(BaseType)) {
10717    // Create the iteration variable for this array index.
10718    IdentifierInfo *IterationVarName = 0;
10719    {
10720      SmallString<8> Str;
10721      llvm::raw_svector_ostream OS(Str);
10722      OS << "__i" << IndexVariables.size();
10723      IterationVarName = &S.Context.Idents.get(OS.str());
10724    }
10725    VarDecl *IterationVar
10726      = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10727                        IterationVarName, SizeType,
10728                        S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10729                        SC_None, SC_None);
10730    IndexVariables.push_back(IterationVar);
10731    LSI->ArrayIndexVars.push_back(IterationVar);
10732
10733    // Create a reference to the iteration variable.
10734    ExprResult IterationVarRef
10735      = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10736    assert(!IterationVarRef.isInvalid() &&
10737           "Reference to invented variable cannot fail!");
10738    IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10739    assert(!IterationVarRef.isInvalid() &&
10740           "Conversion of invented variable cannot fail!");
10741
10742    // Subscript the array with this iteration variable.
10743    ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10744                             Ref, Loc, IterationVarRef.take(), Loc);
10745    if (Subscript.isInvalid()) {
10746      S.CleanupVarDeclMarking();
10747      S.DiscardCleanupsInEvaluationContext();
10748      S.PopExpressionEvaluationContext();
10749      return ExprError();
10750    }
10751
10752    Ref = Subscript.take();
10753    BaseType = Array->getElementType();
10754  }
10755
10756  // Construct the entity that we will be initializing. For an array, this
10757  // will be first element in the array, which may require several levels
10758  // of array-subscript entities.
10759  SmallVector<InitializedEntity, 4> Entities;
10760  Entities.reserve(1 + IndexVariables.size());
10761  Entities.push_back(
10762    InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10763  for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10764    Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10765                                                            0,
10766                                                            Entities.back()));
10767
10768  InitializationKind InitKind
10769    = InitializationKind::CreateDirect(Loc, Loc, Loc);
10770  InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10771  ExprResult Result(true);
10772  if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10773    Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10774
10775  // If this initialization requires any cleanups (e.g., due to a
10776  // default argument to a copy constructor), note that for the
10777  // lambda.
10778  if (S.ExprNeedsCleanups)
10779    LSI->ExprNeedsCleanups = true;
10780
10781  // Exit the expression evaluation context used for the capture.
10782  S.CleanupVarDeclMarking();
10783  S.DiscardCleanupsInEvaluationContext();
10784  S.PopExpressionEvaluationContext();
10785  return Result;
10786}
10787
10788bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10789                              TryCaptureKind Kind, SourceLocation EllipsisLoc,
10790                              bool BuildAndDiagnose,
10791                              QualType &CaptureType,
10792                              QualType &DeclRefType) {
10793  bool Nested = false;
10794
10795  DeclContext *DC = CurContext;
10796  if (Var->getDeclContext() == DC) return true;
10797  if (!Var->hasLocalStorage()) return true;
10798
10799  bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10800
10801  // Walk up the stack to determine whether we can capture the variable,
10802  // performing the "simple" checks that don't depend on type. We stop when
10803  // we've either hit the declared scope of the variable or find an existing
10804  // capture of that variable.
10805  CaptureType = Var->getType();
10806  DeclRefType = CaptureType.getNonReferenceType();
10807  bool Explicit = (Kind != TryCapture_Implicit);
10808  unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10809  do {
10810    // Only block literals and lambda expressions can capture; other
10811    // scopes don't work.
10812    DeclContext *ParentDC;
10813    if (isa<BlockDecl>(DC))
10814      ParentDC = DC->getParent();
10815    else if (isa<CXXMethodDecl>(DC) &&
10816             cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10817             cast<CXXRecordDecl>(DC->getParent())->isLambda())
10818      ParentDC = DC->getParent()->getParent();
10819    else {
10820      if (BuildAndDiagnose)
10821        diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10822      return true;
10823    }
10824
10825    CapturingScopeInfo *CSI =
10826      cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10827
10828    // Check whether we've already captured it.
10829    if (CSI->CaptureMap.count(Var)) {
10830      // If we found a capture, any subcaptures are nested.
10831      Nested = true;
10832
10833      // Retrieve the capture type for this variable.
10834      CaptureType = CSI->getCapture(Var).getCaptureType();
10835
10836      // Compute the type of an expression that refers to this variable.
10837      DeclRefType = CaptureType.getNonReferenceType();
10838
10839      const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10840      if (Cap.isCopyCapture() &&
10841          !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10842        DeclRefType.addConst();
10843      break;
10844    }
10845
10846    bool IsBlock = isa<BlockScopeInfo>(CSI);
10847    bool IsLambda = !IsBlock;
10848
10849    // Lambdas are not allowed to capture unnamed variables
10850    // (e.g. anonymous unions).
10851    // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10852    // assuming that's the intent.
10853    if (IsLambda && !Var->getDeclName()) {
10854      if (BuildAndDiagnose) {
10855        Diag(Loc, diag::err_lambda_capture_anonymous_var);
10856        Diag(Var->getLocation(), diag::note_declared_at);
10857      }
10858      return true;
10859    }
10860
10861    // Prohibit variably-modified types; they're difficult to deal with.
10862    if (Var->getType()->isVariablyModifiedType()) {
10863      if (BuildAndDiagnose) {
10864        if (IsBlock)
10865          Diag(Loc, diag::err_ref_vm_type);
10866        else
10867          Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10868        Diag(Var->getLocation(), diag::note_previous_decl)
10869          << Var->getDeclName();
10870      }
10871      return true;
10872    }
10873    // Prohibit structs with flexible array members too.
10874    // We cannot capture what is in the tail end of the struct.
10875    if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
10876      if (VTTy->getDecl()->hasFlexibleArrayMember()) {
10877        if (BuildAndDiagnose) {
10878          if (IsBlock)
10879            Diag(Loc, diag::err_ref_flexarray_type);
10880          else
10881            Diag(Loc, diag::err_lambda_capture_flexarray_type)
10882              << Var->getDeclName();
10883          Diag(Var->getLocation(), diag::note_previous_decl)
10884            << Var->getDeclName();
10885        }
10886        return true;
10887      }
10888    }
10889    // Lambdas are not allowed to capture __block variables; they don't
10890    // support the expected semantics.
10891    if (IsLambda && HasBlocksAttr) {
10892      if (BuildAndDiagnose) {
10893        Diag(Loc, diag::err_lambda_capture_block)
10894          << Var->getDeclName();
10895        Diag(Var->getLocation(), diag::note_previous_decl)
10896          << Var->getDeclName();
10897      }
10898      return true;
10899    }
10900
10901    if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10902      // No capture-default
10903      if (BuildAndDiagnose) {
10904        Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10905        Diag(Var->getLocation(), diag::note_previous_decl)
10906          << Var->getDeclName();
10907        Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10908             diag::note_lambda_decl);
10909      }
10910      return true;
10911    }
10912
10913    FunctionScopesIndex--;
10914    DC = ParentDC;
10915    Explicit = false;
10916  } while (!Var->getDeclContext()->Equals(DC));
10917
10918  // Walk back down the scope stack, computing the type of the capture at
10919  // each step, checking type-specific requirements, and adding captures if
10920  // requested.
10921  for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10922       ++I) {
10923    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10924
10925    // Compute the type of the capture and of a reference to the capture within
10926    // this scope.
10927    if (isa<BlockScopeInfo>(CSI)) {
10928      Expr *CopyExpr = 0;
10929      bool ByRef = false;
10930
10931      // Blocks are not allowed to capture arrays.
10932      if (CaptureType->isArrayType()) {
10933        if (BuildAndDiagnose) {
10934          Diag(Loc, diag::err_ref_array_type);
10935          Diag(Var->getLocation(), diag::note_previous_decl)
10936          << Var->getDeclName();
10937        }
10938        return true;
10939      }
10940
10941      // Forbid the block-capture of autoreleasing variables.
10942      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10943        if (BuildAndDiagnose) {
10944          Diag(Loc, diag::err_arc_autoreleasing_capture)
10945            << /*block*/ 0;
10946          Diag(Var->getLocation(), diag::note_previous_decl)
10947            << Var->getDeclName();
10948        }
10949        return true;
10950      }
10951
10952      if (HasBlocksAttr || CaptureType->isReferenceType()) {
10953        // Block capture by reference does not change the capture or
10954        // declaration reference types.
10955        ByRef = true;
10956      } else {
10957        // Block capture by copy introduces 'const'.
10958        CaptureType = CaptureType.getNonReferenceType().withConst();
10959        DeclRefType = CaptureType;
10960
10961        if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10962          if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10963            // The capture logic needs the destructor, so make sure we mark it.
10964            // Usually this is unnecessary because most local variables have
10965            // their destructors marked at declaration time, but parameters are
10966            // an exception because it's technically only the call site that
10967            // actually requires the destructor.
10968            if (isa<ParmVarDecl>(Var))
10969              FinalizeVarWithDestructor(Var, Record);
10970
10971            // According to the blocks spec, the capture of a variable from
10972            // the stack requires a const copy constructor.  This is not true
10973            // of the copy/move done to move a __block variable to the heap.
10974            Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
10975                                                      DeclRefType.withConst(),
10976                                                      VK_LValue, Loc);
10977
10978            ExprResult Result
10979              = PerformCopyInitialization(
10980                  InitializedEntity::InitializeBlock(Var->getLocation(),
10981                                                     CaptureType, false),
10982                  Loc, Owned(DeclRef));
10983
10984            // Build a full-expression copy expression if initialization
10985            // succeeded and used a non-trivial constructor.  Recover from
10986            // errors by pretending that the copy isn't necessary.
10987            if (!Result.isInvalid() &&
10988                !cast<CXXConstructExpr>(Result.get())->getConstructor()
10989                   ->isTrivial()) {
10990              Result = MaybeCreateExprWithCleanups(Result);
10991              CopyExpr = Result.take();
10992            }
10993          }
10994        }
10995      }
10996
10997      // Actually capture the variable.
10998      if (BuildAndDiagnose)
10999        CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11000                        SourceLocation(), CaptureType, CopyExpr);
11001      Nested = true;
11002      continue;
11003    }
11004
11005    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11006
11007    // Determine whether we are capturing by reference or by value.
11008    bool ByRef = false;
11009    if (I == N - 1 && Kind != TryCapture_Implicit) {
11010      ByRef = (Kind == TryCapture_ExplicitByRef);
11011    } else {
11012      ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11013    }
11014
11015    // Compute the type of the field that will capture this variable.
11016    if (ByRef) {
11017      // C++11 [expr.prim.lambda]p15:
11018      //   An entity is captured by reference if it is implicitly or
11019      //   explicitly captured but not captured by copy. It is
11020      //   unspecified whether additional unnamed non-static data
11021      //   members are declared in the closure type for entities
11022      //   captured by reference.
11023      //
11024      // FIXME: It is not clear whether we want to build an lvalue reference
11025      // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11026      // to do the former, while EDG does the latter. Core issue 1249 will
11027      // clarify, but for now we follow GCC because it's a more permissive and
11028      // easily defensible position.
11029      CaptureType = Context.getLValueReferenceType(DeclRefType);
11030    } else {
11031      // C++11 [expr.prim.lambda]p14:
11032      //   For each entity captured by copy, an unnamed non-static
11033      //   data member is declared in the closure type. The
11034      //   declaration order of these members is unspecified. The type
11035      //   of such a data member is the type of the corresponding
11036      //   captured entity if the entity is not a reference to an
11037      //   object, or the referenced type otherwise. [Note: If the
11038      //   captured entity is a reference to a function, the
11039      //   corresponding data member is also a reference to a
11040      //   function. - end note ]
11041      if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11042        if (!RefType->getPointeeType()->isFunctionType())
11043          CaptureType = RefType->getPointeeType();
11044      }
11045
11046      // Forbid the lambda copy-capture of autoreleasing variables.
11047      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11048        if (BuildAndDiagnose) {
11049          Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11050          Diag(Var->getLocation(), diag::note_previous_decl)
11051            << Var->getDeclName();
11052        }
11053        return true;
11054      }
11055    }
11056
11057    // Capture this variable in the lambda.
11058    Expr *CopyExpr = 0;
11059    if (BuildAndDiagnose) {
11060      ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11061                                          DeclRefType, Loc,
11062                                          Nested);
11063      if (!Result.isInvalid())
11064        CopyExpr = Result.take();
11065    }
11066
11067    // Compute the type of a reference to this captured variable.
11068    if (ByRef)
11069      DeclRefType = CaptureType.getNonReferenceType();
11070    else {
11071      // C++ [expr.prim.lambda]p5:
11072      //   The closure type for a lambda-expression has a public inline
11073      //   function call operator [...]. This function call operator is
11074      //   declared const (9.3.1) if and only if the lambda-expressionâs
11075      //   parameter-declaration-clause is not followed by mutable.
11076      DeclRefType = CaptureType.getNonReferenceType();
11077      if (!LSI->Mutable && !CaptureType->isReferenceType())
11078        DeclRefType.addConst();
11079    }
11080
11081    // Add the capture.
11082    if (BuildAndDiagnose)
11083      CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11084                      EllipsisLoc, CaptureType, CopyExpr);
11085    Nested = true;
11086  }
11087
11088  return false;
11089}
11090
11091bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11092                              TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11093  QualType CaptureType;
11094  QualType DeclRefType;
11095  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11096                            /*BuildAndDiagnose=*/true, CaptureType,
11097                            DeclRefType);
11098}
11099
11100QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11101  QualType CaptureType;
11102  QualType DeclRefType;
11103
11104  // Determine whether we can capture this variable.
11105  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11106                         /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11107    return QualType();
11108
11109  return DeclRefType;
11110}
11111
11112static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11113                               SourceLocation Loc) {
11114  // Keep track of used but undefined variables.
11115  // FIXME: We shouldn't suppress this warning for static data members.
11116  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11117      Var->getLinkage() != ExternalLinkage &&
11118      !(Var->isStaticDataMember() && Var->hasInit())) {
11119    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11120    if (old.isInvalid()) old = Loc;
11121  }
11122
11123  SemaRef.tryCaptureVariable(Var, Loc);
11124
11125  Var->setUsed(true);
11126}
11127
11128void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11129  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11130  // an object that satisfies the requirements for appearing in a
11131  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11132  // is immediately applied."  This function handles the lvalue-to-rvalue
11133  // conversion part.
11134  MaybeODRUseExprs.erase(E->IgnoreParens());
11135}
11136
11137ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11138  if (!Res.isUsable())
11139    return Res;
11140
11141  // If a constant-expression is a reference to a variable where we delay
11142  // deciding whether it is an odr-use, just assume we will apply the
11143  // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11144  // (a non-type template argument), we have special handling anyway.
11145  UpdateMarkingForLValueToRValue(Res.get());
11146  return Res;
11147}
11148
11149void Sema::CleanupVarDeclMarking() {
11150  for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11151                                        e = MaybeODRUseExprs.end();
11152       i != e; ++i) {
11153    VarDecl *Var;
11154    SourceLocation Loc;
11155    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11156      Var = cast<VarDecl>(DRE->getDecl());
11157      Loc = DRE->getLocation();
11158    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11159      Var = cast<VarDecl>(ME->getMemberDecl());
11160      Loc = ME->getMemberLoc();
11161    } else {
11162      llvm_unreachable("Unexpcted expression");
11163    }
11164
11165    MarkVarDeclODRUsed(*this, Var, Loc);
11166  }
11167
11168  MaybeODRUseExprs.clear();
11169}
11170
11171// Mark a VarDecl referenced, and perform the necessary handling to compute
11172// odr-uses.
11173static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11174                                    VarDecl *Var, Expr *E) {
11175  Var->setReferenced();
11176
11177  if (!IsPotentiallyEvaluatedContext(SemaRef))
11178    return;
11179
11180  // Implicit instantiation of static data members of class templates.
11181  if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11182    MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11183    assert(MSInfo && "Missing member specialization information?");
11184    bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11185    if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11186        (!AlreadyInstantiated ||
11187         Var->isUsableInConstantExpressions(SemaRef.Context))) {
11188      if (!AlreadyInstantiated) {
11189        // This is a modification of an existing AST node. Notify listeners.
11190        if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11191          L->StaticDataMemberInstantiated(Var);
11192        MSInfo->setPointOfInstantiation(Loc);
11193      }
11194      SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11195      if (Var->isUsableInConstantExpressions(SemaRef.Context))
11196        // Do not defer instantiations of variables which could be used in a
11197        // constant expression.
11198        SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11199      else
11200        SemaRef.PendingInstantiations.push_back(
11201            std::make_pair(Var, PointOfInstantiation));
11202    }
11203  }
11204
11205  // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11206  // the requirements for appearing in a constant expression (5.19) and, if
11207  // it is an object, the lvalue-to-rvalue conversion (4.1)
11208  // is immediately applied."  We check the first part here, and
11209  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11210  // Note that we use the C++11 definition everywhere because nothing in
11211  // C++03 depends on whether we get the C++03 version correct. The second
11212  // part does not apply to references, since they are not objects.
11213  const VarDecl *DefVD;
11214  if (E && !isa<ParmVarDecl>(Var) &&
11215      Var->isUsableInConstantExpressions(SemaRef.Context) &&
11216      Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11217    if (!Var->getType()->isReferenceType())
11218      SemaRef.MaybeODRUseExprs.insert(E);
11219  } else
11220    MarkVarDeclODRUsed(SemaRef, Var, Loc);
11221}
11222
11223/// \brief Mark a variable referenced, and check whether it is odr-used
11224/// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11225/// used directly for normal expressions referring to VarDecl.
11226void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11227  DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11228}
11229
11230static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11231                               Decl *D, Expr *E, bool OdrUse) {
11232  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11233    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11234    return;
11235  }
11236
11237  SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11238
11239  // If this is a call to a method via a cast, also mark the method in the
11240  // derived class used in case codegen can devirtualize the call.
11241  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11242  if (!ME)
11243    return;
11244  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11245  if (!MD)
11246    return;
11247  const Expr *Base = ME->getBase();
11248  const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11249  if (!MostDerivedClassDecl)
11250    return;
11251  CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11252  if (!DM || DM->isPure())
11253    return;
11254  SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11255}
11256
11257/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11258void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11259  // TODO: update this with DR# once a defect report is filed.
11260  // C++11 defect. The address of a pure member should not be an ODR use, even
11261  // if it's a qualified reference.
11262  bool OdrUse = true;
11263  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11264    if (Method->isVirtual())
11265      OdrUse = false;
11266  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11267}
11268
11269/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11270void Sema::MarkMemberReferenced(MemberExpr *E) {
11271  // C++11 [basic.def.odr]p2:
11272  //   A non-overloaded function whose name appears as a potentially-evaluated
11273  //   expression or a member of a set of candidate functions, if selected by
11274  //   overload resolution when referred to from a potentially-evaluated
11275  //   expression, is odr-used, unless it is a pure virtual function and its
11276  //   name is not explicitly qualified.
11277  bool OdrUse = true;
11278  if (!E->hasQualifier()) {
11279    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11280      if (Method->isPure())
11281        OdrUse = false;
11282  }
11283  SourceLocation Loc = E->getMemberLoc().isValid() ?
11284                            E->getMemberLoc() : E->getLocStart();
11285  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11286}
11287
11288/// \brief Perform marking for a reference to an arbitrary declaration.  It
11289/// marks the declaration referenced, and performs odr-use checking for functions
11290/// and variables. This method should not be used when building an normal
11291/// expression which refers to a variable.
11292void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11293  if (OdrUse) {
11294    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11295      MarkVariableReferenced(Loc, VD);
11296      return;
11297    }
11298    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11299      MarkFunctionReferenced(Loc, FD);
11300      return;
11301    }
11302  }
11303  D->setReferenced();
11304}
11305
11306namespace {
11307  // Mark all of the declarations referenced
11308  // FIXME: Not fully implemented yet! We need to have a better understanding
11309  // of when we're entering
11310  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11311    Sema &S;
11312    SourceLocation Loc;
11313
11314  public:
11315    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11316
11317    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11318
11319    bool TraverseTemplateArgument(const TemplateArgument &Arg);
11320    bool TraverseRecordType(RecordType *T);
11321  };
11322}
11323
11324bool MarkReferencedDecls::TraverseTemplateArgument(
11325  const TemplateArgument &Arg) {
11326  if (Arg.getKind() == TemplateArgument::Declaration) {
11327    if (Decl *D = Arg.getAsDecl())
11328      S.MarkAnyDeclReferenced(Loc, D, true);
11329  }
11330
11331  return Inherited::TraverseTemplateArgument(Arg);
11332}
11333
11334bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11335  if (ClassTemplateSpecializationDecl *Spec
11336                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11337    const TemplateArgumentList &Args = Spec->getTemplateArgs();
11338    return TraverseTemplateArguments(Args.data(), Args.size());
11339  }
11340
11341  return true;
11342}
11343
11344void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11345  MarkReferencedDecls Marker(*this, Loc);
11346  Marker.TraverseType(Context.getCanonicalType(T));
11347}
11348
11349namespace {
11350  /// \brief Helper class that marks all of the declarations referenced by
11351  /// potentially-evaluated subexpressions as "referenced".
11352  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11353    Sema &S;
11354    bool SkipLocalVariables;
11355
11356  public:
11357    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11358
11359    EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11360      : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11361
11362    void VisitDeclRefExpr(DeclRefExpr *E) {
11363      // If we were asked not to visit local variables, don't.
11364      if (SkipLocalVariables) {
11365        if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11366          if (VD->hasLocalStorage())
11367            return;
11368      }
11369
11370      S.MarkDeclRefReferenced(E);
11371    }
11372
11373    void VisitMemberExpr(MemberExpr *E) {
11374      S.MarkMemberReferenced(E);
11375      Inherited::VisitMemberExpr(E);
11376    }
11377
11378    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11379      S.MarkFunctionReferenced(E->getLocStart(),
11380            const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11381      Visit(E->getSubExpr());
11382    }
11383
11384    void VisitCXXNewExpr(CXXNewExpr *E) {
11385      if (E->getOperatorNew())
11386        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11387      if (E->getOperatorDelete())
11388        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11389      Inherited::VisitCXXNewExpr(E);
11390    }
11391
11392    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11393      if (E->getOperatorDelete())
11394        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11395      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11396      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11397        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11398        S.MarkFunctionReferenced(E->getLocStart(),
11399                                    S.LookupDestructor(Record));
11400      }
11401
11402      Inherited::VisitCXXDeleteExpr(E);
11403    }
11404
11405    void VisitCXXConstructExpr(CXXConstructExpr *E) {
11406      S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11407      Inherited::VisitCXXConstructExpr(E);
11408    }
11409
11410    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11411      Visit(E->getExpr());
11412    }
11413
11414    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11415      Inherited::VisitImplicitCastExpr(E);
11416
11417      if (E->getCastKind() == CK_LValueToRValue)
11418        S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11419    }
11420  };
11421}
11422
11423/// \brief Mark any declarations that appear within this expression or any
11424/// potentially-evaluated subexpressions as "referenced".
11425///
11426/// \param SkipLocalVariables If true, don't mark local variables as
11427/// 'referenced'.
11428void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11429                                            bool SkipLocalVariables) {
11430  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11431}
11432
11433/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11434/// of the program being compiled.
11435///
11436/// This routine emits the given diagnostic when the code currently being
11437/// type-checked is "potentially evaluated", meaning that there is a
11438/// possibility that the code will actually be executable. Code in sizeof()
11439/// expressions, code used only during overload resolution, etc., are not
11440/// potentially evaluated. This routine will suppress such diagnostics or,
11441/// in the absolutely nutty case of potentially potentially evaluated
11442/// expressions (C++ typeid), queue the diagnostic to potentially emit it
11443/// later.
11444///
11445/// This routine should be used for all diagnostics that describe the run-time
11446/// behavior of a program, such as passing a non-POD value through an ellipsis.
11447/// Failure to do so will likely result in spurious diagnostics or failures
11448/// during overload resolution or within sizeof/alignof/typeof/typeid.
11449bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11450                               const PartialDiagnostic &PD) {
11451  switch (ExprEvalContexts.back().Context) {
11452  case Unevaluated:
11453    // The argument will never be evaluated, so don't complain.
11454    break;
11455
11456  case ConstantEvaluated:
11457    // Relevant diagnostics should be produced by constant evaluation.
11458    break;
11459
11460  case PotentiallyEvaluated:
11461  case PotentiallyEvaluatedIfUsed:
11462    if (Statement && getCurFunctionOrMethodDecl()) {
11463      FunctionScopes.back()->PossiblyUnreachableDiags.
11464        push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11465    }
11466    else
11467      Diag(Loc, PD);
11468
11469    return true;
11470  }
11471
11472  return false;
11473}
11474
11475bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11476                               CallExpr *CE, FunctionDecl *FD) {
11477  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11478    return false;
11479
11480  // If we're inside a decltype's expression, don't check for a valid return
11481  // type or construct temporaries until we know whether this is the last call.
11482  if (ExprEvalContexts.back().IsDecltype) {
11483    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11484    return false;
11485  }
11486
11487  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11488    FunctionDecl *FD;
11489    CallExpr *CE;
11490
11491  public:
11492    CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11493      : FD(FD), CE(CE) { }
11494
11495    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11496      if (!FD) {
11497        S.Diag(Loc, diag::err_call_incomplete_return)
11498          << T << CE->getSourceRange();
11499        return;
11500      }
11501
11502      S.Diag(Loc, diag::err_call_function_incomplete_return)
11503        << CE->getSourceRange() << FD->getDeclName() << T;
11504      S.Diag(FD->getLocation(),
11505             diag::note_function_with_incomplete_return_type_declared_here)
11506        << FD->getDeclName();
11507    }
11508  } Diagnoser(FD, CE);
11509
11510  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11511    return true;
11512
11513  return false;
11514}
11515
11516// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11517// will prevent this condition from triggering, which is what we want.
11518void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11519  SourceLocation Loc;
11520
11521  unsigned diagnostic = diag::warn_condition_is_assignment;
11522  bool IsOrAssign = false;
11523
11524  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11525    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11526      return;
11527
11528    IsOrAssign = Op->getOpcode() == BO_OrAssign;
11529
11530    // Greylist some idioms by putting them into a warning subcategory.
11531    if (ObjCMessageExpr *ME
11532          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11533      Selector Sel = ME->getSelector();
11534
11535      // self = [<foo> init...]
11536      if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11537        diagnostic = diag::warn_condition_is_idiomatic_assignment;
11538
11539      // <foo> = [<bar> nextObject]
11540      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11541        diagnostic = diag::warn_condition_is_idiomatic_assignment;
11542    }
11543
11544    Loc = Op->getOperatorLoc();
11545  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11546    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11547      return;
11548
11549    IsOrAssign = Op->getOperator() == OO_PipeEqual;
11550    Loc = Op->getOperatorLoc();
11551  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11552    return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11553  else {
11554    // Not an assignment.
11555    return;
11556  }
11557
11558  Diag(Loc, diagnostic) << E->getSourceRange();
11559
11560  SourceLocation Open = E->getLocStart();
11561  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11562  Diag(Loc, diag::note_condition_assign_silence)
11563        << FixItHint::CreateInsertion(Open, "(")
11564        << FixItHint::CreateInsertion(Close, ")");
11565
11566  if (IsOrAssign)
11567    Diag(Loc, diag::note_condition_or_assign_to_comparison)
11568      << FixItHint::CreateReplacement(Loc, "!=");
11569  else
11570    Diag(Loc, diag::note_condition_assign_to_comparison)
11571      << FixItHint::CreateReplacement(Loc, "==");
11572}
11573
11574/// \brief Redundant parentheses over an equality comparison can indicate
11575/// that the user intended an assignment used as condition.
11576void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11577  // Don't warn if the parens came from a macro.
11578  SourceLocation parenLoc = ParenE->getLocStart();
11579  if (parenLoc.isInvalid() || parenLoc.isMacroID())
11580    return;
11581  // Don't warn for dependent expressions.
11582  if (ParenE->isTypeDependent())
11583    return;
11584
11585  Expr *E = ParenE->IgnoreParens();
11586
11587  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11588    if (opE->getOpcode() == BO_EQ &&
11589        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11590                                                           == Expr::MLV_Valid) {
11591      SourceLocation Loc = opE->getOperatorLoc();
11592
11593      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11594      SourceRange ParenERange = ParenE->getSourceRange();
11595      Diag(Loc, diag::note_equality_comparison_silence)
11596        << FixItHint::CreateRemoval(ParenERange.getBegin())
11597        << FixItHint::CreateRemoval(ParenERange.getEnd());
11598      Diag(Loc, diag::note_equality_comparison_to_assign)
11599        << FixItHint::CreateReplacement(Loc, "=");
11600    }
11601}
11602
11603ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11604  DiagnoseAssignmentAsCondition(E);
11605  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11606    DiagnoseEqualityWithExtraParens(parenE);
11607
11608  ExprResult result = CheckPlaceholderExpr(E);
11609  if (result.isInvalid()) return ExprError();
11610  E = result.take();
11611
11612  if (!E->isTypeDependent()) {
11613    if (getLangOpts().CPlusPlus)
11614      return CheckCXXBooleanCondition(E); // C++ 6.4p4
11615
11616    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11617    if (ERes.isInvalid())
11618      return ExprError();
11619    E = ERes.take();
11620
11621    QualType T = E->getType();
11622    if (!T->isScalarType()) { // C99 6.8.4.1p1
11623      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11624        << T << E->getSourceRange();
11625      return ExprError();
11626    }
11627  }
11628
11629  return Owned(E);
11630}
11631
11632ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11633                                       Expr *SubExpr) {
11634  if (!SubExpr)
11635    return ExprError();
11636
11637  return CheckBooleanCondition(SubExpr, Loc);
11638}
11639
11640namespace {
11641  /// A visitor for rebuilding a call to an __unknown_any expression
11642  /// to have an appropriate type.
11643  struct RebuildUnknownAnyFunction
11644    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11645
11646    Sema &S;
11647
11648    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11649
11650    ExprResult VisitStmt(Stmt *S) {
11651      llvm_unreachable("unexpected statement!");
11652    }
11653
11654    ExprResult VisitExpr(Expr *E) {
11655      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11656        << E->getSourceRange();
11657      return ExprError();
11658    }
11659
11660    /// Rebuild an expression which simply semantically wraps another
11661    /// expression which it shares the type and value kind of.
11662    template <class T> ExprResult rebuildSugarExpr(T *E) {
11663      ExprResult SubResult = Visit(E->getSubExpr());
11664      if (SubResult.isInvalid()) return ExprError();
11665
11666      Expr *SubExpr = SubResult.take();
11667      E->setSubExpr(SubExpr);
11668      E->setType(SubExpr->getType());
11669      E->setValueKind(SubExpr->getValueKind());
11670      assert(E->getObjectKind() == OK_Ordinary);
11671      return E;
11672    }
11673
11674    ExprResult VisitParenExpr(ParenExpr *E) {
11675      return rebuildSugarExpr(E);
11676    }
11677
11678    ExprResult VisitUnaryExtension(UnaryOperator *E) {
11679      return rebuildSugarExpr(E);
11680    }
11681
11682    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11683      ExprResult SubResult = Visit(E->getSubExpr());
11684      if (SubResult.isInvalid()) return ExprError();
11685
11686      Expr *SubExpr = SubResult.take();
11687      E->setSubExpr(SubExpr);
11688      E->setType(S.Context.getPointerType(SubExpr->getType()));
11689      assert(E->getValueKind() == VK_RValue);
11690      assert(E->getObjectKind() == OK_Ordinary);
11691      return E;
11692    }
11693
11694    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11695      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11696
11697      E->setType(VD->getType());
11698
11699      assert(E->getValueKind() == VK_RValue);
11700      if (S.getLangOpts().CPlusPlus &&
11701          !(isa<CXXMethodDecl>(VD) &&
11702            cast<CXXMethodDecl>(VD)->isInstance()))
11703        E->setValueKind(VK_LValue);
11704
11705      return E;
11706    }
11707
11708    ExprResult VisitMemberExpr(MemberExpr *E) {
11709      return resolveDecl(E, E->getMemberDecl());
11710    }
11711
11712    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11713      return resolveDecl(E, E->getDecl());
11714    }
11715  };
11716}
11717
11718/// Given a function expression of unknown-any type, try to rebuild it
11719/// to have a function type.
11720static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11721  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11722  if (Result.isInvalid()) return ExprError();
11723  return S.DefaultFunctionArrayConversion(Result.take());
11724}
11725
11726namespace {
11727  /// A visitor for rebuilding an expression of type __unknown_anytype
11728  /// into one which resolves the type directly on the referring
11729  /// expression.  Strict preservation of the original source
11730  /// structure is not a goal.
11731  struct RebuildUnknownAnyExpr
11732    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11733
11734    Sema &S;
11735
11736    /// The current destination type.
11737    QualType DestType;
11738
11739    RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11740      : S(S), DestType(CastType) {}
11741
11742    ExprResult VisitStmt(Stmt *S) {
11743      llvm_unreachable("unexpected statement!");
11744    }
11745
11746    ExprResult VisitExpr(Expr *E) {
11747      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11748        << E->getSourceRange();
11749      return ExprError();
11750    }
11751
11752    ExprResult VisitCallExpr(CallExpr *E);
11753    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11754
11755    /// Rebuild an expression which simply semantically wraps another
11756    /// expression which it shares the type and value kind of.
11757    template <class T> ExprResult rebuildSugarExpr(T *E) {
11758      ExprResult SubResult = Visit(E->getSubExpr());
11759      if (SubResult.isInvalid()) return ExprError();
11760      Expr *SubExpr = SubResult.take();
11761      E->setSubExpr(SubExpr);
11762      E->setType(SubExpr->getType());
11763      E->setValueKind(SubExpr->getValueKind());
11764      assert(E->getObjectKind() == OK_Ordinary);
11765      return E;
11766    }
11767
11768    ExprResult VisitParenExpr(ParenExpr *E) {
11769      return rebuildSugarExpr(E);
11770    }
11771
11772    ExprResult VisitUnaryExtension(UnaryOperator *E) {
11773      return rebuildSugarExpr(E);
11774    }
11775
11776    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11777      const PointerType *Ptr = DestType->getAs<PointerType>();
11778      if (!Ptr) {
11779        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11780          << E->getSourceRange();
11781        return ExprError();
11782      }
11783      assert(E->getValueKind() == VK_RValue);
11784      assert(E->getObjectKind() == OK_Ordinary);
11785      E->setType(DestType);
11786
11787      // Build the sub-expression as if it were an object of the pointee type.
11788      DestType = Ptr->getPointeeType();
11789      ExprResult SubResult = Visit(E->getSubExpr());
11790      if (SubResult.isInvalid()) return ExprError();
11791      E->setSubExpr(SubResult.take());
11792      return E;
11793    }
11794
11795    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11796
11797    ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11798
11799    ExprResult VisitMemberExpr(MemberExpr *E) {
11800      return resolveDecl(E, E->getMemberDecl());
11801    }
11802
11803    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11804      return resolveDecl(E, E->getDecl());
11805    }
11806  };
11807}
11808
11809/// Rebuilds a call expression which yielded __unknown_anytype.
11810ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11811  Expr *CalleeExpr = E->getCallee();
11812
11813  enum FnKind {
11814    FK_MemberFunction,
11815    FK_FunctionPointer,
11816    FK_BlockPointer
11817  };
11818
11819  FnKind Kind;
11820  QualType CalleeType = CalleeExpr->getType();
11821  if (CalleeType == S.Context.BoundMemberTy) {
11822    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11823    Kind = FK_MemberFunction;
11824    CalleeType = Expr::findBoundMemberType(CalleeExpr);
11825  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11826    CalleeType = Ptr->getPointeeType();
11827    Kind = FK_FunctionPointer;
11828  } else {
11829    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11830    Kind = FK_BlockPointer;
11831  }
11832  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11833
11834  // Verify that this is a legal result type of a function.
11835  if (DestType->isArrayType() || DestType->isFunctionType()) {
11836    unsigned diagID = diag::err_func_returning_array_function;
11837    if (Kind == FK_BlockPointer)
11838      diagID = diag::err_block_returning_array_function;
11839
11840    S.Diag(E->getExprLoc(), diagID)
11841      << DestType->isFunctionType() << DestType;
11842    return ExprError();
11843  }
11844
11845  // Otherwise, go ahead and set DestType as the call's result.
11846  E->setType(DestType.getNonLValueExprType(S.Context));
11847  E->setValueKind(Expr::getValueKindForType(DestType));
11848  assert(E->getObjectKind() == OK_Ordinary);
11849
11850  // Rebuild the function type, replacing the result type with DestType.
11851  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11852    DestType =
11853      S.Context.getFunctionType(DestType,
11854                                ArrayRef<QualType>(Proto->arg_type_begin(),
11855                                                   Proto->getNumArgs()),
11856                                Proto->getExtProtoInfo());
11857  else
11858    DestType = S.Context.getFunctionNoProtoType(DestType,
11859                                                FnType->getExtInfo());
11860
11861  // Rebuild the appropriate pointer-to-function type.
11862  switch (Kind) {
11863  case FK_MemberFunction:
11864    // Nothing to do.
11865    break;
11866
11867  case FK_FunctionPointer:
11868    DestType = S.Context.getPointerType(DestType);
11869    break;
11870
11871  case FK_BlockPointer:
11872    DestType = S.Context.getBlockPointerType(DestType);
11873    break;
11874  }
11875
11876  // Finally, we can recurse.
11877  ExprResult CalleeResult = Visit(CalleeExpr);
11878  if (!CalleeResult.isUsable()) return ExprError();
11879  E->setCallee(CalleeResult.take());
11880
11881  // Bind a temporary if necessary.
11882  return S.MaybeBindToTemporary(E);
11883}
11884
11885ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11886  // Verify that this is a legal result type of a call.
11887  if (DestType->isArrayType() || DestType->isFunctionType()) {
11888    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11889      << DestType->isFunctionType() << DestType;
11890    return ExprError();
11891  }
11892
11893  // Rewrite the method result type if available.
11894  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11895    assert(Method->getResultType() == S.Context.UnknownAnyTy);
11896    Method->setResultType(DestType);
11897  }
11898
11899  // Change the type of the message.
11900  E->setType(DestType.getNonReferenceType());
11901  E->setValueKind(Expr::getValueKindForType(DestType));
11902
11903  return S.MaybeBindToTemporary(E);
11904}
11905
11906ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11907  // The only case we should ever see here is a function-to-pointer decay.
11908  if (E->getCastKind() == CK_FunctionToPointerDecay) {
11909    assert(E->getValueKind() == VK_RValue);
11910    assert(E->getObjectKind() == OK_Ordinary);
11911
11912    E->setType(DestType);
11913
11914    // Rebuild the sub-expression as the pointee (function) type.
11915    DestType = DestType->castAs<PointerType>()->getPointeeType();
11916
11917    ExprResult Result = Visit(E->getSubExpr());
11918    if (!Result.isUsable()) return ExprError();
11919
11920    E->setSubExpr(Result.take());
11921    return S.Owned(E);
11922  } else if (E->getCastKind() == CK_LValueToRValue) {
11923    assert(E->getValueKind() == VK_RValue);
11924    assert(E->getObjectKind() == OK_Ordinary);
11925
11926    assert(isa<BlockPointerType>(E->getType()));
11927
11928    E->setType(DestType);
11929
11930    // The sub-expression has to be a lvalue reference, so rebuild it as such.
11931    DestType = S.Context.getLValueReferenceType(DestType);
11932
11933    ExprResult Result = Visit(E->getSubExpr());
11934    if (!Result.isUsable()) return ExprError();
11935
11936    E->setSubExpr(Result.take());
11937    return S.Owned(E);
11938  } else {
11939    llvm_unreachable("Unhandled cast type!");
11940  }
11941}
11942
11943ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11944  ExprValueKind ValueKind = VK_LValue;
11945  QualType Type = DestType;
11946
11947  // We know how to make this work for certain kinds of decls:
11948
11949  //  - functions
11950  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11951    if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11952      DestType = Ptr->getPointeeType();
11953      ExprResult Result = resolveDecl(E, VD);
11954      if (Result.isInvalid()) return ExprError();
11955      return S.ImpCastExprToType(Result.take(), Type,
11956                                 CK_FunctionToPointerDecay, VK_RValue);
11957    }
11958
11959    if (!Type->isFunctionType()) {
11960      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11961        << VD << E->getSourceRange();
11962      return ExprError();
11963    }
11964
11965    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11966      if (MD->isInstance()) {
11967        ValueKind = VK_RValue;
11968        Type = S.Context.BoundMemberTy;
11969      }
11970
11971    // Function references aren't l-values in C.
11972    if (!S.getLangOpts().CPlusPlus)
11973      ValueKind = VK_RValue;
11974
11975  //  - variables
11976  } else if (isa<VarDecl>(VD)) {
11977    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11978      Type = RefTy->getPointeeType();
11979    } else if (Type->isFunctionType()) {
11980      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11981        << VD << E->getSourceRange();
11982      return ExprError();
11983    }
11984
11985  //  - nothing else
11986  } else {
11987    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11988      << VD << E->getSourceRange();
11989    return ExprError();
11990  }
11991
11992  VD->setType(DestType);
11993  E->setType(Type);
11994  E->setValueKind(ValueKind);
11995  return S.Owned(E);
11996}
11997
11998/// Check a cast of an unknown-any type.  We intentionally only
11999/// trigger this for C-style casts.
12000ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12001                                     Expr *CastExpr, CastKind &CastKind,
12002                                     ExprValueKind &VK, CXXCastPath &Path) {
12003  // Rewrite the casted expression from scratch.
12004  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12005  if (!result.isUsable()) return ExprError();
12006
12007  CastExpr = result.take();
12008  VK = CastExpr->getValueKind();
12009  CastKind = CK_NoOp;
12010
12011  return CastExpr;
12012}
12013
12014ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12015  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12016}
12017
12018ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12019                                    Expr *arg, QualType &paramType) {
12020  // If the syntactic form of the argument is not an explicit cast of
12021  // any sort, just do default argument promotion.
12022  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12023  if (!castArg) {
12024    ExprResult result = DefaultArgumentPromotion(arg);
12025    if (result.isInvalid()) return ExprError();
12026    paramType = result.get()->getType();
12027    return result;
12028  }
12029
12030  // Otherwise, use the type that was written in the explicit cast.
12031  assert(!arg->hasPlaceholderType());
12032  paramType = castArg->getTypeAsWritten();
12033
12034  // Copy-initialize a parameter of that type.
12035  InitializedEntity entity =
12036    InitializedEntity::InitializeParameter(Context, paramType,
12037                                           /*consumed*/ false);
12038  return PerformCopyInitialization(entity, callLoc, Owned(arg));
12039}
12040
12041static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12042  Expr *orig = E;
12043  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12044  while (true) {
12045    E = E->IgnoreParenImpCasts();
12046    if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12047      E = call->getCallee();
12048      diagID = diag::err_uncasted_call_of_unknown_any;
12049    } else {
12050      break;
12051    }
12052  }
12053
12054  SourceLocation loc;
12055  NamedDecl *d;
12056  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12057    loc = ref->getLocation();
12058    d = ref->getDecl();
12059  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12060    loc = mem->getMemberLoc();
12061    d = mem->getMemberDecl();
12062  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12063    diagID = diag::err_uncasted_call_of_unknown_any;
12064    loc = msg->getSelectorStartLoc();
12065    d = msg->getMethodDecl();
12066    if (!d) {
12067      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12068        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12069        << orig->getSourceRange();
12070      return ExprError();
12071    }
12072  } else {
12073    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12074      << E->getSourceRange();
12075    return ExprError();
12076  }
12077
12078  S.Diag(loc, diagID) << d << orig->getSourceRange();
12079
12080  // Never recoverable.
12081  return ExprError();
12082}
12083
12084/// Check for operands with placeholder types and complain if found.
12085/// Returns true if there was an error and no recovery was possible.
12086ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12087  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12088  if (!placeholderType) return Owned(E);
12089
12090  switch (placeholderType->getKind()) {
12091
12092  // Overloaded expressions.
12093  case BuiltinType::Overload: {
12094    // Try to resolve a single function template specialization.
12095    // This is obligatory.
12096    ExprResult result = Owned(E);
12097    if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12098      return result;
12099
12100    // If that failed, try to recover with a call.
12101    } else {
12102      tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12103                           /*complain*/ true);
12104      return result;
12105    }
12106  }
12107
12108  // Bound member functions.
12109  case BuiltinType::BoundMember: {
12110    ExprResult result = Owned(E);
12111    tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12112                         /*complain*/ true);
12113    return result;
12114  }
12115
12116  // ARC unbridged casts.
12117  case BuiltinType::ARCUnbridgedCast: {
12118    Expr *realCast = stripARCUnbridgedCast(E);
12119    diagnoseARCUnbridgedCast(realCast);
12120    return Owned(realCast);
12121  }
12122
12123  // Expressions of unknown type.
12124  case BuiltinType::UnknownAny:
12125    return diagnoseUnknownAnyExpr(*this, E);
12126
12127  // Pseudo-objects.
12128  case BuiltinType::PseudoObject:
12129    return checkPseudoObjectRValue(E);
12130
12131  case BuiltinType::BuiltinFn:
12132    Diag(E->getLocStart(), diag::err_builtin_fn_use);
12133    return ExprError();
12134
12135  // Everything else should be impossible.
12136#define BUILTIN_TYPE(Id, SingletonId) \
12137  case BuiltinType::Id:
12138#define PLACEHOLDER_TYPE(Id, SingletonId)
12139#include "clang/AST/BuiltinTypes.def"
12140    break;
12141  }
12142
12143  llvm_unreachable("invalid placeholder type!");
12144}
12145
12146bool Sema::CheckCaseExpression(Expr *E) {
12147  if (E->isTypeDependent())
12148    return true;
12149  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12150    return E->getType()->isIntegralOrEnumerationType();
12151  return false;
12152}
12153
12154/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12155ExprResult
12156Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12157  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12158         "Unknown Objective-C Boolean value!");
12159  QualType BoolT = Context.ObjCBuiltinBoolTy;
12160  if (!Context.getBOOLDecl()) {
12161    LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12162                        Sema::LookupOrdinaryName);
12163    if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12164      NamedDecl *ND = Result.getFoundDecl();
12165      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12166        Context.setBOOLDecl(TD);
12167    }
12168  }
12169  if (Context.getBOOLDecl())
12170    BoolT = Context.getBOOLType();
12171  return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12172                                        BoolT, OpLoc));
12173}
12174