SemaExpr.cpp revision e1971a136a75e6722059d759d9700e411f63f344
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 "clang/Sema/DelayedDiagnostic.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ScopeInfo.h"
19#include "clang/Sema/AnalysisBasedWarnings.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTMutationListener.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
30#include "clang/AST/RecursiveASTVisitor.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/PartialDiagnostic.h"
33#include "clang/Basic/SourceManager.h"
34#include "clang/Basic/TargetInfo.h"
35#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/ScopeInfo.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/SemaFixItUtils.h"
43#include "clang/Sema/Template.h"
44#include "TreeTransform.h"
45using namespace clang;
46using namespace sema;
47
48/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51  // See if this is an auto-typed variable whose initializer we are parsing.
52  if (ParsingInitForAutoVars.count(D))
53    return false;
54
55  // See if this is a deleted function.
56  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57    if (FD->isDeleted())
58      return false;
59  }
60
61  // See if this function is unavailable.
62  if (D->getAvailability() == AR_Unavailable &&
63      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64    return false;
65
66  return true;
67}
68
69static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
70                              NamedDecl *D, SourceLocation Loc,
71                              const ObjCInterfaceDecl *UnknownObjCClass) {
72  // See if this declaration is unavailable or deprecated.
73  std::string Message;
74  AvailabilityResult Result = D->getAvailability(&Message);
75  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76    if (Result == AR_Available) {
77      const DeclContext *DC = ECD->getDeclContext();
78      if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79        Result = TheEnumDecl->getAvailability(&Message);
80    }
81
82  switch (Result) {
83    case AR_Available:
84    case AR_NotYetIntroduced:
85      break;
86
87    case AR_Deprecated:
88      S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
89      break;
90
91    case AR_Unavailable:
92      if (S.getCurContextAvailability() != AR_Unavailable) {
93        if (Message.empty()) {
94          if (!UnknownObjCClass)
95            S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
96          else
97            S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
98              << D->getDeclName();
99        }
100        else
101          S.Diag(Loc, diag::err_unavailable_message)
102            << D->getDeclName() << Message;
103          S.Diag(D->getLocation(), diag::note_unavailable_here)
104          << isa<FunctionDecl>(D) << false;
105      }
106      break;
107    }
108    return Result;
109}
110
111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
115  if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116    // If the method was explicitly defaulted, point at that declaration.
117    if (!Method->isImplicit())
118      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120    // Try to diagnose why this special member function was implicitly
121    // deleted. This might fail, if that reason no longer applies.
122    CXXSpecialMember CSM = getSpecialMember(Method);
123    if (CSM != CXXInvalid)
124      ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126    return;
127  }
128
129  Diag(Decl->getLocation(), diag::note_unavailable_here)
130    << 1 << Decl->isDeleted();
131}
132
133/// \brief Determine whether a FunctionDecl was ever declared with an
134/// explicit storage class.
135static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136  for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137                                     E = D->redecls_end();
138       I != E; ++I) {
139    if (I->getStorageClassAsWritten() != SC_None)
140      return true;
141  }
142  return false;
143}
144
145/// \brief Check whether we're in an extern inline function and referring to a
146/// variable or function with internal linkage (C11 6.7.4p3).
147///
148/// This is only a warning because we used to silently accept this code, but
149/// in many cases it will not behave correctly. This is not enabled in C++ mode
150/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151/// and so while there may still be user mistakes, most of the time we can't
152/// prove that there are errors.
153static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154                                                      const NamedDecl *D,
155                                                      SourceLocation Loc) {
156  // This is disabled under C++; there are too many ways for this to fire in
157  // contexts where the warning is a false positive, or where it is technically
158  // correct but benign.
159  if (S.getLangOpts().CPlusPlus)
160    return;
161
162  // Check if this is an inlined function or method.
163  FunctionDecl *Current = S.getCurFunctionDecl();
164  if (!Current)
165    return;
166  if (!Current->isInlined())
167    return;
168  if (Current->getLinkage() != ExternalLinkage)
169    return;
170
171  // Check if the decl has internal linkage.
172  if (D->getLinkage() != InternalLinkage)
173    return;
174
175  // Downgrade from ExtWarn to Extension if
176  //  (1) the supposedly external inline function is in the main file,
177  //      and probably won't be included anywhere else.
178  //  (2) the thing we're referencing is a pure function.
179  //  (3) the thing we're referencing is another inline function.
180  // This last can give us false negatives, but it's better than warning on
181  // wrappers for simple C library functions.
182  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183  bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184  if (!DowngradeWarning && UsedFn)
185    DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186
187  S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188                               : diag::warn_internal_in_extern_inline)
189    << /*IsVar=*/!UsedFn << D;
190
191  // Suggest "static" on the inline function, if possible.
192  if (!hasAnyExplicitStorageClass(Current)) {
193    const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194    SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195    S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196      << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197  }
198
199  S.Diag(D->getCanonicalDecl()->getLocation(),
200         diag::note_internal_decl_declared_here)
201    << D;
202}
203
204/// \brief Determine whether the use of this declaration is valid, and
205/// emit any corresponding diagnostics.
206///
207/// This routine diagnoses various problems with referencing
208/// declarations that can occur when using a declaration. For example,
209/// it might warn if a deprecated or unavailable declaration is being
210/// used, or produce an error (and return true) if a C++0x deleted
211/// function is being used.
212///
213/// \returns true if there was an error (this declaration cannot be
214/// referenced), false otherwise.
215///
216bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
217                             const ObjCInterfaceDecl *UnknownObjCClass) {
218  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
219    // If there were any diagnostics suppressed by template argument deduction,
220    // emit them now.
221    llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
222      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223    if (Pos != SuppressedDiagnostics.end()) {
224      SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
225      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226        Diag(Suppressed[I].first, Suppressed[I].second);
227
228      // Clear out the list of suppressed diagnostics, so that we don't emit
229      // them again for this specialization. However, we don't obsolete this
230      // entry from the table, because we want to avoid ever emitting these
231      // diagnostics again.
232      Suppressed.clear();
233    }
234  }
235
236  // See if this is an auto-typed variable whose initializer we are parsing.
237  if (ParsingInitForAutoVars.count(D)) {
238    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239      << D->getDeclName();
240    return true;
241  }
242
243  // See if this is a deleted function.
244  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245    if (FD->isDeleted()) {
246      Diag(Loc, diag::err_deleted_function_use);
247      NoteDeletedFunction(FD);
248      return true;
249    }
250  }
251  DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
252
253  // Warn if this is used but marked unused.
254  if (D->hasAttr<UnusedAttr>())
255    Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
256
257  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
258
259  return false;
260}
261
262/// \brief Retrieve the message suffix that should be added to a
263/// diagnostic complaining about the given function being deleted or
264/// unavailable.
265std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266  // FIXME: C++0x implicitly-deleted special member functions could be
267  // detected here so that we could improve diagnostics to say, e.g.,
268  // "base class 'A' had a deleted copy constructor".
269  if (FD->isDeleted())
270    return std::string();
271
272  std::string Message;
273  if (FD->getAvailability(&Message))
274    return ": " + Message;
275
276  return std::string();
277}
278
279/// DiagnoseSentinelCalls - This routine checks whether a call or
280/// message-send is to a declaration with the sentinel attribute, and
281/// if so, it checks that the requirements of the sentinel are
282/// satisfied.
283void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
284                                 Expr **args, unsigned numArgs) {
285  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
286  if (!attr)
287    return;
288
289  // The number of formal parameters of the declaration.
290  unsigned numFormalParams;
291
292  // The kind of declaration.  This is also an index into a %select in
293  // the diagnostic.
294  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295
296  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
297    numFormalParams = MD->param_size();
298    calleeType = CT_Method;
299  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
300    numFormalParams = FD->param_size();
301    calleeType = CT_Function;
302  } else if (isa<VarDecl>(D)) {
303    QualType type = cast<ValueDecl>(D)->getType();
304    const FunctionType *fn = 0;
305    if (const PointerType *ptr = type->getAs<PointerType>()) {
306      fn = ptr->getPointeeType()->getAs<FunctionType>();
307      if (!fn) return;
308      calleeType = CT_Function;
309    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310      fn = ptr->getPointeeType()->castAs<FunctionType>();
311      calleeType = CT_Block;
312    } else {
313      return;
314    }
315
316    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317      numFormalParams = proto->getNumArgs();
318    } else {
319      numFormalParams = 0;
320    }
321  } else {
322    return;
323  }
324
325  // "nullPos" is the number of formal parameters at the end which
326  // effectively count as part of the variadic arguments.  This is
327  // useful if you would prefer to not have *any* formal parameters,
328  // but the language forces you to have at least one.
329  unsigned nullPos = attr->getNullPos();
330  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332
333  // The number of arguments which should follow the sentinel.
334  unsigned numArgsAfterSentinel = attr->getSentinel();
335
336  // If there aren't enough arguments for all the formal parameters,
337  // the sentinel, and the args after the sentinel, complain.
338  if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
339    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
340    Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
341    return;
342  }
343
344  // Otherwise, find the sentinel expression.
345  Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
346  if (!sentinelExpr) return;
347  if (sentinelExpr->isValueDependent()) return;
348  if (Context.isSentinelNullExpr(sentinelExpr)) return;
349
350  // Pick a reasonable string to insert.  Optimistically use 'nil' or
351  // 'NULL' if those are actually defined in the context.  Only use
352  // 'nil' for ObjC methods, where it's much more likely that the
353  // variadic arguments form a list of object pointers.
354  SourceLocation MissingNilLoc
355    = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356  std::string NullValue;
357  if (calleeType == CT_Method &&
358      PP.getIdentifierInfo("nil")->hasMacroDefinition())
359    NullValue = "nil";
360  else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361    NullValue = "NULL";
362  else
363    NullValue = "(void*) 0";
364
365  if (MissingNilLoc.isInvalid())
366    Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367  else
368    Diag(MissingNilLoc, diag::warn_missing_sentinel)
369      << calleeType
370      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
371  Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
372}
373
374SourceRange Sema::getExprRange(Expr *E) const {
375  return E ? E->getSourceRange() : SourceRange();
376}
377
378//===----------------------------------------------------------------------===//
379//  Standard Promotions and Conversions
380//===----------------------------------------------------------------------===//
381
382/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
383ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
384  // Handle any placeholder expressions which made it here.
385  if (E->getType()->isPlaceholderType()) {
386    ExprResult result = CheckPlaceholderExpr(E);
387    if (result.isInvalid()) return ExprError();
388    E = result.take();
389  }
390
391  QualType Ty = E->getType();
392  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393
394  if (Ty->isFunctionType())
395    E = ImpCastExprToType(E, Context.getPointerType(Ty),
396                          CK_FunctionToPointerDecay).take();
397  else if (Ty->isArrayType()) {
398    // In C90 mode, arrays only promote to pointers if the array expression is
399    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400    // type 'array of type' is converted to an expression that has type 'pointer
401    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
402    // that has type 'array of type' ...".  The relevant change is "an lvalue"
403    // (C90) to "an expression" (C99).
404    //
405    // C++ 4.2p1:
406    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407    // T" can be converted to an rvalue of type "pointer to T".
408    //
409    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
410      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411                            CK_ArrayToPointerDecay).take();
412  }
413  return Owned(E);
414}
415
416static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417  // Check to see if we are dereferencing a null pointer.  If so,
418  // and if not volatile-qualified, this is undefined behavior that the
419  // optimizer will delete, so warn about it.  People sometimes try to use this
420  // to get a deterministic trap and are surprised by clang's behavior.  This
421  // only handles the pattern "*null", which is a very syntactic check.
422  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423    if (UO->getOpcode() == UO_Deref &&
424        UO->getSubExpr()->IgnoreParenCasts()->
425          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426        !UO->getType().isVolatileQualified()) {
427    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428                          S.PDiag(diag::warn_indirection_through_null)
429                            << UO->getSubExpr()->getSourceRange());
430    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431                        S.PDiag(diag::note_indirection_through_null));
432  }
433}
434
435ExprResult Sema::DefaultLvalueConversion(Expr *E) {
436  // Handle any placeholder expressions which made it here.
437  if (E->getType()->isPlaceholderType()) {
438    ExprResult result = CheckPlaceholderExpr(E);
439    if (result.isInvalid()) return ExprError();
440    E = result.take();
441  }
442
443  // C++ [conv.lval]p1:
444  //   A glvalue of a non-function, non-array type T can be
445  //   converted to a prvalue.
446  if (!E->isGLValue()) return Owned(E);
447
448  QualType T = E->getType();
449  assert(!T.isNull() && "r-value conversion on typeless expression?");
450
451  // We don't want to throw lvalue-to-rvalue casts on top of
452  // expressions of certain types in C++.
453  if (getLangOpts().CPlusPlus &&
454      (E->getType() == Context.OverloadTy ||
455       T->isDependentType() ||
456       T->isRecordType()))
457    return Owned(E);
458
459  // The C standard is actually really unclear on this point, and
460  // DR106 tells us what the result should be but not why.  It's
461  // generally best to say that void types just doesn't undergo
462  // lvalue-to-rvalue at all.  Note that expressions of unqualified
463  // 'void' type are never l-values, but qualified void can be.
464  if (T->isVoidType())
465    return Owned(E);
466
467  CheckForNullPointerDereference(*this, E);
468
469  // C++ [conv.lval]p1:
470  //   [...] If T is a non-class type, the type of the prvalue is the
471  //   cv-unqualified version of T. Otherwise, the type of the
472  //   rvalue is T.
473  //
474  // C99 6.3.2.1p2:
475  //   If the lvalue has qualified type, the value has the unqualified
476  //   version of the type of the lvalue; otherwise, the value has the
477  //   type of the lvalue.
478  if (T.hasQualifiers())
479    T = T.getUnqualifiedType();
480
481  UpdateMarkingForLValueToRValue(E);
482
483  ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484                                                  E, 0, VK_RValue));
485
486  // C11 6.3.2.1p2:
487  //   ... if the lvalue has atomic type, the value has the non-atomic version
488  //   of the type of the lvalue ...
489  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490    T = Atomic->getValueType().getUnqualifiedType();
491    Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492                                         Res.get(), 0, VK_RValue));
493  }
494
495  return Res;
496}
497
498ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499  ExprResult Res = DefaultFunctionArrayConversion(E);
500  if (Res.isInvalid())
501    return ExprError();
502  Res = DefaultLvalueConversion(Res.take());
503  if (Res.isInvalid())
504    return ExprError();
505  return move(Res);
506}
507
508
509/// UsualUnaryConversions - Performs various conversions that are common to most
510/// operators (C99 6.3). The conversions of array and function types are
511/// sometimes suppressed. For example, the array->pointer conversion doesn't
512/// apply if the array is an argument to the sizeof or address (&) operators.
513/// In these instances, this routine should *not* be called.
514ExprResult Sema::UsualUnaryConversions(Expr *E) {
515  // First, convert to an r-value.
516  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517  if (Res.isInvalid())
518    return Owned(E);
519  E = Res.take();
520
521  QualType Ty = E->getType();
522  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
523
524  // Half FP is a bit different: it's a storage-only type, meaning that any
525  // "use" of it should be promoted to float.
526  if (Ty->isHalfType())
527    return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528
529  // Try to perform integral promotions if the object has a theoretically
530  // promotable type.
531  if (Ty->isIntegralOrUnscopedEnumerationType()) {
532    // C99 6.3.1.1p2:
533    //
534    //   The following may be used in an expression wherever an int or
535    //   unsigned int may be used:
536    //     - an object or expression with an integer type whose integer
537    //       conversion rank is less than or equal to the rank of int
538    //       and unsigned int.
539    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
540    //
541    //   If an int can represent all values of the original type, the
542    //   value is converted to an int; otherwise, it is converted to an
543    //   unsigned int. These are called the integer promotions. All
544    //   other types are unchanged by the integer promotions.
545
546    QualType PTy = Context.isPromotableBitField(E);
547    if (!PTy.isNull()) {
548      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549      return Owned(E);
550    }
551    if (Ty->isPromotableIntegerType()) {
552      QualType PT = Context.getPromotedIntegerType(Ty);
553      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554      return Owned(E);
555    }
556  }
557  return Owned(E);
558}
559
560/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
561/// do not have a prototype. Arguments that have type float are promoted to
562/// double. All other argument types are converted by UsualUnaryConversions().
563ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564  QualType Ty = E->getType();
565  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
566
567  ExprResult Res = UsualUnaryConversions(E);
568  if (Res.isInvalid())
569    return Owned(E);
570  E = Res.take();
571
572  // If this is a 'float' (CVR qualified or typedef) promote to double.
573  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
574    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575
576  // C++ performs lvalue-to-rvalue conversion as a default argument
577  // promotion, even on class types, but note:
578  //   C++11 [conv.lval]p2:
579  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
580  //     operand or a subexpression thereof the value contained in the
581  //     referenced object is not accessed. Otherwise, if the glvalue
582  //     has a class type, the conversion copy-initializes a temporary
583  //     of type T from the glvalue and the result of the conversion
584  //     is a prvalue for the temporary.
585  // FIXME: add some way to gate this entire thing for correctness in
586  // potentially potentially evaluated contexts.
587  if (getLangOpts().CPlusPlus && E->isGLValue() &&
588      ExprEvalContexts.back().Context != Unevaluated) {
589    ExprResult Temp = PerformCopyInitialization(
590                       InitializedEntity::InitializeTemporary(E->getType()),
591                                                E->getExprLoc(),
592                                                Owned(E));
593    if (Temp.isInvalid())
594      return ExprError();
595    E = Temp.get();
596  }
597
598  return Owned(E);
599}
600
601/// Determine the degree of POD-ness for an expression.
602/// Incomplete types are considered POD, since this check can be performed
603/// when we're in an unevaluated context.
604Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
605  if (Ty->isIncompleteType() || Ty.isCXX98PODType(Context))
606    return VAK_Valid;
607  // C++0x [expr.call]p7:
608  //   Passing a potentially-evaluated argument of class type (Clause 9)
609  //   having a non-trivial copy constructor, a non-trivial move constructor,
610  //   or a non-trivial destructor, with no corresponding parameter,
611  //   is conditionally-supported with implementation-defined semantics.
612
613  if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
614    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
615      if (Record->hasTrivialCopyConstructor() &&
616          Record->hasTrivialMoveConstructor() &&
617          Record->hasTrivialDestructor())
618        return VAK_ValidInCXX11;
619
620  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
621    return VAK_Valid;
622  return VAK_Invalid;
623}
624
625bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
626  // Don't allow one to pass an Objective-C interface to a vararg.
627  const QualType & Ty = E->getType();
628
629  // Complain about passing non-POD types through varargs.
630  switch (isValidVarArgType(Ty)) {
631  case VAK_Valid:
632    break;
633  case VAK_ValidInCXX11:
634    DiagRuntimeBehavior(E->getLocStart(), 0,
635        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
636        << E->getType() << CT);
637    break;
638  case VAK_Invalid:
639    return DiagRuntimeBehavior(E->getLocStart(), 0,
640                   PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
641                   << getLangOpts().CPlusPlus0x << Ty << CT);
642  }
643  // c++ rules are enforced elsewhere.
644  return false;
645}
646
647/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
648/// will warn if the resulting type is not a POD type, and rejects ObjC
649/// interfaces passed by value.
650ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
651                                                  FunctionDecl *FDecl) {
652  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
653    // Strip the unbridged-cast placeholder expression off, if applicable.
654    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
655        (CT == VariadicMethod ||
656         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
657      E = stripARCUnbridgedCast(E);
658
659    // Otherwise, do normal placeholder checking.
660    } else {
661      ExprResult ExprRes = CheckPlaceholderExpr(E);
662      if (ExprRes.isInvalid())
663        return ExprError();
664      E = ExprRes.take();
665    }
666  }
667
668  ExprResult ExprRes = DefaultArgumentPromotion(E);
669  if (ExprRes.isInvalid())
670    return ExprError();
671  E = ExprRes.take();
672
673  if (E->getType()->isObjCObjectType() &&
674    DiagRuntimeBehavior(E->getLocStart(), 0,
675                        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
676                          << E->getType() << CT))
677    return ExprError();
678
679  // Diagnostics regarding non-POD argument types are
680  // emitted along with format string checking in Sema::CheckFunctionCall().
681  if (isValidVarArgType(E->getType()) == VAK_Invalid) {
682    // Turn this into a trap.
683    CXXScopeSpec SS;
684    SourceLocation TemplateKWLoc;
685    UnqualifiedId Name;
686    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
687                       E->getLocStart());
688    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
689                                          Name, true, false);
690    if (TrapFn.isInvalid())
691      return ExprError();
692
693    ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
694                                    E->getLocStart(), MultiExprArg(),
695                                    E->getLocEnd());
696    if (Call.isInvalid())
697      return ExprError();
698
699    ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
700                                  Call.get(), E);
701    if (Comma.isInvalid())
702      return ExprError();
703    return Comma.get();
704  }
705
706  if (!getLangOpts().CPlusPlus &&
707      RequireCompleteType(E->getExprLoc(), E->getType(),
708                          diag::err_call_incomplete_argument))
709    return ExprError();
710
711  return Owned(E);
712}
713
714/// \brief Converts an integer to complex float type.  Helper function of
715/// UsualArithmeticConversions()
716///
717/// \return false if the integer expression is an integer type and is
718/// successfully converted to the complex type.
719static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
720                                                  ExprResult &ComplexExpr,
721                                                  QualType IntTy,
722                                                  QualType ComplexTy,
723                                                  bool SkipCast) {
724  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
725  if (SkipCast) return false;
726  if (IntTy->isIntegerType()) {
727    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
728    IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
729    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
730                                  CK_FloatingRealToComplex);
731  } else {
732    assert(IntTy->isComplexIntegerType());
733    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
734                                  CK_IntegralComplexToFloatingComplex);
735  }
736  return false;
737}
738
739/// \brief Takes two complex float types and converts them to the same type.
740/// Helper function of UsualArithmeticConversions()
741static QualType
742handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
743                                            ExprResult &RHS, QualType LHSType,
744                                            QualType RHSType,
745                                            bool IsCompAssign) {
746  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
747
748  if (order < 0) {
749    // _Complex float -> _Complex double
750    if (!IsCompAssign)
751      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
752    return RHSType;
753  }
754  if (order > 0)
755    // _Complex float -> _Complex double
756    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
757  return LHSType;
758}
759
760/// \brief Converts otherExpr to complex float and promotes complexExpr if
761/// necessary.  Helper function of UsualArithmeticConversions()
762static QualType handleOtherComplexFloatConversion(Sema &S,
763                                                  ExprResult &ComplexExpr,
764                                                  ExprResult &OtherExpr,
765                                                  QualType ComplexTy,
766                                                  QualType OtherTy,
767                                                  bool ConvertComplexExpr,
768                                                  bool ConvertOtherExpr) {
769  int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
770
771  // If just the complexExpr is complex, the otherExpr needs to be converted,
772  // and the complexExpr might need to be promoted.
773  if (order > 0) { // complexExpr is wider
774    // float -> _Complex double
775    if (ConvertOtherExpr) {
776      QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
777      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
778      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
779                                      CK_FloatingRealToComplex);
780    }
781    return ComplexTy;
782  }
783
784  // otherTy is at least as wide.  Find its corresponding complex type.
785  QualType result = (order == 0 ? ComplexTy :
786                                  S.Context.getComplexType(OtherTy));
787
788  // double -> _Complex double
789  if (ConvertOtherExpr)
790    OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
791                                    CK_FloatingRealToComplex);
792
793  // _Complex float -> _Complex double
794  if (ConvertComplexExpr && order < 0)
795    ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
796                                      CK_FloatingComplexCast);
797
798  return result;
799}
800
801/// \brief Handle arithmetic conversion with complex types.  Helper function of
802/// UsualArithmeticConversions()
803static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
804                                             ExprResult &RHS, QualType LHSType,
805                                             QualType RHSType,
806                                             bool IsCompAssign) {
807  // if we have an integer operand, the result is the complex type.
808  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
809                                             /*skipCast*/false))
810    return LHSType;
811  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
812                                             /*skipCast*/IsCompAssign))
813    return RHSType;
814
815  // This handles complex/complex, complex/float, or float/complex.
816  // When both operands are complex, the shorter operand is converted to the
817  // type of the longer, and that is the type of the result. This corresponds
818  // to what is done when combining two real floating-point operands.
819  // The fun begins when size promotion occur across type domains.
820  // From H&S 6.3.4: When one operand is complex and the other is a real
821  // floating-point type, the less precise type is converted, within it's
822  // real or complex domain, to the precision of the other type. For example,
823  // when combining a "long double" with a "double _Complex", the
824  // "double _Complex" is promoted to "long double _Complex".
825
826  bool LHSComplexFloat = LHSType->isComplexType();
827  bool RHSComplexFloat = RHSType->isComplexType();
828
829  // If both are complex, just cast to the more precise type.
830  if (LHSComplexFloat && RHSComplexFloat)
831    return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
832                                                       LHSType, RHSType,
833                                                       IsCompAssign);
834
835  // If only one operand is complex, promote it if necessary and convert the
836  // other operand to complex.
837  if (LHSComplexFloat)
838    return handleOtherComplexFloatConversion(
839        S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
840        /*convertOtherExpr*/ true);
841
842  assert(RHSComplexFloat);
843  return handleOtherComplexFloatConversion(
844      S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
845      /*convertOtherExpr*/ !IsCompAssign);
846}
847
848/// \brief Hande arithmetic conversion from integer to float.  Helper function
849/// of UsualArithmeticConversions()
850static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
851                                           ExprResult &IntExpr,
852                                           QualType FloatTy, QualType IntTy,
853                                           bool ConvertFloat, bool ConvertInt) {
854  if (IntTy->isIntegerType()) {
855    if (ConvertInt)
856      // Convert intExpr to the lhs floating point type.
857      IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
858                                    CK_IntegralToFloating);
859    return FloatTy;
860  }
861
862  // Convert both sides to the appropriate complex float.
863  assert(IntTy->isComplexIntegerType());
864  QualType result = S.Context.getComplexType(FloatTy);
865
866  // _Complex int -> _Complex float
867  if (ConvertInt)
868    IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
869                                  CK_IntegralComplexToFloatingComplex);
870
871  // float -> _Complex float
872  if (ConvertFloat)
873    FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
874                                    CK_FloatingRealToComplex);
875
876  return result;
877}
878
879/// \brief Handle arithmethic conversion with floating point types.  Helper
880/// function of UsualArithmeticConversions()
881static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
882                                      ExprResult &RHS, QualType LHSType,
883                                      QualType RHSType, bool IsCompAssign) {
884  bool LHSFloat = LHSType->isRealFloatingType();
885  bool RHSFloat = RHSType->isRealFloatingType();
886
887  // If we have two real floating types, convert the smaller operand
888  // to the bigger result.
889  if (LHSFloat && RHSFloat) {
890    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
891    if (order > 0) {
892      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
893      return LHSType;
894    }
895
896    assert(order < 0 && "illegal float comparison");
897    if (!IsCompAssign)
898      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
899    return RHSType;
900  }
901
902  if (LHSFloat)
903    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
904                                      /*convertFloat=*/!IsCompAssign,
905                                      /*convertInt=*/ true);
906  assert(RHSFloat);
907  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
908                                    /*convertInt=*/ true,
909                                    /*convertFloat=*/!IsCompAssign);
910}
911
912/// \brief Handle conversions with GCC complex int extension.  Helper function
913/// of UsualArithmeticConversions()
914// FIXME: if the operands are (int, _Complex long), we currently
915// don't promote the complex.  Also, signedness?
916static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
917                                           ExprResult &RHS, QualType LHSType,
918                                           QualType RHSType,
919                                           bool IsCompAssign) {
920  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
921  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
922
923  if (LHSComplexInt && RHSComplexInt) {
924    int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
925                                              RHSComplexInt->getElementType());
926    assert(order && "inequal types with equal element ordering");
927    if (order > 0) {
928      // _Complex int -> _Complex long
929      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
930      return LHSType;
931    }
932
933    if (!IsCompAssign)
934      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
935    return RHSType;
936  }
937
938  if (LHSComplexInt) {
939    // int -> _Complex int
940    // FIXME: This needs to take integer ranks into account
941    RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
942                              CK_IntegralCast);
943    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
944    return LHSType;
945  }
946
947  assert(RHSComplexInt);
948  // int -> _Complex int
949  // FIXME: This needs to take integer ranks into account
950  if (!IsCompAssign) {
951    LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
952                              CK_IntegralCast);
953    LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
954  }
955  return RHSType;
956}
957
958/// \brief Handle integer arithmetic conversions.  Helper function of
959/// UsualArithmeticConversions()
960static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
961                                        ExprResult &RHS, QualType LHSType,
962                                        QualType RHSType, bool IsCompAssign) {
963  // The rules for this case are in C99 6.3.1.8
964  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
965  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
966  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
967  if (LHSSigned == RHSSigned) {
968    // Same signedness; use the higher-ranked type
969    if (order >= 0) {
970      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
971      return LHSType;
972    } else if (!IsCompAssign)
973      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
974    return RHSType;
975  } else if (order != (LHSSigned ? 1 : -1)) {
976    // The unsigned type has greater than or equal rank to the
977    // signed type, so use the unsigned type
978    if (RHSSigned) {
979      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
980      return LHSType;
981    } else if (!IsCompAssign)
982      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
983    return RHSType;
984  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
985    // The two types are different widths; if we are here, that
986    // means the signed type is larger than the unsigned type, so
987    // use the signed type.
988    if (LHSSigned) {
989      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
990      return LHSType;
991    } else if (!IsCompAssign)
992      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
993    return RHSType;
994  } else {
995    // The signed type is higher-ranked than the unsigned type,
996    // but isn't actually any bigger (like unsigned int and long
997    // on most 32-bit systems).  Use the unsigned type corresponding
998    // to the signed type.
999    QualType result =
1000      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1001    RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1002    if (!IsCompAssign)
1003      LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1004    return result;
1005  }
1006}
1007
1008/// UsualArithmeticConversions - Performs various conversions that are common to
1009/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1010/// routine returns the first non-arithmetic type found. The client is
1011/// responsible for emitting appropriate error diagnostics.
1012/// FIXME: verify the conversion rules for "complex int" are consistent with
1013/// GCC.
1014QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1015                                          bool IsCompAssign) {
1016  if (!IsCompAssign) {
1017    LHS = UsualUnaryConversions(LHS.take());
1018    if (LHS.isInvalid())
1019      return QualType();
1020  }
1021
1022  RHS = UsualUnaryConversions(RHS.take());
1023  if (RHS.isInvalid())
1024    return QualType();
1025
1026  // For conversion purposes, we ignore any qualifiers.
1027  // For example, "const float" and "float" are equivalent.
1028  QualType LHSType =
1029    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1030  QualType RHSType =
1031    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1032
1033  // For conversion purposes, we ignore any atomic qualifier on the LHS.
1034  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1035    LHSType = AtomicLHS->getValueType();
1036
1037  // If both types are identical, no conversion is needed.
1038  if (LHSType == RHSType)
1039    return LHSType;
1040
1041  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1042  // The caller can deal with this (e.g. pointer + int).
1043  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1044    return QualType();
1045
1046  // Apply unary and bitfield promotions to the LHS's type.
1047  QualType LHSUnpromotedType = LHSType;
1048  if (LHSType->isPromotableIntegerType())
1049    LHSType = Context.getPromotedIntegerType(LHSType);
1050  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1051  if (!LHSBitfieldPromoteTy.isNull())
1052    LHSType = LHSBitfieldPromoteTy;
1053  if (LHSType != LHSUnpromotedType && !IsCompAssign)
1054    LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1055
1056  // If both types are identical, no conversion is needed.
1057  if (LHSType == RHSType)
1058    return LHSType;
1059
1060  // At this point, we have two different arithmetic types.
1061
1062  // Handle complex types first (C99 6.3.1.8p1).
1063  if (LHSType->isComplexType() || RHSType->isComplexType())
1064    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1065                                        IsCompAssign);
1066
1067  // Now handle "real" floating types (i.e. float, double, long double).
1068  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1069    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1070                                 IsCompAssign);
1071
1072  // Handle GCC complex int extension.
1073  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1074    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1075                                      IsCompAssign);
1076
1077  // Finally, we have two differing integer types.
1078  return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1079                                 IsCompAssign);
1080}
1081
1082//===----------------------------------------------------------------------===//
1083//  Semantic Analysis for various Expression Types
1084//===----------------------------------------------------------------------===//
1085
1086
1087ExprResult
1088Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1089                                SourceLocation DefaultLoc,
1090                                SourceLocation RParenLoc,
1091                                Expr *ControllingExpr,
1092                                MultiTypeArg ArgTypes,
1093                                MultiExprArg ArgExprs) {
1094  unsigned NumAssocs = ArgTypes.size();
1095  assert(NumAssocs == ArgExprs.size());
1096
1097  ParsedType *ParsedTypes = ArgTypes.release();
1098  Expr **Exprs = ArgExprs.release();
1099
1100  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1101  for (unsigned i = 0; i < NumAssocs; ++i) {
1102    if (ParsedTypes[i])
1103      (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1104    else
1105      Types[i] = 0;
1106  }
1107
1108  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1109                                             ControllingExpr, Types, Exprs,
1110                                             NumAssocs);
1111  delete [] Types;
1112  return ER;
1113}
1114
1115ExprResult
1116Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1117                                 SourceLocation DefaultLoc,
1118                                 SourceLocation RParenLoc,
1119                                 Expr *ControllingExpr,
1120                                 TypeSourceInfo **Types,
1121                                 Expr **Exprs,
1122                                 unsigned NumAssocs) {
1123  bool TypeErrorFound = false,
1124       IsResultDependent = ControllingExpr->isTypeDependent(),
1125       ContainsUnexpandedParameterPack
1126         = ControllingExpr->containsUnexpandedParameterPack();
1127
1128  for (unsigned i = 0; i < NumAssocs; ++i) {
1129    if (Exprs[i]->containsUnexpandedParameterPack())
1130      ContainsUnexpandedParameterPack = true;
1131
1132    if (Types[i]) {
1133      if (Types[i]->getType()->containsUnexpandedParameterPack())
1134        ContainsUnexpandedParameterPack = true;
1135
1136      if (Types[i]->getType()->isDependentType()) {
1137        IsResultDependent = true;
1138      } else {
1139        // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1140        // complete object type other than a variably modified type."
1141        unsigned D = 0;
1142        if (Types[i]->getType()->isIncompleteType())
1143          D = diag::err_assoc_type_incomplete;
1144        else if (!Types[i]->getType()->isObjectType())
1145          D = diag::err_assoc_type_nonobject;
1146        else if (Types[i]->getType()->isVariablyModifiedType())
1147          D = diag::err_assoc_type_variably_modified;
1148
1149        if (D != 0) {
1150          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1151            << Types[i]->getTypeLoc().getSourceRange()
1152            << Types[i]->getType();
1153          TypeErrorFound = true;
1154        }
1155
1156        // C11 6.5.1.1p2 "No two generic associations in the same generic
1157        // selection shall specify compatible types."
1158        for (unsigned j = i+1; j < NumAssocs; ++j)
1159          if (Types[j] && !Types[j]->getType()->isDependentType() &&
1160              Context.typesAreCompatible(Types[i]->getType(),
1161                                         Types[j]->getType())) {
1162            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1163                 diag::err_assoc_compatible_types)
1164              << Types[j]->getTypeLoc().getSourceRange()
1165              << Types[j]->getType()
1166              << Types[i]->getType();
1167            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1168                 diag::note_compat_assoc)
1169              << Types[i]->getTypeLoc().getSourceRange()
1170              << Types[i]->getType();
1171            TypeErrorFound = true;
1172          }
1173      }
1174    }
1175  }
1176  if (TypeErrorFound)
1177    return ExprError();
1178
1179  // If we determined that the generic selection is result-dependent, don't
1180  // try to compute the result expression.
1181  if (IsResultDependent)
1182    return Owned(new (Context) GenericSelectionExpr(
1183                   Context, KeyLoc, ControllingExpr,
1184                   Types, Exprs, NumAssocs, DefaultLoc,
1185                   RParenLoc, ContainsUnexpandedParameterPack));
1186
1187  SmallVector<unsigned, 1> CompatIndices;
1188  unsigned DefaultIndex = -1U;
1189  for (unsigned i = 0; i < NumAssocs; ++i) {
1190    if (!Types[i])
1191      DefaultIndex = i;
1192    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1193                                        Types[i]->getType()))
1194      CompatIndices.push_back(i);
1195  }
1196
1197  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1198  // type compatible with at most one of the types named in its generic
1199  // association list."
1200  if (CompatIndices.size() > 1) {
1201    // We strip parens here because the controlling expression is typically
1202    // parenthesized in macro definitions.
1203    ControllingExpr = ControllingExpr->IgnoreParens();
1204    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1205      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1206      << (unsigned) CompatIndices.size();
1207    for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1208         E = CompatIndices.end(); I != E; ++I) {
1209      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1210           diag::note_compat_assoc)
1211        << Types[*I]->getTypeLoc().getSourceRange()
1212        << Types[*I]->getType();
1213    }
1214    return ExprError();
1215  }
1216
1217  // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1218  // its controlling expression shall have type compatible with exactly one of
1219  // the types named in its generic association list."
1220  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1221    // We strip parens here because the controlling expression is typically
1222    // parenthesized in macro definitions.
1223    ControllingExpr = ControllingExpr->IgnoreParens();
1224    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1225      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1226    return ExprError();
1227  }
1228
1229  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1230  // type name that is compatible with the type of the controlling expression,
1231  // then the result expression of the generic selection is the expression
1232  // in that generic association. Otherwise, the result expression of the
1233  // generic selection is the expression in the default generic association."
1234  unsigned ResultIndex =
1235    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1236
1237  return Owned(new (Context) GenericSelectionExpr(
1238                 Context, KeyLoc, ControllingExpr,
1239                 Types, Exprs, NumAssocs, DefaultLoc,
1240                 RParenLoc, ContainsUnexpandedParameterPack,
1241                 ResultIndex));
1242}
1243
1244/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1245/// location of the token and the offset of the ud-suffix within it.
1246static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1247                                     unsigned Offset) {
1248  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1249                                        S.getLangOpts());
1250}
1251
1252/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1253/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1254static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1255                                                 IdentifierInfo *UDSuffix,
1256                                                 SourceLocation UDSuffixLoc,
1257                                                 ArrayRef<Expr*> Args,
1258                                                 SourceLocation LitEndLoc) {
1259  assert(Args.size() <= 2 && "too many arguments for literal operator");
1260
1261  QualType ArgTy[2];
1262  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1263    ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1264    if (ArgTy[ArgIdx]->isArrayType())
1265      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1266  }
1267
1268  DeclarationName OpName =
1269    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1270  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1271  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1272
1273  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1274  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1275                              /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1276    return ExprError();
1277
1278  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1279}
1280
1281/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1282/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1283/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1284/// multiple tokens.  However, the common case is that StringToks points to one
1285/// string.
1286///
1287ExprResult
1288Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1289                         Scope *UDLScope) {
1290  assert(NumStringToks && "Must have at least one string!");
1291
1292  StringLiteralParser Literal(StringToks, NumStringToks, PP);
1293  if (Literal.hadError)
1294    return ExprError();
1295
1296  SmallVector<SourceLocation, 4> StringTokLocs;
1297  for (unsigned i = 0; i != NumStringToks; ++i)
1298    StringTokLocs.push_back(StringToks[i].getLocation());
1299
1300  QualType StrTy = Context.CharTy;
1301  if (Literal.isWide())
1302    StrTy = Context.getWCharType();
1303  else if (Literal.isUTF16())
1304    StrTy = Context.Char16Ty;
1305  else if (Literal.isUTF32())
1306    StrTy = Context.Char32Ty;
1307  else if (Literal.isPascal())
1308    StrTy = Context.UnsignedCharTy;
1309
1310  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1311  if (Literal.isWide())
1312    Kind = StringLiteral::Wide;
1313  else if (Literal.isUTF8())
1314    Kind = StringLiteral::UTF8;
1315  else if (Literal.isUTF16())
1316    Kind = StringLiteral::UTF16;
1317  else if (Literal.isUTF32())
1318    Kind = StringLiteral::UTF32;
1319
1320  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1321  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1322    StrTy.addConst();
1323
1324  // Get an array type for the string, according to C99 6.4.5.  This includes
1325  // the nul terminator character as well as the string length for pascal
1326  // strings.
1327  StrTy = Context.getConstantArrayType(StrTy,
1328                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
1329                                       ArrayType::Normal, 0);
1330
1331  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1332  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1333                                             Kind, Literal.Pascal, StrTy,
1334                                             &StringTokLocs[0],
1335                                             StringTokLocs.size());
1336  if (Literal.getUDSuffix().empty())
1337    return Owned(Lit);
1338
1339  // We're building a user-defined literal.
1340  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1341  SourceLocation UDSuffixLoc =
1342    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1343                   Literal.getUDSuffixOffset());
1344
1345  // Make sure we're allowed user-defined literals here.
1346  if (!UDLScope)
1347    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1348
1349  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1350  //   operator "" X (str, len)
1351  QualType SizeType = Context.getSizeType();
1352  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1353  IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1354                                                  StringTokLocs[0]);
1355  Expr *Args[] = { Lit, LenArg };
1356  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1357                                        Args, StringTokLocs.back());
1358}
1359
1360ExprResult
1361Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1362                       SourceLocation Loc,
1363                       const CXXScopeSpec *SS) {
1364  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1365  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1366}
1367
1368/// BuildDeclRefExpr - Build an expression that references a
1369/// declaration that does not require a closure capture.
1370ExprResult
1371Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1372                       const DeclarationNameInfo &NameInfo,
1373                       const CXXScopeSpec *SS) {
1374  if (getLangOpts().CUDA)
1375    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1376      if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1377        CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1378                           CalleeTarget = IdentifyCUDATarget(Callee);
1379        if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1380          Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1381            << CalleeTarget << D->getIdentifier() << CallerTarget;
1382          Diag(D->getLocation(), diag::note_previous_decl)
1383            << D->getIdentifier();
1384          return ExprError();
1385        }
1386      }
1387
1388  bool refersToEnclosingScope =
1389    (CurContext != D->getDeclContext() &&
1390     D->getDeclContext()->isFunctionOrMethod());
1391
1392  DeclRefExpr *E = DeclRefExpr::Create(Context,
1393                                       SS ? SS->getWithLocInContext(Context)
1394                                              : NestedNameSpecifierLoc(),
1395                                       SourceLocation(),
1396                                       D, refersToEnclosingScope,
1397                                       NameInfo, Ty, VK);
1398
1399  MarkDeclRefReferenced(E);
1400
1401  // Just in case we're building an illegal pointer-to-member.
1402  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1403  if (FD && FD->isBitField())
1404    E->setObjectKind(OK_BitField);
1405
1406  return Owned(E);
1407}
1408
1409/// Decomposes the given name into a DeclarationNameInfo, its location, and
1410/// possibly a list of template arguments.
1411///
1412/// If this produces template arguments, it is permitted to call
1413/// DecomposeTemplateName.
1414///
1415/// This actually loses a lot of source location information for
1416/// non-standard name kinds; we should consider preserving that in
1417/// some way.
1418void
1419Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1420                             TemplateArgumentListInfo &Buffer,
1421                             DeclarationNameInfo &NameInfo,
1422                             const TemplateArgumentListInfo *&TemplateArgs) {
1423  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1424    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1425    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1426
1427    ASTTemplateArgsPtr TemplateArgsPtr(*this,
1428                                       Id.TemplateId->getTemplateArgs(),
1429                                       Id.TemplateId->NumArgs);
1430    translateTemplateArguments(TemplateArgsPtr, Buffer);
1431    TemplateArgsPtr.release();
1432
1433    TemplateName TName = Id.TemplateId->Template.get();
1434    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1435    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1436    TemplateArgs = &Buffer;
1437  } else {
1438    NameInfo = GetNameFromUnqualifiedId(Id);
1439    TemplateArgs = 0;
1440  }
1441}
1442
1443/// Diagnose an empty lookup.
1444///
1445/// \return false if new lookup candidates were found
1446bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1447                               CorrectionCandidateCallback &CCC,
1448                               TemplateArgumentListInfo *ExplicitTemplateArgs,
1449                               llvm::ArrayRef<Expr *> Args) {
1450  DeclarationName Name = R.getLookupName();
1451
1452  unsigned diagnostic = diag::err_undeclared_var_use;
1453  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1454  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1455      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1456      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1457    diagnostic = diag::err_undeclared_use;
1458    diagnostic_suggest = diag::err_undeclared_use_suggest;
1459  }
1460
1461  // If the original lookup was an unqualified lookup, fake an
1462  // unqualified lookup.  This is useful when (for example) the
1463  // original lookup would not have found something because it was a
1464  // dependent name.
1465  DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1466    ? CurContext : 0;
1467  while (DC) {
1468    if (isa<CXXRecordDecl>(DC)) {
1469      LookupQualifiedName(R, DC);
1470
1471      if (!R.empty()) {
1472        // Don't give errors about ambiguities in this lookup.
1473        R.suppressDiagnostics();
1474
1475        // During a default argument instantiation the CurContext points
1476        // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1477        // function parameter list, hence add an explicit check.
1478        bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1479                              ActiveTemplateInstantiations.back().Kind ==
1480            ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1481        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1482        bool isInstance = CurMethod &&
1483                          CurMethod->isInstance() &&
1484                          DC == CurMethod->getParent() && !isDefaultArgument;
1485
1486
1487        // Give a code modification hint to insert 'this->'.
1488        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1489        // Actually quite difficult!
1490        if (getLangOpts().MicrosoftMode)
1491          diagnostic = diag::warn_found_via_dependent_bases_lookup;
1492        if (isInstance) {
1493          Diag(R.getNameLoc(), diagnostic) << Name
1494            << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1495          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1496              CallsUndergoingInstantiation.back()->getCallee());
1497
1498
1499          CXXMethodDecl *DepMethod;
1500          if (CurMethod->getTemplatedKind() ==
1501              FunctionDecl::TK_FunctionTemplateSpecialization)
1502            DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1503                getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1504          else
1505            DepMethod = cast<CXXMethodDecl>(
1506                CurMethod->getInstantiatedFromMemberFunction());
1507          assert(DepMethod && "No template pattern found");
1508
1509          QualType DepThisType = DepMethod->getThisType(Context);
1510          CheckCXXThisCapture(R.getNameLoc());
1511          CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1512                                     R.getNameLoc(), DepThisType, false);
1513          TemplateArgumentListInfo TList;
1514          if (ULE->hasExplicitTemplateArgs())
1515            ULE->copyTemplateArgumentsInto(TList);
1516
1517          CXXScopeSpec SS;
1518          SS.Adopt(ULE->getQualifierLoc());
1519          CXXDependentScopeMemberExpr *DepExpr =
1520              CXXDependentScopeMemberExpr::Create(
1521                  Context, DepThis, DepThisType, true, SourceLocation(),
1522                  SS.getWithLocInContext(Context),
1523                  ULE->getTemplateKeywordLoc(), 0,
1524                  R.getLookupNameInfo(),
1525                  ULE->hasExplicitTemplateArgs() ? &TList : 0);
1526          CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1527        } else {
1528          Diag(R.getNameLoc(), diagnostic) << Name;
1529        }
1530
1531        // Do we really want to note all of these?
1532        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1533          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1534
1535        // Return true if we are inside a default argument instantiation
1536        // and the found name refers to an instance member function, otherwise
1537        // the function calling DiagnoseEmptyLookup will try to create an
1538        // implicit member call and this is wrong for default argument.
1539        if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1540          Diag(R.getNameLoc(), diag::err_member_call_without_object);
1541          return true;
1542        }
1543
1544        // Tell the callee to try to recover.
1545        return false;
1546      }
1547
1548      R.clear();
1549    }
1550
1551    // In Microsoft mode, if we are performing lookup from within a friend
1552    // function definition declared at class scope then we must set
1553    // DC to the lexical parent to be able to search into the parent
1554    // class.
1555    if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1556        cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1557        DC->getLexicalParent()->isRecord())
1558      DC = DC->getLexicalParent();
1559    else
1560      DC = DC->getParent();
1561  }
1562
1563  // We didn't find anything, so try to correct for a typo.
1564  TypoCorrection Corrected;
1565  if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1566                                    S, &SS, CCC))) {
1567    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1568    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1569    R.setLookupName(Corrected.getCorrection());
1570
1571    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1572      if (Corrected.isOverloaded()) {
1573        OverloadCandidateSet OCS(R.getNameLoc());
1574        OverloadCandidateSet::iterator Best;
1575        for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1576                                        CDEnd = Corrected.end();
1577             CD != CDEnd; ++CD) {
1578          if (FunctionTemplateDecl *FTD =
1579                   dyn_cast<FunctionTemplateDecl>(*CD))
1580            AddTemplateOverloadCandidate(
1581                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1582                Args, OCS);
1583          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1584            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1585              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1586                                   Args, OCS);
1587        }
1588        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1589          case OR_Success:
1590            ND = Best->Function;
1591            break;
1592          default:
1593            break;
1594        }
1595      }
1596      R.addDecl(ND);
1597      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1598        if (SS.isEmpty())
1599          Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1600            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1601        else
1602          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1603            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1604            << SS.getRange()
1605            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1606        if (ND)
1607          Diag(ND->getLocation(), diag::note_previous_decl)
1608            << CorrectedQuotedStr;
1609
1610        // Tell the callee to try to recover.
1611        return false;
1612      }
1613
1614      if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1615        // FIXME: If we ended up with a typo for a type name or
1616        // Objective-C class name, we're in trouble because the parser
1617        // is in the wrong place to recover. Suggest the typo
1618        // correction, but don't make it a fix-it since we're not going
1619        // to recover well anyway.
1620        if (SS.isEmpty())
1621          Diag(R.getNameLoc(), diagnostic_suggest)
1622            << Name << CorrectedQuotedStr;
1623        else
1624          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1625            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1626            << SS.getRange();
1627
1628        // Don't try to recover; it won't work.
1629        return true;
1630      }
1631    } else {
1632      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1633      // because we aren't able to recover.
1634      if (SS.isEmpty())
1635        Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1636      else
1637        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1638        << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1639        << SS.getRange();
1640      return true;
1641    }
1642  }
1643  R.clear();
1644
1645  // Emit a special diagnostic for failed member lookups.
1646  // FIXME: computing the declaration context might fail here (?)
1647  if (!SS.isEmpty()) {
1648    Diag(R.getNameLoc(), diag::err_no_member)
1649      << Name << computeDeclContext(SS, false)
1650      << SS.getRange();
1651    return true;
1652  }
1653
1654  // Give up, we can't recover.
1655  Diag(R.getNameLoc(), diagnostic) << Name;
1656  return true;
1657}
1658
1659ExprResult Sema::ActOnIdExpression(Scope *S,
1660                                   CXXScopeSpec &SS,
1661                                   SourceLocation TemplateKWLoc,
1662                                   UnqualifiedId &Id,
1663                                   bool HasTrailingLParen,
1664                                   bool IsAddressOfOperand,
1665                                   CorrectionCandidateCallback *CCC) {
1666  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1667         "cannot be direct & operand and have a trailing lparen");
1668
1669  if (SS.isInvalid())
1670    return ExprError();
1671
1672  TemplateArgumentListInfo TemplateArgsBuffer;
1673
1674  // Decompose the UnqualifiedId into the following data.
1675  DeclarationNameInfo NameInfo;
1676  const TemplateArgumentListInfo *TemplateArgs;
1677  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1678
1679  DeclarationName Name = NameInfo.getName();
1680  IdentifierInfo *II = Name.getAsIdentifierInfo();
1681  SourceLocation NameLoc = NameInfo.getLoc();
1682
1683  // C++ [temp.dep.expr]p3:
1684  //   An id-expression is type-dependent if it contains:
1685  //     -- an identifier that was declared with a dependent type,
1686  //        (note: handled after lookup)
1687  //     -- a template-id that is dependent,
1688  //        (note: handled in BuildTemplateIdExpr)
1689  //     -- a conversion-function-id that specifies a dependent type,
1690  //     -- a nested-name-specifier that contains a class-name that
1691  //        names a dependent type.
1692  // Determine whether this is a member of an unknown specialization;
1693  // we need to handle these differently.
1694  bool DependentID = false;
1695  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1696      Name.getCXXNameType()->isDependentType()) {
1697    DependentID = true;
1698  } else if (SS.isSet()) {
1699    if (DeclContext *DC = computeDeclContext(SS, false)) {
1700      if (RequireCompleteDeclContext(SS, DC))
1701        return ExprError();
1702    } else {
1703      DependentID = true;
1704    }
1705  }
1706
1707  if (DependentID)
1708    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1709                                      IsAddressOfOperand, TemplateArgs);
1710
1711  // Perform the required lookup.
1712  LookupResult R(*this, NameInfo,
1713                 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1714                  ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1715  if (TemplateArgs) {
1716    // Lookup the template name again to correctly establish the context in
1717    // which it was found. This is really unfortunate as we already did the
1718    // lookup to determine that it was a template name in the first place. If
1719    // this becomes a performance hit, we can work harder to preserve those
1720    // results until we get here but it's likely not worth it.
1721    bool MemberOfUnknownSpecialization;
1722    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1723                       MemberOfUnknownSpecialization);
1724
1725    if (MemberOfUnknownSpecialization ||
1726        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1727      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1728                                        IsAddressOfOperand, TemplateArgs);
1729  } else {
1730    bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1731    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1732
1733    // If the result might be in a dependent base class, this is a dependent
1734    // id-expression.
1735    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1736      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1737                                        IsAddressOfOperand, TemplateArgs);
1738
1739    // If this reference is in an Objective-C method, then we need to do
1740    // some special Objective-C lookup, too.
1741    if (IvarLookupFollowUp) {
1742      ExprResult E(LookupInObjCMethod(R, S, II, true));
1743      if (E.isInvalid())
1744        return ExprError();
1745
1746      if (Expr *Ex = E.takeAs<Expr>())
1747        return Owned(Ex);
1748    }
1749  }
1750
1751  if (R.isAmbiguous())
1752    return ExprError();
1753
1754  // Determine whether this name might be a candidate for
1755  // argument-dependent lookup.
1756  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1757
1758  if (R.empty() && !ADL) {
1759    // Otherwise, this could be an implicitly declared function reference (legal
1760    // in C90, extension in C99, forbidden in C++).
1761    if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1762      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1763      if (D) R.addDecl(D);
1764    }
1765
1766    // If this name wasn't predeclared and if this is not a function
1767    // call, diagnose the problem.
1768    if (R.empty()) {
1769
1770      // In Microsoft mode, if we are inside a template class member function
1771      // and we can't resolve an identifier then assume the identifier is type
1772      // dependent. The goal is to postpone name lookup to instantiation time
1773      // to be able to search into type dependent base classes.
1774      if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1775          isa<CXXMethodDecl>(CurContext))
1776        return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1777                                          IsAddressOfOperand, TemplateArgs);
1778
1779      CorrectionCandidateCallback DefaultValidator;
1780      if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1781        return ExprError();
1782
1783      assert(!R.empty() &&
1784             "DiagnoseEmptyLookup returned false but added no results");
1785
1786      // If we found an Objective-C instance variable, let
1787      // LookupInObjCMethod build the appropriate expression to
1788      // reference the ivar.
1789      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1790        R.clear();
1791        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1792        // In a hopelessly buggy code, Objective-C instance variable
1793        // lookup fails and no expression will be built to reference it.
1794        if (!E.isInvalid() && !E.get())
1795          return ExprError();
1796        return move(E);
1797      }
1798    }
1799  }
1800
1801  // This is guaranteed from this point on.
1802  assert(!R.empty() || ADL);
1803
1804  // Check whether this might be a C++ implicit instance member access.
1805  // C++ [class.mfct.non-static]p3:
1806  //   When an id-expression that is not part of a class member access
1807  //   syntax and not used to form a pointer to member is used in the
1808  //   body of a non-static member function of class X, if name lookup
1809  //   resolves the name in the id-expression to a non-static non-type
1810  //   member of some class C, the id-expression is transformed into a
1811  //   class member access expression using (*this) as the
1812  //   postfix-expression to the left of the . operator.
1813  //
1814  // But we don't actually need to do this for '&' operands if R
1815  // resolved to a function or overloaded function set, because the
1816  // expression is ill-formed if it actually works out to be a
1817  // non-static member function:
1818  //
1819  // C++ [expr.ref]p4:
1820  //   Otherwise, if E1.E2 refers to a non-static member function. . .
1821  //   [t]he expression can be used only as the left-hand operand of a
1822  //   member function call.
1823  //
1824  // There are other safeguards against such uses, but it's important
1825  // to get this right here so that we don't end up making a
1826  // spuriously dependent expression if we're inside a dependent
1827  // instance method.
1828  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1829    bool MightBeImplicitMember;
1830    if (!IsAddressOfOperand)
1831      MightBeImplicitMember = true;
1832    else if (!SS.isEmpty())
1833      MightBeImplicitMember = false;
1834    else if (R.isOverloadedResult())
1835      MightBeImplicitMember = false;
1836    else if (R.isUnresolvableResult())
1837      MightBeImplicitMember = true;
1838    else
1839      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1840                              isa<IndirectFieldDecl>(R.getFoundDecl());
1841
1842    if (MightBeImplicitMember)
1843      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1844                                             R, TemplateArgs);
1845  }
1846
1847  if (TemplateArgs || TemplateKWLoc.isValid())
1848    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1849
1850  return BuildDeclarationNameExpr(SS, R, ADL);
1851}
1852
1853/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1854/// declaration name, generally during template instantiation.
1855/// There's a large number of things which don't need to be done along
1856/// this path.
1857ExprResult
1858Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1859                                        const DeclarationNameInfo &NameInfo) {
1860  DeclContext *DC;
1861  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1862    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1863                                     NameInfo, /*TemplateArgs=*/0);
1864
1865  if (RequireCompleteDeclContext(SS, DC))
1866    return ExprError();
1867
1868  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1869  LookupQualifiedName(R, DC);
1870
1871  if (R.isAmbiguous())
1872    return ExprError();
1873
1874  if (R.empty()) {
1875    Diag(NameInfo.getLoc(), diag::err_no_member)
1876      << NameInfo.getName() << DC << SS.getRange();
1877    return ExprError();
1878  }
1879
1880  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1881}
1882
1883/// LookupInObjCMethod - The parser has read a name in, and Sema has
1884/// detected that we're currently inside an ObjC method.  Perform some
1885/// additional lookup.
1886///
1887/// Ideally, most of this would be done by lookup, but there's
1888/// actually quite a lot of extra work involved.
1889///
1890/// Returns a null sentinel to indicate trivial success.
1891ExprResult
1892Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1893                         IdentifierInfo *II, bool AllowBuiltinCreation) {
1894  SourceLocation Loc = Lookup.getNameLoc();
1895  ObjCMethodDecl *CurMethod = getCurMethodDecl();
1896
1897  // There are two cases to handle here.  1) scoped lookup could have failed,
1898  // in which case we should look for an ivar.  2) scoped lookup could have
1899  // found a decl, but that decl is outside the current instance method (i.e.
1900  // a global variable).  In these two cases, we do a lookup for an ivar with
1901  // this name, if the lookup sucedes, we replace it our current decl.
1902
1903  // If we're in a class method, we don't normally want to look for
1904  // ivars.  But if we don't find anything else, and there's an
1905  // ivar, that's an error.
1906  bool IsClassMethod = CurMethod->isClassMethod();
1907
1908  bool LookForIvars;
1909  if (Lookup.empty())
1910    LookForIvars = true;
1911  else if (IsClassMethod)
1912    LookForIvars = false;
1913  else
1914    LookForIvars = (Lookup.isSingleResult() &&
1915                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1916  ObjCInterfaceDecl *IFace = 0;
1917  if (LookForIvars) {
1918    IFace = CurMethod->getClassInterface();
1919    ObjCInterfaceDecl *ClassDeclared;
1920    ObjCIvarDecl *IV = 0;
1921    if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1922      // Diagnose using an ivar in a class method.
1923      if (IsClassMethod)
1924        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1925                         << IV->getDeclName());
1926
1927      // If we're referencing an invalid decl, just return this as a silent
1928      // error node.  The error diagnostic was already emitted on the decl.
1929      if (IV->isInvalidDecl())
1930        return ExprError();
1931
1932      // Check if referencing a field with __attribute__((deprecated)).
1933      if (DiagnoseUseOfDecl(IV, Loc))
1934        return ExprError();
1935
1936      // Diagnose the use of an ivar outside of the declaring class.
1937      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1938          !declaresSameEntity(ClassDeclared, IFace) &&
1939          !getLangOpts().DebuggerSupport)
1940        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1941
1942      // FIXME: This should use a new expr for a direct reference, don't
1943      // turn this into Self->ivar, just return a BareIVarExpr or something.
1944      IdentifierInfo &II = Context.Idents.get("self");
1945      UnqualifiedId SelfName;
1946      SelfName.setIdentifier(&II, SourceLocation());
1947      SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1948      CXXScopeSpec SelfScopeSpec;
1949      SourceLocation TemplateKWLoc;
1950      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
1951                                              SelfName, false, false);
1952      if (SelfExpr.isInvalid())
1953        return ExprError();
1954
1955      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1956      if (SelfExpr.isInvalid())
1957        return ExprError();
1958
1959      MarkAnyDeclReferenced(Loc, IV);
1960      return Owned(new (Context)
1961                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
1962                                   SelfExpr.take(), true, true));
1963    }
1964  } else if (CurMethod->isInstanceMethod()) {
1965    // We should warn if a local variable hides an ivar.
1966    if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1967      ObjCInterfaceDecl *ClassDeclared;
1968      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1969        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1970            declaresSameEntity(IFace, ClassDeclared))
1971          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1972      }
1973    }
1974  } else if (Lookup.isSingleResult() &&
1975             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1976    // If accessing a stand-alone ivar in a class method, this is an error.
1977    if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1978      return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1979                       << IV->getDeclName());
1980  }
1981
1982  if (Lookup.empty() && II && AllowBuiltinCreation) {
1983    // FIXME. Consolidate this with similar code in LookupName.
1984    if (unsigned BuiltinID = II->getBuiltinID()) {
1985      if (!(getLangOpts().CPlusPlus &&
1986            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1987        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1988                                           S, Lookup.isForRedeclaration(),
1989                                           Lookup.getNameLoc());
1990        if (D) Lookup.addDecl(D);
1991      }
1992    }
1993  }
1994  // Sentinel value saying that we didn't do anything special.
1995  return Owned((Expr*) 0);
1996}
1997
1998/// \brief Cast a base object to a member's actual type.
1999///
2000/// Logically this happens in three phases:
2001///
2002/// * First we cast from the base type to the naming class.
2003///   The naming class is the class into which we were looking
2004///   when we found the member;  it's the qualifier type if a
2005///   qualifier was provided, and otherwise it's the base type.
2006///
2007/// * Next we cast from the naming class to the declaring class.
2008///   If the member we found was brought into a class's scope by
2009///   a using declaration, this is that class;  otherwise it's
2010///   the class declaring the member.
2011///
2012/// * Finally we cast from the declaring class to the "true"
2013///   declaring class of the member.  This conversion does not
2014///   obey access control.
2015ExprResult
2016Sema::PerformObjectMemberConversion(Expr *From,
2017                                    NestedNameSpecifier *Qualifier,
2018                                    NamedDecl *FoundDecl,
2019                                    NamedDecl *Member) {
2020  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2021  if (!RD)
2022    return Owned(From);
2023
2024  QualType DestRecordType;
2025  QualType DestType;
2026  QualType FromRecordType;
2027  QualType FromType = From->getType();
2028  bool PointerConversions = false;
2029  if (isa<FieldDecl>(Member)) {
2030    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2031
2032    if (FromType->getAs<PointerType>()) {
2033      DestType = Context.getPointerType(DestRecordType);
2034      FromRecordType = FromType->getPointeeType();
2035      PointerConversions = true;
2036    } else {
2037      DestType = DestRecordType;
2038      FromRecordType = FromType;
2039    }
2040  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2041    if (Method->isStatic())
2042      return Owned(From);
2043
2044    DestType = Method->getThisType(Context);
2045    DestRecordType = DestType->getPointeeType();
2046
2047    if (FromType->getAs<PointerType>()) {
2048      FromRecordType = FromType->getPointeeType();
2049      PointerConversions = true;
2050    } else {
2051      FromRecordType = FromType;
2052      DestType = DestRecordType;
2053    }
2054  } else {
2055    // No conversion necessary.
2056    return Owned(From);
2057  }
2058
2059  if (DestType->isDependentType() || FromType->isDependentType())
2060    return Owned(From);
2061
2062  // If the unqualified types are the same, no conversion is necessary.
2063  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2064    return Owned(From);
2065
2066  SourceRange FromRange = From->getSourceRange();
2067  SourceLocation FromLoc = FromRange.getBegin();
2068
2069  ExprValueKind VK = From->getValueKind();
2070
2071  // C++ [class.member.lookup]p8:
2072  //   [...] Ambiguities can often be resolved by qualifying a name with its
2073  //   class name.
2074  //
2075  // If the member was a qualified name and the qualified referred to a
2076  // specific base subobject type, we'll cast to that intermediate type
2077  // first and then to the object in which the member is declared. That allows
2078  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2079  //
2080  //   class Base { public: int x; };
2081  //   class Derived1 : public Base { };
2082  //   class Derived2 : public Base { };
2083  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2084  //
2085  //   void VeryDerived::f() {
2086  //     x = 17; // error: ambiguous base subobjects
2087  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2088  //   }
2089  if (Qualifier) {
2090    QualType QType = QualType(Qualifier->getAsType(), 0);
2091    assert(!QType.isNull() && "lookup done with dependent qualifier?");
2092    assert(QType->isRecordType() && "lookup done with non-record type");
2093
2094    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2095
2096    // In C++98, the qualifier type doesn't actually have to be a base
2097    // type of the object type, in which case we just ignore it.
2098    // Otherwise build the appropriate casts.
2099    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2100      CXXCastPath BasePath;
2101      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2102                                       FromLoc, FromRange, &BasePath))
2103        return ExprError();
2104
2105      if (PointerConversions)
2106        QType = Context.getPointerType(QType);
2107      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2108                               VK, &BasePath).take();
2109
2110      FromType = QType;
2111      FromRecordType = QRecordType;
2112
2113      // If the qualifier type was the same as the destination type,
2114      // we're done.
2115      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2116        return Owned(From);
2117    }
2118  }
2119
2120  bool IgnoreAccess = false;
2121
2122  // If we actually found the member through a using declaration, cast
2123  // down to the using declaration's type.
2124  //
2125  // Pointer equality is fine here because only one declaration of a
2126  // class ever has member declarations.
2127  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2128    assert(isa<UsingShadowDecl>(FoundDecl));
2129    QualType URecordType = Context.getTypeDeclType(
2130                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2131
2132    // We only need to do this if the naming-class to declaring-class
2133    // conversion is non-trivial.
2134    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2135      assert(IsDerivedFrom(FromRecordType, URecordType));
2136      CXXCastPath BasePath;
2137      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2138                                       FromLoc, FromRange, &BasePath))
2139        return ExprError();
2140
2141      QualType UType = URecordType;
2142      if (PointerConversions)
2143        UType = Context.getPointerType(UType);
2144      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2145                               VK, &BasePath).take();
2146      FromType = UType;
2147      FromRecordType = URecordType;
2148    }
2149
2150    // We don't do access control for the conversion from the
2151    // declaring class to the true declaring class.
2152    IgnoreAccess = true;
2153  }
2154
2155  CXXCastPath BasePath;
2156  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2157                                   FromLoc, FromRange, &BasePath,
2158                                   IgnoreAccess))
2159    return ExprError();
2160
2161  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2162                           VK, &BasePath);
2163}
2164
2165bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2166                                      const LookupResult &R,
2167                                      bool HasTrailingLParen) {
2168  // Only when used directly as the postfix-expression of a call.
2169  if (!HasTrailingLParen)
2170    return false;
2171
2172  // Never if a scope specifier was provided.
2173  if (SS.isSet())
2174    return false;
2175
2176  // Only in C++ or ObjC++.
2177  if (!getLangOpts().CPlusPlus)
2178    return false;
2179
2180  // Turn off ADL when we find certain kinds of declarations during
2181  // normal lookup:
2182  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2183    NamedDecl *D = *I;
2184
2185    // C++0x [basic.lookup.argdep]p3:
2186    //     -- a declaration of a class member
2187    // Since using decls preserve this property, we check this on the
2188    // original decl.
2189    if (D->isCXXClassMember())
2190      return false;
2191
2192    // C++0x [basic.lookup.argdep]p3:
2193    //     -- a block-scope function declaration that is not a
2194    //        using-declaration
2195    // NOTE: we also trigger this for function templates (in fact, we
2196    // don't check the decl type at all, since all other decl types
2197    // turn off ADL anyway).
2198    if (isa<UsingShadowDecl>(D))
2199      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2200    else if (D->getDeclContext()->isFunctionOrMethod())
2201      return false;
2202
2203    // C++0x [basic.lookup.argdep]p3:
2204    //     -- a declaration that is neither a function or a function
2205    //        template
2206    // And also for builtin functions.
2207    if (isa<FunctionDecl>(D)) {
2208      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2209
2210      // But also builtin functions.
2211      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2212        return false;
2213    } else if (!isa<FunctionTemplateDecl>(D))
2214      return false;
2215  }
2216
2217  return true;
2218}
2219
2220
2221/// Diagnoses obvious problems with the use of the given declaration
2222/// as an expression.  This is only actually called for lookups that
2223/// were not overloaded, and it doesn't promise that the declaration
2224/// will in fact be used.
2225static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2226  if (isa<TypedefNameDecl>(D)) {
2227    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2228    return true;
2229  }
2230
2231  if (isa<ObjCInterfaceDecl>(D)) {
2232    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2233    return true;
2234  }
2235
2236  if (isa<NamespaceDecl>(D)) {
2237    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2238    return true;
2239  }
2240
2241  return false;
2242}
2243
2244ExprResult
2245Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2246                               LookupResult &R,
2247                               bool NeedsADL) {
2248  // If this is a single, fully-resolved result and we don't need ADL,
2249  // just build an ordinary singleton decl ref.
2250  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2251    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2252                                    R.getFoundDecl());
2253
2254  // We only need to check the declaration if there's exactly one
2255  // result, because in the overloaded case the results can only be
2256  // functions and function templates.
2257  if (R.isSingleResult() &&
2258      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2259    return ExprError();
2260
2261  // Otherwise, just build an unresolved lookup expression.  Suppress
2262  // any lookup-related diagnostics; we'll hash these out later, when
2263  // we've picked a target.
2264  R.suppressDiagnostics();
2265
2266  UnresolvedLookupExpr *ULE
2267    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2268                                   SS.getWithLocInContext(Context),
2269                                   R.getLookupNameInfo(),
2270                                   NeedsADL, R.isOverloadedResult(),
2271                                   R.begin(), R.end());
2272
2273  return Owned(ULE);
2274}
2275
2276/// \brief Complete semantic analysis for a reference to the given declaration.
2277ExprResult
2278Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2279                               const DeclarationNameInfo &NameInfo,
2280                               NamedDecl *D) {
2281  assert(D && "Cannot refer to a NULL declaration");
2282  assert(!isa<FunctionTemplateDecl>(D) &&
2283         "Cannot refer unambiguously to a function template");
2284
2285  SourceLocation Loc = NameInfo.getLoc();
2286  if (CheckDeclInExpr(*this, Loc, D))
2287    return ExprError();
2288
2289  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2290    // Specifically diagnose references to class templates that are missing
2291    // a template argument list.
2292    Diag(Loc, diag::err_template_decl_ref)
2293      << Template << SS.getRange();
2294    Diag(Template->getLocation(), diag::note_template_decl_here);
2295    return ExprError();
2296  }
2297
2298  // Make sure that we're referring to a value.
2299  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2300  if (!VD) {
2301    Diag(Loc, diag::err_ref_non_value)
2302      << D << SS.getRange();
2303    Diag(D->getLocation(), diag::note_declared_at);
2304    return ExprError();
2305  }
2306
2307  // Check whether this declaration can be used. Note that we suppress
2308  // this check when we're going to perform argument-dependent lookup
2309  // on this function name, because this might not be the function
2310  // that overload resolution actually selects.
2311  if (DiagnoseUseOfDecl(VD, Loc))
2312    return ExprError();
2313
2314  // Only create DeclRefExpr's for valid Decl's.
2315  if (VD->isInvalidDecl())
2316    return ExprError();
2317
2318  // Handle members of anonymous structs and unions.  If we got here,
2319  // and the reference is to a class member indirect field, then this
2320  // must be the subject of a pointer-to-member expression.
2321  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2322    if (!indirectField->isCXXClassMember())
2323      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2324                                                      indirectField);
2325
2326  {
2327    QualType type = VD->getType();
2328    ExprValueKind valueKind = VK_RValue;
2329
2330    switch (D->getKind()) {
2331    // Ignore all the non-ValueDecl kinds.
2332#define ABSTRACT_DECL(kind)
2333#define VALUE(type, base)
2334#define DECL(type, base) \
2335    case Decl::type:
2336#include "clang/AST/DeclNodes.inc"
2337      llvm_unreachable("invalid value decl kind");
2338
2339    // These shouldn't make it here.
2340    case Decl::ObjCAtDefsField:
2341    case Decl::ObjCIvar:
2342      llvm_unreachable("forming non-member reference to ivar?");
2343
2344    // Enum constants are always r-values and never references.
2345    // Unresolved using declarations are dependent.
2346    case Decl::EnumConstant:
2347    case Decl::UnresolvedUsingValue:
2348      valueKind = VK_RValue;
2349      break;
2350
2351    // Fields and indirect fields that got here must be for
2352    // pointer-to-member expressions; we just call them l-values for
2353    // internal consistency, because this subexpression doesn't really
2354    // exist in the high-level semantics.
2355    case Decl::Field:
2356    case Decl::IndirectField:
2357      assert(getLangOpts().CPlusPlus &&
2358             "building reference to field in C?");
2359
2360      // These can't have reference type in well-formed programs, but
2361      // for internal consistency we do this anyway.
2362      type = type.getNonReferenceType();
2363      valueKind = VK_LValue;
2364      break;
2365
2366    // Non-type template parameters are either l-values or r-values
2367    // depending on the type.
2368    case Decl::NonTypeTemplateParm: {
2369      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2370        type = reftype->getPointeeType();
2371        valueKind = VK_LValue; // even if the parameter is an r-value reference
2372        break;
2373      }
2374
2375      // For non-references, we need to strip qualifiers just in case
2376      // the template parameter was declared as 'const int' or whatever.
2377      valueKind = VK_RValue;
2378      type = type.getUnqualifiedType();
2379      break;
2380    }
2381
2382    case Decl::Var:
2383      // In C, "extern void blah;" is valid and is an r-value.
2384      if (!getLangOpts().CPlusPlus &&
2385          !type.hasQualifiers() &&
2386          type->isVoidType()) {
2387        valueKind = VK_RValue;
2388        break;
2389      }
2390      // fallthrough
2391
2392    case Decl::ImplicitParam:
2393    case Decl::ParmVar: {
2394      // These are always l-values.
2395      valueKind = VK_LValue;
2396      type = type.getNonReferenceType();
2397
2398      // FIXME: Does the addition of const really only apply in
2399      // potentially-evaluated contexts? Since the variable isn't actually
2400      // captured in an unevaluated context, it seems that the answer is no.
2401      if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2402        QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2403        if (!CapturedType.isNull())
2404          type = CapturedType;
2405      }
2406
2407      break;
2408    }
2409
2410    case Decl::Function: {
2411      const FunctionType *fty = type->castAs<FunctionType>();
2412
2413      // If we're referring to a function with an __unknown_anytype
2414      // result type, make the entire expression __unknown_anytype.
2415      if (fty->getResultType() == Context.UnknownAnyTy) {
2416        type = Context.UnknownAnyTy;
2417        valueKind = VK_RValue;
2418        break;
2419      }
2420
2421      // Functions are l-values in C++.
2422      if (getLangOpts().CPlusPlus) {
2423        valueKind = VK_LValue;
2424        break;
2425      }
2426
2427      // C99 DR 316 says that, if a function type comes from a
2428      // function definition (without a prototype), that type is only
2429      // used for checking compatibility. Therefore, when referencing
2430      // the function, we pretend that we don't have the full function
2431      // type.
2432      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2433          isa<FunctionProtoType>(fty))
2434        type = Context.getFunctionNoProtoType(fty->getResultType(),
2435                                              fty->getExtInfo());
2436
2437      // Functions are r-values in C.
2438      valueKind = VK_RValue;
2439      break;
2440    }
2441
2442    case Decl::CXXMethod:
2443      // If we're referring to a method with an __unknown_anytype
2444      // result type, make the entire expression __unknown_anytype.
2445      // This should only be possible with a type written directly.
2446      if (const FunctionProtoType *proto
2447            = dyn_cast<FunctionProtoType>(VD->getType()))
2448        if (proto->getResultType() == Context.UnknownAnyTy) {
2449          type = Context.UnknownAnyTy;
2450          valueKind = VK_RValue;
2451          break;
2452        }
2453
2454      // C++ methods are l-values if static, r-values if non-static.
2455      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2456        valueKind = VK_LValue;
2457        break;
2458      }
2459      // fallthrough
2460
2461    case Decl::CXXConversion:
2462    case Decl::CXXDestructor:
2463    case Decl::CXXConstructor:
2464      valueKind = VK_RValue;
2465      break;
2466    }
2467
2468    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2469  }
2470}
2471
2472ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2473  PredefinedExpr::IdentType IT;
2474
2475  switch (Kind) {
2476  default: llvm_unreachable("Unknown simple primary expr!");
2477  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2478  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2479  case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2480  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2481  }
2482
2483  // Pre-defined identifiers are of type char[x], where x is the length of the
2484  // string.
2485
2486  Decl *currentDecl = getCurFunctionOrMethodDecl();
2487  if (!currentDecl && getCurBlock())
2488    currentDecl = getCurBlock()->TheDecl;
2489  if (!currentDecl) {
2490    Diag(Loc, diag::ext_predef_outside_function);
2491    currentDecl = Context.getTranslationUnitDecl();
2492  }
2493
2494  QualType ResTy;
2495  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2496    ResTy = Context.DependentTy;
2497  } else {
2498    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2499
2500    llvm::APInt LengthI(32, Length + 1);
2501    if (Kind == tok::kw_L__FUNCTION__)
2502      ResTy = Context.WCharTy.withConst();
2503    else
2504      ResTy = Context.CharTy.withConst();
2505    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2506  }
2507  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2508}
2509
2510ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2511  SmallString<16> CharBuffer;
2512  bool Invalid = false;
2513  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2514  if (Invalid)
2515    return ExprError();
2516
2517  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2518                            PP, Tok.getKind());
2519  if (Literal.hadError())
2520    return ExprError();
2521
2522  QualType Ty;
2523  if (Literal.isWide())
2524    Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2525  else if (Literal.isUTF16())
2526    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2527  else if (Literal.isUTF32())
2528    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2529  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2530    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2531  else
2532    Ty = Context.CharTy;  // 'x' -> char in C++
2533
2534  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2535  if (Literal.isWide())
2536    Kind = CharacterLiteral::Wide;
2537  else if (Literal.isUTF16())
2538    Kind = CharacterLiteral::UTF16;
2539  else if (Literal.isUTF32())
2540    Kind = CharacterLiteral::UTF32;
2541
2542  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2543                                             Tok.getLocation());
2544
2545  if (Literal.getUDSuffix().empty())
2546    return Owned(Lit);
2547
2548  // We're building a user-defined literal.
2549  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2550  SourceLocation UDSuffixLoc =
2551    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2552
2553  // Make sure we're allowed user-defined literals here.
2554  if (!UDLScope)
2555    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2556
2557  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2558  //   operator "" X (ch)
2559  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2560                                        llvm::makeArrayRef(&Lit, 1),
2561                                        Tok.getLocation());
2562}
2563
2564ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2565  unsigned IntSize = Context.getTargetInfo().getIntWidth();
2566  return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2567                                      Context.IntTy, Loc));
2568}
2569
2570static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2571                                  QualType Ty, SourceLocation Loc) {
2572  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2573
2574  using llvm::APFloat;
2575  APFloat Val(Format);
2576
2577  APFloat::opStatus result = Literal.GetFloatValue(Val);
2578
2579  // Overflow is always an error, but underflow is only an error if
2580  // we underflowed to zero (APFloat reports denormals as underflow).
2581  if ((result & APFloat::opOverflow) ||
2582      ((result & APFloat::opUnderflow) && Val.isZero())) {
2583    unsigned diagnostic;
2584    SmallString<20> buffer;
2585    if (result & APFloat::opOverflow) {
2586      diagnostic = diag::warn_float_overflow;
2587      APFloat::getLargest(Format).toString(buffer);
2588    } else {
2589      diagnostic = diag::warn_float_underflow;
2590      APFloat::getSmallest(Format).toString(buffer);
2591    }
2592
2593    S.Diag(Loc, diagnostic)
2594      << Ty
2595      << StringRef(buffer.data(), buffer.size());
2596  }
2597
2598  bool isExact = (result == APFloat::opOK);
2599  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2600}
2601
2602ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2603  // Fast path for a single digit (which is quite common).  A single digit
2604  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2605  if (Tok.getLength() == 1) {
2606    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2607    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2608  }
2609
2610  SmallString<512> IntegerBuffer;
2611  // Add padding so that NumericLiteralParser can overread by one character.
2612  IntegerBuffer.resize(Tok.getLength()+1);
2613  const char *ThisTokBegin = &IntegerBuffer[0];
2614
2615  // Get the spelling of the token, which eliminates trigraphs, etc.
2616  bool Invalid = false;
2617  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2618  if (Invalid)
2619    return ExprError();
2620
2621  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2622                               Tok.getLocation(), PP);
2623  if (Literal.hadError)
2624    return ExprError();
2625
2626  if (Literal.hasUDSuffix()) {
2627    // We're building a user-defined literal.
2628    IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2629    SourceLocation UDSuffixLoc =
2630      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2631
2632    // Make sure we're allowed user-defined literals here.
2633    if (!UDLScope)
2634      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2635
2636    QualType CookedTy;
2637    if (Literal.isFloatingLiteral()) {
2638      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2639      // long double, the literal is treated as a call of the form
2640      //   operator "" X (f L)
2641      CookedTy = Context.LongDoubleTy;
2642    } else {
2643      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2644      // unsigned long long, the literal is treated as a call of the form
2645      //   operator "" X (n ULL)
2646      CookedTy = Context.UnsignedLongLongTy;
2647    }
2648
2649    DeclarationName OpName =
2650      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2651    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2652    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2653
2654    // Perform literal operator lookup to determine if we're building a raw
2655    // literal or a cooked one.
2656    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2657    switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2658                                  /*AllowRawAndTemplate*/true)) {
2659    case LOLR_Error:
2660      return ExprError();
2661
2662    case LOLR_Cooked: {
2663      Expr *Lit;
2664      if (Literal.isFloatingLiteral()) {
2665        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2666      } else {
2667        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2668        if (Literal.GetIntegerValue(ResultVal))
2669          Diag(Tok.getLocation(), diag::warn_integer_too_large);
2670        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2671                                     Tok.getLocation());
2672      }
2673      return BuildLiteralOperatorCall(R, OpNameInfo,
2674                                      llvm::makeArrayRef(&Lit, 1),
2675                                      Tok.getLocation());
2676    }
2677
2678    case LOLR_Raw: {
2679      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2680      // literal is treated as a call of the form
2681      //   operator "" X ("n")
2682      SourceLocation TokLoc = Tok.getLocation();
2683      unsigned Length = Literal.getUDSuffixOffset();
2684      QualType StrTy = Context.getConstantArrayType(
2685          Context.CharTy, llvm::APInt(32, Length + 1),
2686          ArrayType::Normal, 0);
2687      Expr *Lit = StringLiteral::Create(
2688          Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2689          /*Pascal*/false, StrTy, &TokLoc, 1);
2690      return BuildLiteralOperatorCall(R, OpNameInfo,
2691                                      llvm::makeArrayRef(&Lit, 1), TokLoc);
2692    }
2693
2694    case LOLR_Template:
2695      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2696      // template), L is treated as a call fo the form
2697      //   operator "" X <'c1', 'c2', ... 'ck'>()
2698      // where n is the source character sequence c1 c2 ... ck.
2699      TemplateArgumentListInfo ExplicitArgs;
2700      unsigned CharBits = Context.getIntWidth(Context.CharTy);
2701      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2702      llvm::APSInt Value(CharBits, CharIsUnsigned);
2703      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2704        Value = ThisTokBegin[I];
2705        TemplateArgument Arg(Context, Value, Context.CharTy);
2706        TemplateArgumentLocInfo ArgInfo;
2707        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2708      }
2709      return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2710                                      Tok.getLocation(), &ExplicitArgs);
2711    }
2712
2713    llvm_unreachable("unexpected literal operator lookup result");
2714  }
2715
2716  Expr *Res;
2717
2718  if (Literal.isFloatingLiteral()) {
2719    QualType Ty;
2720    if (Literal.isFloat)
2721      Ty = Context.FloatTy;
2722    else if (!Literal.isLong)
2723      Ty = Context.DoubleTy;
2724    else
2725      Ty = Context.LongDoubleTy;
2726
2727    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2728
2729    if (Ty == Context.DoubleTy) {
2730      if (getLangOpts().SinglePrecisionConstants) {
2731        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2732      } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2733        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2734        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2735      }
2736    }
2737  } else if (!Literal.isIntegerLiteral()) {
2738    return ExprError();
2739  } else {
2740    QualType Ty;
2741
2742    // long long is a C99 feature.
2743    if (!getLangOpts().C99 && Literal.isLongLong)
2744      Diag(Tok.getLocation(),
2745           getLangOpts().CPlusPlus0x ?
2746             diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2747
2748    // Get the value in the widest-possible width.
2749    unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2750    // The microsoft literal suffix extensions support 128-bit literals, which
2751    // may be wider than [u]intmax_t.
2752    if (Literal.isMicrosoftInteger && MaxWidth < 128)
2753      MaxWidth = 128;
2754    llvm::APInt ResultVal(MaxWidth, 0);
2755
2756    if (Literal.GetIntegerValue(ResultVal)) {
2757      // If this value didn't fit into uintmax_t, warn and force to ull.
2758      Diag(Tok.getLocation(), diag::warn_integer_too_large);
2759      Ty = Context.UnsignedLongLongTy;
2760      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2761             "long long is not intmax_t?");
2762    } else {
2763      // If this value fits into a ULL, try to figure out what else it fits into
2764      // according to the rules of C99 6.4.4.1p5.
2765
2766      // Octal, Hexadecimal, and integers with a U suffix are allowed to
2767      // be an unsigned int.
2768      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2769
2770      // Check from smallest to largest, picking the smallest type we can.
2771      unsigned Width = 0;
2772      if (!Literal.isLong && !Literal.isLongLong) {
2773        // Are int/unsigned possibilities?
2774        unsigned IntSize = Context.getTargetInfo().getIntWidth();
2775
2776        // Does it fit in a unsigned int?
2777        if (ResultVal.isIntN(IntSize)) {
2778          // Does it fit in a signed int?
2779          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2780            Ty = Context.IntTy;
2781          else if (AllowUnsigned)
2782            Ty = Context.UnsignedIntTy;
2783          Width = IntSize;
2784        }
2785      }
2786
2787      // Are long/unsigned long possibilities?
2788      if (Ty.isNull() && !Literal.isLongLong) {
2789        unsigned LongSize = Context.getTargetInfo().getLongWidth();
2790
2791        // Does it fit in a unsigned long?
2792        if (ResultVal.isIntN(LongSize)) {
2793          // Does it fit in a signed long?
2794          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2795            Ty = Context.LongTy;
2796          else if (AllowUnsigned)
2797            Ty = Context.UnsignedLongTy;
2798          Width = LongSize;
2799        }
2800      }
2801
2802      // Check long long if needed.
2803      if (Ty.isNull()) {
2804        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2805
2806        // Does it fit in a unsigned long long?
2807        if (ResultVal.isIntN(LongLongSize)) {
2808          // Does it fit in a signed long long?
2809          // To be compatible with MSVC, hex integer literals ending with the
2810          // LL or i64 suffix are always signed in Microsoft mode.
2811          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2812              (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2813            Ty = Context.LongLongTy;
2814          else if (AllowUnsigned)
2815            Ty = Context.UnsignedLongLongTy;
2816          Width = LongLongSize;
2817        }
2818      }
2819
2820      // If it doesn't fit in unsigned long long, and we're using Microsoft
2821      // extensions, then its a 128-bit integer literal.
2822      if (Ty.isNull() && Literal.isMicrosoftInteger) {
2823        if (Literal.isUnsigned)
2824          Ty = Context.UnsignedInt128Ty;
2825        else
2826          Ty = Context.Int128Ty;
2827        Width = 128;
2828      }
2829
2830      // If we still couldn't decide a type, we probably have something that
2831      // does not fit in a signed long long, but has no U suffix.
2832      if (Ty.isNull()) {
2833        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2834        Ty = Context.UnsignedLongLongTy;
2835        Width = Context.getTargetInfo().getLongLongWidth();
2836      }
2837
2838      if (ResultVal.getBitWidth() != Width)
2839        ResultVal = ResultVal.trunc(Width);
2840    }
2841    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2842  }
2843
2844  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2845  if (Literal.isImaginary)
2846    Res = new (Context) ImaginaryLiteral(Res,
2847                                        Context.getComplexType(Res->getType()));
2848
2849  return Owned(Res);
2850}
2851
2852ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2853  assert((E != 0) && "ActOnParenExpr() missing expr");
2854  return Owned(new (Context) ParenExpr(L, R, E));
2855}
2856
2857static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2858                                         SourceLocation Loc,
2859                                         SourceRange ArgRange) {
2860  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2861  // scalar or vector data type argument..."
2862  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2863  // type (C99 6.2.5p18) or void.
2864  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2865    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2866      << T << ArgRange;
2867    return true;
2868  }
2869
2870  assert((T->isVoidType() || !T->isIncompleteType()) &&
2871         "Scalar types should always be complete");
2872  return false;
2873}
2874
2875static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2876                                           SourceLocation Loc,
2877                                           SourceRange ArgRange,
2878                                           UnaryExprOrTypeTrait TraitKind) {
2879  // C99 6.5.3.4p1:
2880  if (T->isFunctionType()) {
2881    // alignof(function) is allowed as an extension.
2882    if (TraitKind == UETT_SizeOf)
2883      S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2884    return false;
2885  }
2886
2887  // Allow sizeof(void)/alignof(void) as an extension.
2888  if (T->isVoidType()) {
2889    S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2890    return false;
2891  }
2892
2893  return true;
2894}
2895
2896static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2897                                             SourceLocation Loc,
2898                                             SourceRange ArgRange,
2899                                             UnaryExprOrTypeTrait TraitKind) {
2900  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2901  if (S.LangOpts.ObjCRuntime.isNonFragile() && T->isObjCObjectType()) {
2902    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2903      << T << (TraitKind == UETT_SizeOf)
2904      << ArgRange;
2905    return true;
2906  }
2907
2908  return false;
2909}
2910
2911/// \brief Check the constrains on expression operands to unary type expression
2912/// and type traits.
2913///
2914/// Completes any types necessary and validates the constraints on the operand
2915/// expression. The logic mostly mirrors the type-based overload, but may modify
2916/// the expression as it completes the type for that expression through template
2917/// instantiation, etc.
2918bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2919                                            UnaryExprOrTypeTrait ExprKind) {
2920  QualType ExprTy = E->getType();
2921
2922  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2923  //   the result is the size of the referenced type."
2924  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2925  //   result shall be the alignment of the referenced type."
2926  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2927    ExprTy = Ref->getPointeeType();
2928
2929  if (ExprKind == UETT_VecStep)
2930    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2931                                        E->getSourceRange());
2932
2933  // Whitelist some types as extensions
2934  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2935                                      E->getSourceRange(), ExprKind))
2936    return false;
2937
2938  if (RequireCompleteExprType(E,
2939                              diag::err_sizeof_alignof_incomplete_type,
2940                              ExprKind, E->getSourceRange()))
2941    return true;
2942
2943  // Completeing the expression's type may have changed it.
2944  ExprTy = E->getType();
2945  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2946    ExprTy = Ref->getPointeeType();
2947
2948  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2949                                       E->getSourceRange(), ExprKind))
2950    return true;
2951
2952  if (ExprKind == UETT_SizeOf) {
2953    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2954      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2955        QualType OType = PVD->getOriginalType();
2956        QualType Type = PVD->getType();
2957        if (Type->isPointerType() && OType->isArrayType()) {
2958          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2959            << Type << OType;
2960          Diag(PVD->getLocation(), diag::note_declared_at);
2961        }
2962      }
2963    }
2964  }
2965
2966  return false;
2967}
2968
2969/// \brief Check the constraints on operands to unary expression and type
2970/// traits.
2971///
2972/// This will complete any types necessary, and validate the various constraints
2973/// on those operands.
2974///
2975/// The UsualUnaryConversions() function is *not* called by this routine.
2976/// C99 6.3.2.1p[2-4] all state:
2977///   Except when it is the operand of the sizeof operator ...
2978///
2979/// C++ [expr.sizeof]p4
2980///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2981///   standard conversions are not applied to the operand of sizeof.
2982///
2983/// This policy is followed for all of the unary trait expressions.
2984bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2985                                            SourceLocation OpLoc,
2986                                            SourceRange ExprRange,
2987                                            UnaryExprOrTypeTrait ExprKind) {
2988  if (ExprType->isDependentType())
2989    return false;
2990
2991  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2992  //   the result is the size of the referenced type."
2993  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2994  //   result shall be the alignment of the referenced type."
2995  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2996    ExprType = Ref->getPointeeType();
2997
2998  if (ExprKind == UETT_VecStep)
2999    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3000
3001  // Whitelist some types as extensions
3002  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3003                                      ExprKind))
3004    return false;
3005
3006  if (RequireCompleteType(OpLoc, ExprType,
3007                          diag::err_sizeof_alignof_incomplete_type,
3008                          ExprKind, ExprRange))
3009    return true;
3010
3011  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3012                                       ExprKind))
3013    return true;
3014
3015  return false;
3016}
3017
3018static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3019  E = E->IgnoreParens();
3020
3021  // alignof decl is always ok.
3022  if (isa<DeclRefExpr>(E))
3023    return false;
3024
3025  // Cannot know anything else if the expression is dependent.
3026  if (E->isTypeDependent())
3027    return false;
3028
3029  if (E->getBitField()) {
3030    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3031       << 1 << E->getSourceRange();
3032    return true;
3033  }
3034
3035  // Alignment of a field access is always okay, so long as it isn't a
3036  // bit-field.
3037  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3038    if (isa<FieldDecl>(ME->getMemberDecl()))
3039      return false;
3040
3041  return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3042}
3043
3044bool Sema::CheckVecStepExpr(Expr *E) {
3045  E = E->IgnoreParens();
3046
3047  // Cannot know anything else if the expression is dependent.
3048  if (E->isTypeDependent())
3049    return false;
3050
3051  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3052}
3053
3054/// \brief Build a sizeof or alignof expression given a type operand.
3055ExprResult
3056Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3057                                     SourceLocation OpLoc,
3058                                     UnaryExprOrTypeTrait ExprKind,
3059                                     SourceRange R) {
3060  if (!TInfo)
3061    return ExprError();
3062
3063  QualType T = TInfo->getType();
3064
3065  if (!T->isDependentType() &&
3066      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3067    return ExprError();
3068
3069  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3070  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3071                                                      Context.getSizeType(),
3072                                                      OpLoc, R.getEnd()));
3073}
3074
3075/// \brief Build a sizeof or alignof expression given an expression
3076/// operand.
3077ExprResult
3078Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3079                                     UnaryExprOrTypeTrait ExprKind) {
3080  ExprResult PE = CheckPlaceholderExpr(E);
3081  if (PE.isInvalid())
3082    return ExprError();
3083
3084  E = PE.get();
3085
3086  // Verify that the operand is valid.
3087  bool isInvalid = false;
3088  if (E->isTypeDependent()) {
3089    // Delay type-checking for type-dependent expressions.
3090  } else if (ExprKind == UETT_AlignOf) {
3091    isInvalid = CheckAlignOfExpr(*this, E);
3092  } else if (ExprKind == UETT_VecStep) {
3093    isInvalid = CheckVecStepExpr(E);
3094  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3095    Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3096    isInvalid = true;
3097  } else {
3098    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3099  }
3100
3101  if (isInvalid)
3102    return ExprError();
3103
3104  if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3105    PE = TranformToPotentiallyEvaluated(E);
3106    if (PE.isInvalid()) return ExprError();
3107    E = PE.take();
3108  }
3109
3110  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3111  return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3112      ExprKind, E, Context.getSizeType(), OpLoc,
3113      E->getSourceRange().getEnd()));
3114}
3115
3116/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3117/// expr and the same for @c alignof and @c __alignof
3118/// Note that the ArgRange is invalid if isType is false.
3119ExprResult
3120Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3121                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
3122                                    void *TyOrEx, const SourceRange &ArgRange) {
3123  // If error parsing type, ignore.
3124  if (TyOrEx == 0) return ExprError();
3125
3126  if (IsType) {
3127    TypeSourceInfo *TInfo;
3128    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3129    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3130  }
3131
3132  Expr *ArgEx = (Expr *)TyOrEx;
3133  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3134  return move(Result);
3135}
3136
3137static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3138                                     bool IsReal) {
3139  if (V.get()->isTypeDependent())
3140    return S.Context.DependentTy;
3141
3142  // _Real and _Imag are only l-values for normal l-values.
3143  if (V.get()->getObjectKind() != OK_Ordinary) {
3144    V = S.DefaultLvalueConversion(V.take());
3145    if (V.isInvalid())
3146      return QualType();
3147  }
3148
3149  // These operators return the element type of a complex type.
3150  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3151    return CT->getElementType();
3152
3153  // Otherwise they pass through real integer and floating point types here.
3154  if (V.get()->getType()->isArithmeticType())
3155    return V.get()->getType();
3156
3157  // Test for placeholders.
3158  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3159  if (PR.isInvalid()) return QualType();
3160  if (PR.get() != V.get()) {
3161    V = move(PR);
3162    return CheckRealImagOperand(S, V, Loc, IsReal);
3163  }
3164
3165  // Reject anything else.
3166  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3167    << (IsReal ? "__real" : "__imag");
3168  return QualType();
3169}
3170
3171
3172
3173ExprResult
3174Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3175                          tok::TokenKind Kind, Expr *Input) {
3176  UnaryOperatorKind Opc;
3177  switch (Kind) {
3178  default: llvm_unreachable("Unknown unary op!");
3179  case tok::plusplus:   Opc = UO_PostInc; break;
3180  case tok::minusminus: Opc = UO_PostDec; break;
3181  }
3182
3183  // Since this might is a postfix expression, get rid of ParenListExprs.
3184  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3185  if (Result.isInvalid()) return ExprError();
3186  Input = Result.take();
3187
3188  return BuildUnaryOp(S, OpLoc, Opc, Input);
3189}
3190
3191ExprResult
3192Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3193                              Expr *Idx, SourceLocation RLoc) {
3194  // Since this might be a postfix expression, get rid of ParenListExprs.
3195  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3196  if (Result.isInvalid()) return ExprError();
3197  Base = Result.take();
3198
3199  Expr *LHSExp = Base, *RHSExp = Idx;
3200
3201  if (getLangOpts().CPlusPlus &&
3202      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3203    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3204                                                  Context.DependentTy,
3205                                                  VK_LValue, OK_Ordinary,
3206                                                  RLoc));
3207  }
3208
3209  if (getLangOpts().CPlusPlus &&
3210      (LHSExp->getType()->isRecordType() ||
3211       LHSExp->getType()->isEnumeralType() ||
3212       RHSExp->getType()->isRecordType() ||
3213       RHSExp->getType()->isEnumeralType()) &&
3214      !LHSExp->getType()->isObjCObjectPointerType()) {
3215    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3216  }
3217
3218  return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3219}
3220
3221
3222ExprResult
3223Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3224                                      Expr *Idx, SourceLocation RLoc) {
3225  Expr *LHSExp = Base;
3226  Expr *RHSExp = Idx;
3227
3228  // Perform default conversions.
3229  if (!LHSExp->getType()->getAs<VectorType>()) {
3230    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3231    if (Result.isInvalid())
3232      return ExprError();
3233    LHSExp = Result.take();
3234  }
3235  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3236  if (Result.isInvalid())
3237    return ExprError();
3238  RHSExp = Result.take();
3239
3240  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3241  ExprValueKind VK = VK_LValue;
3242  ExprObjectKind OK = OK_Ordinary;
3243
3244  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3245  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3246  // in the subscript position. As a result, we need to derive the array base
3247  // and index from the expression types.
3248  Expr *BaseExpr, *IndexExpr;
3249  QualType ResultType;
3250  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3251    BaseExpr = LHSExp;
3252    IndexExpr = RHSExp;
3253    ResultType = Context.DependentTy;
3254  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3255    BaseExpr = LHSExp;
3256    IndexExpr = RHSExp;
3257    ResultType = PTy->getPointeeType();
3258  } else if (const ObjCObjectPointerType *PTy =
3259             LHSTy->getAs<ObjCObjectPointerType>()) {
3260    BaseExpr = LHSExp;
3261    IndexExpr = RHSExp;
3262    Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3263    if (!Result.isInvalid())
3264      return Owned(Result.take());
3265    ResultType = PTy->getPointeeType();
3266  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3267     // Handle the uncommon case of "123[Ptr]".
3268    BaseExpr = RHSExp;
3269    IndexExpr = LHSExp;
3270    ResultType = PTy->getPointeeType();
3271  } else if (const ObjCObjectPointerType *PTy =
3272               RHSTy->getAs<ObjCObjectPointerType>()) {
3273     // Handle the uncommon case of "123[Ptr]".
3274    BaseExpr = RHSExp;
3275    IndexExpr = LHSExp;
3276    ResultType = PTy->getPointeeType();
3277  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3278    BaseExpr = LHSExp;    // vectors: V[123]
3279    IndexExpr = RHSExp;
3280    VK = LHSExp->getValueKind();
3281    if (VK != VK_RValue)
3282      OK = OK_VectorComponent;
3283
3284    // FIXME: need to deal with const...
3285    ResultType = VTy->getElementType();
3286  } else if (LHSTy->isArrayType()) {
3287    // If we see an array that wasn't promoted by
3288    // DefaultFunctionArrayLvalueConversion, it must be an array that
3289    // wasn't promoted because of the C90 rule that doesn't
3290    // allow promoting non-lvalue arrays.  Warn, then
3291    // force the promotion here.
3292    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3293        LHSExp->getSourceRange();
3294    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3295                               CK_ArrayToPointerDecay).take();
3296    LHSTy = LHSExp->getType();
3297
3298    BaseExpr = LHSExp;
3299    IndexExpr = RHSExp;
3300    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3301  } else if (RHSTy->isArrayType()) {
3302    // Same as previous, except for 123[f().a] case
3303    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3304        RHSExp->getSourceRange();
3305    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3306                               CK_ArrayToPointerDecay).take();
3307    RHSTy = RHSExp->getType();
3308
3309    BaseExpr = RHSExp;
3310    IndexExpr = LHSExp;
3311    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3312  } else {
3313    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3314       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3315  }
3316  // C99 6.5.2.1p1
3317  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3318    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3319                     << IndexExpr->getSourceRange());
3320
3321  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3322       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3323         && !IndexExpr->isTypeDependent())
3324    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3325
3326  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3327  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3328  // type. Note that Functions are not objects, and that (in C99 parlance)
3329  // incomplete types are not object types.
3330  if (ResultType->isFunctionType()) {
3331    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3332      << ResultType << BaseExpr->getSourceRange();
3333    return ExprError();
3334  }
3335
3336  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3337    // GNU extension: subscripting on pointer to void
3338    Diag(LLoc, diag::ext_gnu_subscript_void_type)
3339      << BaseExpr->getSourceRange();
3340
3341    // C forbids expressions of unqualified void type from being l-values.
3342    // See IsCForbiddenLValueType.
3343    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3344  } else if (!ResultType->isDependentType() &&
3345      RequireCompleteType(LLoc, ResultType,
3346                          diag::err_subscript_incomplete_type, BaseExpr))
3347    return ExprError();
3348
3349  // Diagnose bad cases where we step over interface counts.
3350  if (ResultType->isObjCObjectType() && LangOpts.ObjCRuntime.isNonFragile()) {
3351    Diag(LLoc, diag::err_subscript_nonfragile_interface)
3352      << ResultType << BaseExpr->getSourceRange();
3353    return ExprError();
3354  }
3355
3356  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3357         !ResultType.isCForbiddenLValueType());
3358
3359  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3360                                                ResultType, VK, OK, RLoc));
3361}
3362
3363ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3364                                        FunctionDecl *FD,
3365                                        ParmVarDecl *Param) {
3366  if (Param->hasUnparsedDefaultArg()) {
3367    Diag(CallLoc,
3368         diag::err_use_of_default_argument_to_function_declared_later) <<
3369      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3370    Diag(UnparsedDefaultArgLocs[Param],
3371         diag::note_default_argument_declared_here);
3372    return ExprError();
3373  }
3374
3375  if (Param->hasUninstantiatedDefaultArg()) {
3376    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3377
3378    // Instantiate the expression.
3379    MultiLevelTemplateArgumentList ArgList
3380      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3381
3382    std::pair<const TemplateArgument *, unsigned> Innermost
3383      = ArgList.getInnermost();
3384    InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3385                               Innermost.second);
3386
3387    ExprResult Result;
3388    {
3389      // C++ [dcl.fct.default]p5:
3390      //   The names in the [default argument] expression are bound, and
3391      //   the semantic constraints are checked, at the point where the
3392      //   default argument expression appears.
3393      ContextRAII SavedContext(*this, FD);
3394      LocalInstantiationScope Local(*this);
3395      Result = SubstExpr(UninstExpr, ArgList);
3396    }
3397    if (Result.isInvalid())
3398      return ExprError();
3399
3400    // Check the expression as an initializer for the parameter.
3401    InitializedEntity Entity
3402      = InitializedEntity::InitializeParameter(Context, Param);
3403    InitializationKind Kind
3404      = InitializationKind::CreateCopy(Param->getLocation(),
3405             /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3406    Expr *ResultE = Result.takeAs<Expr>();
3407
3408    InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3409    Result = InitSeq.Perform(*this, Entity, Kind,
3410                             MultiExprArg(*this, &ResultE, 1));
3411    if (Result.isInvalid())
3412      return ExprError();
3413
3414    Expr *Arg = Result.takeAs<Expr>();
3415    CheckImplicitConversions(Arg, Param->getOuterLocStart());
3416    // Build the default argument expression.
3417    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3418  }
3419
3420  // If the default expression creates temporaries, we need to
3421  // push them to the current stack of expression temporaries so they'll
3422  // be properly destroyed.
3423  // FIXME: We should really be rebuilding the default argument with new
3424  // bound temporaries; see the comment in PR5810.
3425  // We don't need to do that with block decls, though, because
3426  // blocks in default argument expression can never capture anything.
3427  if (isa<ExprWithCleanups>(Param->getInit())) {
3428    // Set the "needs cleanups" bit regardless of whether there are
3429    // any explicit objects.
3430    ExprNeedsCleanups = true;
3431
3432    // Append all the objects to the cleanup list.  Right now, this
3433    // should always be a no-op, because blocks in default argument
3434    // expressions should never be able to capture anything.
3435    assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3436           "default argument expression has capturing blocks?");
3437  }
3438
3439  // We already type-checked the argument, so we know it works.
3440  // Just mark all of the declarations in this potentially-evaluated expression
3441  // as being "referenced".
3442  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3443                                   /*SkipLocalVariables=*/true);
3444  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3445}
3446
3447
3448Sema::VariadicCallType
3449Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3450                          Expr *Fn) {
3451  if (Proto && Proto->isVariadic()) {
3452    if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3453      return VariadicConstructor;
3454    else if (Fn && Fn->getType()->isBlockPointerType())
3455      return VariadicBlock;
3456    else if (FDecl) {
3457      if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3458        if (Method->isInstance())
3459          return VariadicMethod;
3460    }
3461    return VariadicFunction;
3462  }
3463  return VariadicDoesNotApply;
3464}
3465
3466/// ConvertArgumentsForCall - Converts the arguments specified in
3467/// Args/NumArgs to the parameter types of the function FDecl with
3468/// function prototype Proto. Call is the call expression itself, and
3469/// Fn is the function expression. For a C++ member function, this
3470/// routine does not attempt to convert the object argument. Returns
3471/// true if the call is ill-formed.
3472bool
3473Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3474                              FunctionDecl *FDecl,
3475                              const FunctionProtoType *Proto,
3476                              Expr **Args, unsigned NumArgs,
3477                              SourceLocation RParenLoc,
3478                              bool IsExecConfig) {
3479  // Bail out early if calling a builtin with custom typechecking.
3480  // We don't need to do this in the
3481  if (FDecl)
3482    if (unsigned ID = FDecl->getBuiltinID())
3483      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3484        return false;
3485
3486  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3487  // assignment, to the types of the corresponding parameter, ...
3488  unsigned NumArgsInProto = Proto->getNumArgs();
3489  bool Invalid = false;
3490  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3491  unsigned FnKind = Fn->getType()->isBlockPointerType()
3492                       ? 1 /* block */
3493                       : (IsExecConfig ? 3 /* kernel function (exec config) */
3494                                       : 0 /* function */);
3495
3496  // If too few arguments are available (and we don't have default
3497  // arguments for the remaining parameters), don't make the call.
3498  if (NumArgs < NumArgsInProto) {
3499    if (NumArgs < MinArgs) {
3500      if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3501        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3502                          ? diag::err_typecheck_call_too_few_args_one
3503                          : diag::err_typecheck_call_too_few_args_at_least_one)
3504          << FnKind
3505          << FDecl->getParamDecl(0) << Fn->getSourceRange();
3506      else
3507        Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3508                          ? diag::err_typecheck_call_too_few_args
3509                          : diag::err_typecheck_call_too_few_args_at_least)
3510          << FnKind
3511          << MinArgs << NumArgs << Fn->getSourceRange();
3512
3513      // Emit the location of the prototype.
3514      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3515        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3516          << FDecl;
3517
3518      return true;
3519    }
3520    Call->setNumArgs(Context, NumArgsInProto);
3521  }
3522
3523  // If too many are passed and not variadic, error on the extras and drop
3524  // them.
3525  if (NumArgs > NumArgsInProto) {
3526    if (!Proto->isVariadic()) {
3527      if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3528        Diag(Args[NumArgsInProto]->getLocStart(),
3529             MinArgs == NumArgsInProto
3530               ? diag::err_typecheck_call_too_many_args_one
3531               : diag::err_typecheck_call_too_many_args_at_most_one)
3532          << FnKind
3533          << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3534          << SourceRange(Args[NumArgsInProto]->getLocStart(),
3535                         Args[NumArgs-1]->getLocEnd());
3536      else
3537        Diag(Args[NumArgsInProto]->getLocStart(),
3538             MinArgs == NumArgsInProto
3539               ? diag::err_typecheck_call_too_many_args
3540               : diag::err_typecheck_call_too_many_args_at_most)
3541          << FnKind
3542          << NumArgsInProto << NumArgs << Fn->getSourceRange()
3543          << SourceRange(Args[NumArgsInProto]->getLocStart(),
3544                         Args[NumArgs-1]->getLocEnd());
3545
3546      // Emit the location of the prototype.
3547      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3548        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3549          << FDecl;
3550
3551      // This deletes the extra arguments.
3552      Call->setNumArgs(Context, NumArgsInProto);
3553      return true;
3554    }
3555  }
3556  SmallVector<Expr *, 8> AllArgs;
3557  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3558
3559  Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3560                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
3561  if (Invalid)
3562    return true;
3563  unsigned TotalNumArgs = AllArgs.size();
3564  for (unsigned i = 0; i < TotalNumArgs; ++i)
3565    Call->setArg(i, AllArgs[i]);
3566
3567  return false;
3568}
3569
3570bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3571                                  FunctionDecl *FDecl,
3572                                  const FunctionProtoType *Proto,
3573                                  unsigned FirstProtoArg,
3574                                  Expr **Args, unsigned NumArgs,
3575                                  SmallVector<Expr *, 8> &AllArgs,
3576                                  VariadicCallType CallType,
3577                                  bool AllowExplicit) {
3578  unsigned NumArgsInProto = Proto->getNumArgs();
3579  unsigned NumArgsToCheck = NumArgs;
3580  bool Invalid = false;
3581  if (NumArgs != NumArgsInProto)
3582    // Use default arguments for missing arguments
3583    NumArgsToCheck = NumArgsInProto;
3584  unsigned ArgIx = 0;
3585  // Continue to check argument types (even if we have too few/many args).
3586  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3587    QualType ProtoArgType = Proto->getArgType(i);
3588
3589    Expr *Arg;
3590    ParmVarDecl *Param;
3591    if (ArgIx < NumArgs) {
3592      Arg = Args[ArgIx++];
3593
3594      if (RequireCompleteType(Arg->getLocStart(),
3595                              ProtoArgType,
3596                              diag::err_call_incomplete_argument, Arg))
3597        return true;
3598
3599      // Pass the argument
3600      Param = 0;
3601      if (FDecl && i < FDecl->getNumParams())
3602        Param = FDecl->getParamDecl(i);
3603
3604      // Strip the unbridged-cast placeholder expression off, if applicable.
3605      if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3606          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3607          (!Param || !Param->hasAttr<CFConsumedAttr>()))
3608        Arg = stripARCUnbridgedCast(Arg);
3609
3610      InitializedEntity Entity =
3611        Param? InitializedEntity::InitializeParameter(Context, Param)
3612             : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3613                                                      Proto->isArgConsumed(i));
3614      ExprResult ArgE = PerformCopyInitialization(Entity,
3615                                                  SourceLocation(),
3616                                                  Owned(Arg),
3617                                                  /*TopLevelOfInitList=*/false,
3618                                                  AllowExplicit);
3619      if (ArgE.isInvalid())
3620        return true;
3621
3622      Arg = ArgE.takeAs<Expr>();
3623    } else {
3624      Param = FDecl->getParamDecl(i);
3625
3626      ExprResult ArgExpr =
3627        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3628      if (ArgExpr.isInvalid())
3629        return true;
3630
3631      Arg = ArgExpr.takeAs<Expr>();
3632    }
3633
3634    // Check for array bounds violations for each argument to the call. This
3635    // check only triggers warnings when the argument isn't a more complex Expr
3636    // with its own checking, such as a BinaryOperator.
3637    CheckArrayAccess(Arg);
3638
3639    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3640    CheckStaticArrayArgument(CallLoc, Param, Arg);
3641
3642    AllArgs.push_back(Arg);
3643  }
3644
3645  // If this is a variadic call, handle args passed through "...".
3646  if (CallType != VariadicDoesNotApply) {
3647    // Assume that extern "C" functions with variadic arguments that
3648    // return __unknown_anytype aren't *really* variadic.
3649    if (Proto->getResultType() == Context.UnknownAnyTy &&
3650        FDecl && FDecl->isExternC()) {
3651      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3652        ExprResult arg;
3653        if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3654          arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3655        else
3656          arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3657        Invalid |= arg.isInvalid();
3658        AllArgs.push_back(arg.take());
3659      }
3660
3661    // Otherwise do argument promotion, (C99 6.5.2.2p7).
3662    } else {
3663      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3664        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3665                                                          FDecl);
3666        Invalid |= Arg.isInvalid();
3667        AllArgs.push_back(Arg.take());
3668      }
3669    }
3670
3671    // Check for array bounds violations.
3672    for (unsigned i = ArgIx; i != NumArgs; ++i)
3673      CheckArrayAccess(Args[i]);
3674  }
3675  return Invalid;
3676}
3677
3678static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3679  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3680  if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3681    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3682      << ATL->getLocalSourceRange();
3683}
3684
3685/// CheckStaticArrayArgument - If the given argument corresponds to a static
3686/// array parameter, check that it is non-null, and that if it is formed by
3687/// array-to-pointer decay, the underlying array is sufficiently large.
3688///
3689/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3690/// array type derivation, then for each call to the function, the value of the
3691/// corresponding actual argument shall provide access to the first element of
3692/// an array with at least as many elements as specified by the size expression.
3693void
3694Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3695                               ParmVarDecl *Param,
3696                               const Expr *ArgExpr) {
3697  // Static array parameters are not supported in C++.
3698  if (!Param || getLangOpts().CPlusPlus)
3699    return;
3700
3701  QualType OrigTy = Param->getOriginalType();
3702
3703  const ArrayType *AT = Context.getAsArrayType(OrigTy);
3704  if (!AT || AT->getSizeModifier() != ArrayType::Static)
3705    return;
3706
3707  if (ArgExpr->isNullPointerConstant(Context,
3708                                     Expr::NPC_NeverValueDependent)) {
3709    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3710    DiagnoseCalleeStaticArrayParam(*this, Param);
3711    return;
3712  }
3713
3714  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3715  if (!CAT)
3716    return;
3717
3718  const ConstantArrayType *ArgCAT =
3719    Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3720  if (!ArgCAT)
3721    return;
3722
3723  if (ArgCAT->getSize().ult(CAT->getSize())) {
3724    Diag(CallLoc, diag::warn_static_array_too_small)
3725      << ArgExpr->getSourceRange()
3726      << (unsigned) ArgCAT->getSize().getZExtValue()
3727      << (unsigned) CAT->getSize().getZExtValue();
3728    DiagnoseCalleeStaticArrayParam(*this, Param);
3729  }
3730}
3731
3732/// Given a function expression of unknown-any type, try to rebuild it
3733/// to have a function type.
3734static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3735
3736/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3737/// This provides the location of the left/right parens and a list of comma
3738/// locations.
3739ExprResult
3740Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3741                    MultiExprArg ArgExprs, SourceLocation RParenLoc,
3742                    Expr *ExecConfig, bool IsExecConfig) {
3743  unsigned NumArgs = ArgExprs.size();
3744
3745  // Since this might be a postfix expression, get rid of ParenListExprs.
3746  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3747  if (Result.isInvalid()) return ExprError();
3748  Fn = Result.take();
3749
3750  Expr **Args = ArgExprs.release();
3751
3752  if (getLangOpts().CPlusPlus) {
3753    // If this is a pseudo-destructor expression, build the call immediately.
3754    if (isa<CXXPseudoDestructorExpr>(Fn)) {
3755      if (NumArgs > 0) {
3756        // Pseudo-destructor calls should not have any arguments.
3757        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3758          << FixItHint::CreateRemoval(
3759                                    SourceRange(Args[0]->getLocStart(),
3760                                                Args[NumArgs-1]->getLocEnd()));
3761      }
3762
3763      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3764                                          VK_RValue, RParenLoc));
3765    }
3766
3767    // Determine whether this is a dependent call inside a C++ template,
3768    // in which case we won't do any semantic analysis now.
3769    // FIXME: Will need to cache the results of name lookup (including ADL) in
3770    // Fn.
3771    bool Dependent = false;
3772    if (Fn->isTypeDependent())
3773      Dependent = true;
3774    else if (Expr::hasAnyTypeDependentArguments(
3775        llvm::makeArrayRef(Args, NumArgs)))
3776      Dependent = true;
3777
3778    if (Dependent) {
3779      if (ExecConfig) {
3780        return Owned(new (Context) CUDAKernelCallExpr(
3781            Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3782            Context.DependentTy, VK_RValue, RParenLoc));
3783      } else {
3784        return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3785                                            Context.DependentTy, VK_RValue,
3786                                            RParenLoc));
3787      }
3788    }
3789
3790    // Determine whether this is a call to an object (C++ [over.call.object]).
3791    if (Fn->getType()->isRecordType())
3792      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3793                                                RParenLoc));
3794
3795    if (Fn->getType() == Context.UnknownAnyTy) {
3796      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3797      if (result.isInvalid()) return ExprError();
3798      Fn = result.take();
3799    }
3800
3801    if (Fn->getType() == Context.BoundMemberTy) {
3802      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3803                                       RParenLoc);
3804    }
3805  }
3806
3807  // Check for overloaded calls.  This can happen even in C due to extensions.
3808  if (Fn->getType() == Context.OverloadTy) {
3809    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3810
3811    // We aren't supposed to apply this logic for if there's an '&' involved.
3812    if (!find.HasFormOfMemberPointer) {
3813      OverloadExpr *ovl = find.Expression;
3814      if (isa<UnresolvedLookupExpr>(ovl)) {
3815        UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3816        return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3817                                       RParenLoc, ExecConfig);
3818      } else {
3819        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3820                                         RParenLoc);
3821      }
3822    }
3823  }
3824
3825  // If we're directly calling a function, get the appropriate declaration.
3826  if (Fn->getType() == Context.UnknownAnyTy) {
3827    ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3828    if (result.isInvalid()) return ExprError();
3829    Fn = result.take();
3830  }
3831
3832  Expr *NakedFn = Fn->IgnoreParens();
3833
3834  NamedDecl *NDecl = 0;
3835  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3836    if (UnOp->getOpcode() == UO_AddrOf)
3837      NakedFn = UnOp->getSubExpr()->IgnoreParens();
3838
3839  if (isa<DeclRefExpr>(NakedFn))
3840    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3841  else if (isa<MemberExpr>(NakedFn))
3842    NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3843
3844  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3845                               ExecConfig, IsExecConfig);
3846}
3847
3848ExprResult
3849Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3850                              MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3851  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3852  if (!ConfigDecl)
3853    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3854                          << "cudaConfigureCall");
3855  QualType ConfigQTy = ConfigDecl->getType();
3856
3857  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3858      ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3859  MarkFunctionReferenced(LLLLoc, ConfigDecl);
3860
3861  return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3862                       /*IsExecConfig=*/true);
3863}
3864
3865/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3866///
3867/// __builtin_astype( value, dst type )
3868///
3869ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3870                                 SourceLocation BuiltinLoc,
3871                                 SourceLocation RParenLoc) {
3872  ExprValueKind VK = VK_RValue;
3873  ExprObjectKind OK = OK_Ordinary;
3874  QualType DstTy = GetTypeFromParser(ParsedDestTy);
3875  QualType SrcTy = E->getType();
3876  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3877    return ExprError(Diag(BuiltinLoc,
3878                          diag::err_invalid_astype_of_different_size)
3879                     << DstTy
3880                     << SrcTy
3881                     << E->getSourceRange());
3882  return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3883               RParenLoc));
3884}
3885
3886/// BuildResolvedCallExpr - Build a call to a resolved expression,
3887/// i.e. an expression not of \p OverloadTy.  The expression should
3888/// unary-convert to an expression of function-pointer or
3889/// block-pointer type.
3890///
3891/// \param NDecl the declaration being called, if available
3892ExprResult
3893Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3894                            SourceLocation LParenLoc,
3895                            Expr **Args, unsigned NumArgs,
3896                            SourceLocation RParenLoc,
3897                            Expr *Config, bool IsExecConfig) {
3898  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3899
3900  // Promote the function operand.
3901  ExprResult Result = UsualUnaryConversions(Fn);
3902  if (Result.isInvalid())
3903    return ExprError();
3904  Fn = Result.take();
3905
3906  // Make the call expr early, before semantic checks.  This guarantees cleanup
3907  // of arguments and function on error.
3908  CallExpr *TheCall;
3909  if (Config)
3910    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3911                                               cast<CallExpr>(Config),
3912                                               Args, NumArgs,
3913                                               Context.BoolTy,
3914                                               VK_RValue,
3915                                               RParenLoc);
3916  else
3917    TheCall = new (Context) CallExpr(Context, Fn,
3918                                     Args, NumArgs,
3919                                     Context.BoolTy,
3920                                     VK_RValue,
3921                                     RParenLoc);
3922
3923  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3924
3925  // Bail out early if calling a builtin with custom typechecking.
3926  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3927    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3928
3929 retry:
3930  const FunctionType *FuncT;
3931  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3932    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3933    // have type pointer to function".
3934    FuncT = PT->getPointeeType()->getAs<FunctionType>();
3935    if (FuncT == 0)
3936      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3937                         << Fn->getType() << Fn->getSourceRange());
3938  } else if (const BlockPointerType *BPT =
3939               Fn->getType()->getAs<BlockPointerType>()) {
3940    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3941  } else {
3942    // Handle calls to expressions of unknown-any type.
3943    if (Fn->getType() == Context.UnknownAnyTy) {
3944      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3945      if (rewrite.isInvalid()) return ExprError();
3946      Fn = rewrite.take();
3947      TheCall->setCallee(Fn);
3948      goto retry;
3949    }
3950
3951    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3952      << Fn->getType() << Fn->getSourceRange());
3953  }
3954
3955  if (getLangOpts().CUDA) {
3956    if (Config) {
3957      // CUDA: Kernel calls must be to global functions
3958      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3959        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3960            << FDecl->getName() << Fn->getSourceRange());
3961
3962      // CUDA: Kernel function must have 'void' return type
3963      if (!FuncT->getResultType()->isVoidType())
3964        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3965            << Fn->getType() << Fn->getSourceRange());
3966    } else {
3967      // CUDA: Calls to global functions must be configured
3968      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3969        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3970            << FDecl->getName() << Fn->getSourceRange());
3971    }
3972  }
3973
3974  // Check for a valid return type
3975  if (CheckCallReturnType(FuncT->getResultType(),
3976                          Fn->getLocStart(), TheCall,
3977                          FDecl))
3978    return ExprError();
3979
3980  // We know the result type of the call, set it.
3981  TheCall->setType(FuncT->getCallResultType(Context));
3982  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
3983
3984  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
3985  if (Proto) {
3986    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
3987                                RParenLoc, IsExecConfig))
3988      return ExprError();
3989  } else {
3990    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3991
3992    if (FDecl) {
3993      // Check if we have too few/too many template arguments, based
3994      // on our knowledge of the function definition.
3995      const FunctionDecl *Def = 0;
3996      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3997        Proto = Def->getType()->getAs<FunctionProtoType>();
3998        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
3999          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4000            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4001      }
4002
4003      // If the function we're calling isn't a function prototype, but we have
4004      // a function prototype from a prior declaratiom, use that prototype.
4005      if (!FDecl->hasPrototype())
4006        Proto = FDecl->getType()->getAs<FunctionProtoType>();
4007    }
4008
4009    // Promote the arguments (C99 6.5.2.2p6).
4010    for (unsigned i = 0; i != NumArgs; i++) {
4011      Expr *Arg = Args[i];
4012
4013      if (Proto && i < Proto->getNumArgs()) {
4014        InitializedEntity Entity
4015          = InitializedEntity::InitializeParameter(Context,
4016                                                   Proto->getArgType(i),
4017                                                   Proto->isArgConsumed(i));
4018        ExprResult ArgE = PerformCopyInitialization(Entity,
4019                                                    SourceLocation(),
4020                                                    Owned(Arg));
4021        if (ArgE.isInvalid())
4022          return true;
4023
4024        Arg = ArgE.takeAs<Expr>();
4025
4026      } else {
4027        ExprResult ArgE = DefaultArgumentPromotion(Arg);
4028
4029        if (ArgE.isInvalid())
4030          return true;
4031
4032        Arg = ArgE.takeAs<Expr>();
4033      }
4034
4035      if (RequireCompleteType(Arg->getLocStart(),
4036                              Arg->getType(),
4037                              diag::err_call_incomplete_argument, Arg))
4038        return ExprError();
4039
4040      TheCall->setArg(i, Arg);
4041    }
4042  }
4043
4044  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4045    if (!Method->isStatic())
4046      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4047        << Fn->getSourceRange());
4048
4049  // Check for sentinels
4050  if (NDecl)
4051    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4052
4053  // Do special checking on direct calls to functions.
4054  if (FDecl) {
4055    if (CheckFunctionCall(FDecl, TheCall, Proto))
4056      return ExprError();
4057
4058    if (BuiltinID)
4059      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4060  } else if (NDecl) {
4061    if (CheckBlockCall(NDecl, TheCall, Proto))
4062      return ExprError();
4063  }
4064
4065  return MaybeBindToTemporary(TheCall);
4066}
4067
4068ExprResult
4069Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4070                           SourceLocation RParenLoc, Expr *InitExpr) {
4071  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4072  // FIXME: put back this assert when initializers are worked out.
4073  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4074
4075  TypeSourceInfo *TInfo;
4076  QualType literalType = GetTypeFromParser(Ty, &TInfo);
4077  if (!TInfo)
4078    TInfo = Context.getTrivialTypeSourceInfo(literalType);
4079
4080  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4081}
4082
4083ExprResult
4084Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4085                               SourceLocation RParenLoc, Expr *LiteralExpr) {
4086  QualType literalType = TInfo->getType();
4087
4088  if (literalType->isArrayType()) {
4089    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4090          diag::err_illegal_decl_array_incomplete_type,
4091          SourceRange(LParenLoc,
4092                      LiteralExpr->getSourceRange().getEnd())))
4093      return ExprError();
4094    if (literalType->isVariableArrayType())
4095      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4096        << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4097  } else if (!literalType->isDependentType() &&
4098             RequireCompleteType(LParenLoc, literalType,
4099               diag::err_typecheck_decl_incomplete_type,
4100               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4101    return ExprError();
4102
4103  InitializedEntity Entity
4104    = InitializedEntity::InitializeTemporary(literalType);
4105  InitializationKind Kind
4106    = InitializationKind::CreateCStyleCast(LParenLoc,
4107                                           SourceRange(LParenLoc, RParenLoc),
4108                                           /*InitList=*/true);
4109  InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4110  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4111                                       MultiExprArg(*this, &LiteralExpr, 1),
4112                                            &literalType);
4113  if (Result.isInvalid())
4114    return ExprError();
4115  LiteralExpr = Result.get();
4116
4117  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4118  if (isFileScope) { // 6.5.2.5p3
4119    if (CheckForConstantInitializer(LiteralExpr, literalType))
4120      return ExprError();
4121  }
4122
4123  // In C, compound literals are l-values for some reason.
4124  ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4125
4126  return MaybeBindToTemporary(
4127           new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4128                                             VK, LiteralExpr, isFileScope));
4129}
4130
4131ExprResult
4132Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4133                    SourceLocation RBraceLoc) {
4134  unsigned NumInit = InitArgList.size();
4135  Expr **InitList = InitArgList.release();
4136
4137  // Immediately handle non-overload placeholders.  Overloads can be
4138  // resolved contextually, but everything else here can't.
4139  for (unsigned I = 0; I != NumInit; ++I) {
4140    if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
4141      ExprResult result = CheckPlaceholderExpr(InitList[I]);
4142
4143      // Ignore failures; dropping the entire initializer list because
4144      // of one failure would be terrible for indexing/etc.
4145      if (result.isInvalid()) continue;
4146
4147      InitList[I] = result.take();
4148    }
4149  }
4150
4151  // Semantic analysis for initializers is done by ActOnDeclarator() and
4152  // CheckInitializer() - it requires knowledge of the object being intialized.
4153
4154  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4155                                               NumInit, RBraceLoc);
4156  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4157  return Owned(E);
4158}
4159
4160/// Do an explicit extend of the given block pointer if we're in ARC.
4161static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4162  assert(E.get()->getType()->isBlockPointerType());
4163  assert(E.get()->isRValue());
4164
4165  // Only do this in an r-value context.
4166  if (!S.getLangOpts().ObjCAutoRefCount) return;
4167
4168  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4169                               CK_ARCExtendBlockObject, E.get(),
4170                               /*base path*/ 0, VK_RValue);
4171  S.ExprNeedsCleanups = true;
4172}
4173
4174/// Prepare a conversion of the given expression to an ObjC object
4175/// pointer type.
4176CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4177  QualType type = E.get()->getType();
4178  if (type->isObjCObjectPointerType()) {
4179    return CK_BitCast;
4180  } else if (type->isBlockPointerType()) {
4181    maybeExtendBlockObject(*this, E);
4182    return CK_BlockPointerToObjCPointerCast;
4183  } else {
4184    assert(type->isPointerType());
4185    return CK_CPointerToObjCPointerCast;
4186  }
4187}
4188
4189/// Prepares for a scalar cast, performing all the necessary stages
4190/// except the final cast and returning the kind required.
4191CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4192  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4193  // Also, callers should have filtered out the invalid cases with
4194  // pointers.  Everything else should be possible.
4195
4196  QualType SrcTy = Src.get()->getType();
4197  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4198    return CK_NoOp;
4199
4200  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4201  case Type::STK_MemberPointer:
4202    llvm_unreachable("member pointer type in C");
4203
4204  case Type::STK_CPointer:
4205  case Type::STK_BlockPointer:
4206  case Type::STK_ObjCObjectPointer:
4207    switch (DestTy->getScalarTypeKind()) {
4208    case Type::STK_CPointer:
4209      return CK_BitCast;
4210    case Type::STK_BlockPointer:
4211      return (SrcKind == Type::STK_BlockPointer
4212                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4213    case Type::STK_ObjCObjectPointer:
4214      if (SrcKind == Type::STK_ObjCObjectPointer)
4215        return CK_BitCast;
4216      if (SrcKind == Type::STK_CPointer)
4217        return CK_CPointerToObjCPointerCast;
4218      maybeExtendBlockObject(*this, Src);
4219      return CK_BlockPointerToObjCPointerCast;
4220    case Type::STK_Bool:
4221      return CK_PointerToBoolean;
4222    case Type::STK_Integral:
4223      return CK_PointerToIntegral;
4224    case Type::STK_Floating:
4225    case Type::STK_FloatingComplex:
4226    case Type::STK_IntegralComplex:
4227    case Type::STK_MemberPointer:
4228      llvm_unreachable("illegal cast from pointer");
4229    }
4230    llvm_unreachable("Should have returned before this");
4231
4232  case Type::STK_Bool: // casting from bool is like casting from an integer
4233  case Type::STK_Integral:
4234    switch (DestTy->getScalarTypeKind()) {
4235    case Type::STK_CPointer:
4236    case Type::STK_ObjCObjectPointer:
4237    case Type::STK_BlockPointer:
4238      if (Src.get()->isNullPointerConstant(Context,
4239                                           Expr::NPC_ValueDependentIsNull))
4240        return CK_NullToPointer;
4241      return CK_IntegralToPointer;
4242    case Type::STK_Bool:
4243      return CK_IntegralToBoolean;
4244    case Type::STK_Integral:
4245      return CK_IntegralCast;
4246    case Type::STK_Floating:
4247      return CK_IntegralToFloating;
4248    case Type::STK_IntegralComplex:
4249      Src = ImpCastExprToType(Src.take(),
4250                              DestTy->castAs<ComplexType>()->getElementType(),
4251                              CK_IntegralCast);
4252      return CK_IntegralRealToComplex;
4253    case Type::STK_FloatingComplex:
4254      Src = ImpCastExprToType(Src.take(),
4255                              DestTy->castAs<ComplexType>()->getElementType(),
4256                              CK_IntegralToFloating);
4257      return CK_FloatingRealToComplex;
4258    case Type::STK_MemberPointer:
4259      llvm_unreachable("member pointer type in C");
4260    }
4261    llvm_unreachable("Should have returned before this");
4262
4263  case Type::STK_Floating:
4264    switch (DestTy->getScalarTypeKind()) {
4265    case Type::STK_Floating:
4266      return CK_FloatingCast;
4267    case Type::STK_Bool:
4268      return CK_FloatingToBoolean;
4269    case Type::STK_Integral:
4270      return CK_FloatingToIntegral;
4271    case Type::STK_FloatingComplex:
4272      Src = ImpCastExprToType(Src.take(),
4273                              DestTy->castAs<ComplexType>()->getElementType(),
4274                              CK_FloatingCast);
4275      return CK_FloatingRealToComplex;
4276    case Type::STK_IntegralComplex:
4277      Src = ImpCastExprToType(Src.take(),
4278                              DestTy->castAs<ComplexType>()->getElementType(),
4279                              CK_FloatingToIntegral);
4280      return CK_IntegralRealToComplex;
4281    case Type::STK_CPointer:
4282    case Type::STK_ObjCObjectPointer:
4283    case Type::STK_BlockPointer:
4284      llvm_unreachable("valid float->pointer cast?");
4285    case Type::STK_MemberPointer:
4286      llvm_unreachable("member pointer type in C");
4287    }
4288    llvm_unreachable("Should have returned before this");
4289
4290  case Type::STK_FloatingComplex:
4291    switch (DestTy->getScalarTypeKind()) {
4292    case Type::STK_FloatingComplex:
4293      return CK_FloatingComplexCast;
4294    case Type::STK_IntegralComplex:
4295      return CK_FloatingComplexToIntegralComplex;
4296    case Type::STK_Floating: {
4297      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4298      if (Context.hasSameType(ET, DestTy))
4299        return CK_FloatingComplexToReal;
4300      Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4301      return CK_FloatingCast;
4302    }
4303    case Type::STK_Bool:
4304      return CK_FloatingComplexToBoolean;
4305    case Type::STK_Integral:
4306      Src = ImpCastExprToType(Src.take(),
4307                              SrcTy->castAs<ComplexType>()->getElementType(),
4308                              CK_FloatingComplexToReal);
4309      return CK_FloatingToIntegral;
4310    case Type::STK_CPointer:
4311    case Type::STK_ObjCObjectPointer:
4312    case Type::STK_BlockPointer:
4313      llvm_unreachable("valid complex float->pointer cast?");
4314    case Type::STK_MemberPointer:
4315      llvm_unreachable("member pointer type in C");
4316    }
4317    llvm_unreachable("Should have returned before this");
4318
4319  case Type::STK_IntegralComplex:
4320    switch (DestTy->getScalarTypeKind()) {
4321    case Type::STK_FloatingComplex:
4322      return CK_IntegralComplexToFloatingComplex;
4323    case Type::STK_IntegralComplex:
4324      return CK_IntegralComplexCast;
4325    case Type::STK_Integral: {
4326      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4327      if (Context.hasSameType(ET, DestTy))
4328        return CK_IntegralComplexToReal;
4329      Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4330      return CK_IntegralCast;
4331    }
4332    case Type::STK_Bool:
4333      return CK_IntegralComplexToBoolean;
4334    case Type::STK_Floating:
4335      Src = ImpCastExprToType(Src.take(),
4336                              SrcTy->castAs<ComplexType>()->getElementType(),
4337                              CK_IntegralComplexToReal);
4338      return CK_IntegralToFloating;
4339    case Type::STK_CPointer:
4340    case Type::STK_ObjCObjectPointer:
4341    case Type::STK_BlockPointer:
4342      llvm_unreachable("valid complex int->pointer cast?");
4343    case Type::STK_MemberPointer:
4344      llvm_unreachable("member pointer type in C");
4345    }
4346    llvm_unreachable("Should have returned before this");
4347  }
4348
4349  llvm_unreachable("Unhandled scalar cast");
4350}
4351
4352bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4353                           CastKind &Kind) {
4354  assert(VectorTy->isVectorType() && "Not a vector type!");
4355
4356  if (Ty->isVectorType() || Ty->isIntegerType()) {
4357    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4358      return Diag(R.getBegin(),
4359                  Ty->isVectorType() ?
4360                  diag::err_invalid_conversion_between_vectors :
4361                  diag::err_invalid_conversion_between_vector_and_integer)
4362        << VectorTy << Ty << R;
4363  } else
4364    return Diag(R.getBegin(),
4365                diag::err_invalid_conversion_between_vector_and_scalar)
4366      << VectorTy << Ty << R;
4367
4368  Kind = CK_BitCast;
4369  return false;
4370}
4371
4372ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4373                                    Expr *CastExpr, CastKind &Kind) {
4374  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4375
4376  QualType SrcTy = CastExpr->getType();
4377
4378  // If SrcTy is a VectorType, the total size must match to explicitly cast to
4379  // an ExtVectorType.
4380  // In OpenCL, casts between vectors of different types are not allowed.
4381  // (See OpenCL 6.2).
4382  if (SrcTy->isVectorType()) {
4383    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4384        || (getLangOpts().OpenCL &&
4385            (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4386      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4387        << DestTy << SrcTy << R;
4388      return ExprError();
4389    }
4390    Kind = CK_BitCast;
4391    return Owned(CastExpr);
4392  }
4393
4394  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4395  // conversion will take place first from scalar to elt type, and then
4396  // splat from elt type to vector.
4397  if (SrcTy->isPointerType())
4398    return Diag(R.getBegin(),
4399                diag::err_invalid_conversion_between_vector_and_scalar)
4400      << DestTy << SrcTy << R;
4401
4402  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4403  ExprResult CastExprRes = Owned(CastExpr);
4404  CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4405  if (CastExprRes.isInvalid())
4406    return ExprError();
4407  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4408
4409  Kind = CK_VectorSplat;
4410  return Owned(CastExpr);
4411}
4412
4413ExprResult
4414Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4415                    Declarator &D, ParsedType &Ty,
4416                    SourceLocation RParenLoc, Expr *CastExpr) {
4417  assert(!D.isInvalidType() && (CastExpr != 0) &&
4418         "ActOnCastExpr(): missing type or expr");
4419
4420  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4421  if (D.isInvalidType())
4422    return ExprError();
4423
4424  if (getLangOpts().CPlusPlus) {
4425    // Check that there are no default arguments (C++ only).
4426    CheckExtraCXXDefaultArguments(D);
4427  }
4428
4429  checkUnusedDeclAttributes(D);
4430
4431  QualType castType = castTInfo->getType();
4432  Ty = CreateParsedType(castType, castTInfo);
4433
4434  bool isVectorLiteral = false;
4435
4436  // Check for an altivec or OpenCL literal,
4437  // i.e. all the elements are integer constants.
4438  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4439  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4440  if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4441       && castType->isVectorType() && (PE || PLE)) {
4442    if (PLE && PLE->getNumExprs() == 0) {
4443      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4444      return ExprError();
4445    }
4446    if (PE || PLE->getNumExprs() == 1) {
4447      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4448      if (!E->getType()->isVectorType())
4449        isVectorLiteral = true;
4450    }
4451    else
4452      isVectorLiteral = true;
4453  }
4454
4455  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4456  // then handle it as such.
4457  if (isVectorLiteral)
4458    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4459
4460  // If the Expr being casted is a ParenListExpr, handle it specially.
4461  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4462  // sequence of BinOp comma operators.
4463  if (isa<ParenListExpr>(CastExpr)) {
4464    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4465    if (Result.isInvalid()) return ExprError();
4466    CastExpr = Result.take();
4467  }
4468
4469  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4470}
4471
4472ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4473                                    SourceLocation RParenLoc, Expr *E,
4474                                    TypeSourceInfo *TInfo) {
4475  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4476         "Expected paren or paren list expression");
4477
4478  Expr **exprs;
4479  unsigned numExprs;
4480  Expr *subExpr;
4481  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4482    exprs = PE->getExprs();
4483    numExprs = PE->getNumExprs();
4484  } else {
4485    subExpr = cast<ParenExpr>(E)->getSubExpr();
4486    exprs = &subExpr;
4487    numExprs = 1;
4488  }
4489
4490  QualType Ty = TInfo->getType();
4491  assert(Ty->isVectorType() && "Expected vector type");
4492
4493  SmallVector<Expr *, 8> initExprs;
4494  const VectorType *VTy = Ty->getAs<VectorType>();
4495  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4496
4497  // '(...)' form of vector initialization in AltiVec: the number of
4498  // initializers must be one or must match the size of the vector.
4499  // If a single value is specified in the initializer then it will be
4500  // replicated to all the components of the vector
4501  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4502    // The number of initializers must be one or must match the size of the
4503    // vector. If a single value is specified in the initializer then it will
4504    // be replicated to all the components of the vector
4505    if (numExprs == 1) {
4506      QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4507      ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4508      if (Literal.isInvalid())
4509        return ExprError();
4510      Literal = ImpCastExprToType(Literal.take(), ElemTy,
4511                                  PrepareScalarCast(Literal, ElemTy));
4512      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4513    }
4514    else if (numExprs < numElems) {
4515      Diag(E->getExprLoc(),
4516           diag::err_incorrect_number_of_vector_initializers);
4517      return ExprError();
4518    }
4519    else
4520      initExprs.append(exprs, exprs + numExprs);
4521  }
4522  else {
4523    // For OpenCL, when the number of initializers is a single value,
4524    // it will be replicated to all components of the vector.
4525    if (getLangOpts().OpenCL &&
4526        VTy->getVectorKind() == VectorType::GenericVector &&
4527        numExprs == 1) {
4528        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4529        ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4530        if (Literal.isInvalid())
4531          return ExprError();
4532        Literal = ImpCastExprToType(Literal.take(), ElemTy,
4533                                    PrepareScalarCast(Literal, ElemTy));
4534        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4535    }
4536
4537    initExprs.append(exprs, exprs + numExprs);
4538  }
4539  // FIXME: This means that pretty-printing the final AST will produce curly
4540  // braces instead of the original commas.
4541  InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4542                                                   &initExprs[0],
4543                                                   initExprs.size(), RParenLoc);
4544  initE->setType(Ty);
4545  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4546}
4547
4548/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4549/// the ParenListExpr into a sequence of comma binary operators.
4550ExprResult
4551Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4552  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4553  if (!E)
4554    return Owned(OrigExpr);
4555
4556  ExprResult Result(E->getExpr(0));
4557
4558  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4559    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4560                        E->getExpr(i));
4561
4562  if (Result.isInvalid()) return ExprError();
4563
4564  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4565}
4566
4567ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4568                                    SourceLocation R,
4569                                    MultiExprArg Val) {
4570  unsigned nexprs = Val.size();
4571  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4572  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4573  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4574  return Owned(expr);
4575}
4576
4577/// \brief Emit a specialized diagnostic when one expression is a null pointer
4578/// constant and the other is not a pointer.  Returns true if a diagnostic is
4579/// emitted.
4580bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4581                                      SourceLocation QuestionLoc) {
4582  Expr *NullExpr = LHSExpr;
4583  Expr *NonPointerExpr = RHSExpr;
4584  Expr::NullPointerConstantKind NullKind =
4585      NullExpr->isNullPointerConstant(Context,
4586                                      Expr::NPC_ValueDependentIsNotNull);
4587
4588  if (NullKind == Expr::NPCK_NotNull) {
4589    NullExpr = RHSExpr;
4590    NonPointerExpr = LHSExpr;
4591    NullKind =
4592        NullExpr->isNullPointerConstant(Context,
4593                                        Expr::NPC_ValueDependentIsNotNull);
4594  }
4595
4596  if (NullKind == Expr::NPCK_NotNull)
4597    return false;
4598
4599  if (NullKind == Expr::NPCK_ZeroInteger) {
4600    // In this case, check to make sure that we got here from a "NULL"
4601    // string in the source code.
4602    NullExpr = NullExpr->IgnoreParenImpCasts();
4603    SourceLocation loc = NullExpr->getExprLoc();
4604    if (!findMacroSpelling(loc, "NULL"))
4605      return false;
4606  }
4607
4608  int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4609  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4610      << NonPointerExpr->getType() << DiagType
4611      << NonPointerExpr->getSourceRange();
4612  return true;
4613}
4614
4615/// \brief Return false if the condition expression is valid, true otherwise.
4616static bool checkCondition(Sema &S, Expr *Cond) {
4617  QualType CondTy = Cond->getType();
4618
4619  // C99 6.5.15p2
4620  if (CondTy->isScalarType()) return false;
4621
4622  // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4623  if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4624    return false;
4625
4626  // Emit the proper error message.
4627  S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4628                              diag::err_typecheck_cond_expect_scalar :
4629                              diag::err_typecheck_cond_expect_scalar_or_vector)
4630    << CondTy;
4631  return true;
4632}
4633
4634/// \brief Return false if the two expressions can be converted to a vector,
4635/// true otherwise
4636static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4637                                                    ExprResult &RHS,
4638                                                    QualType CondTy) {
4639  // Both operands should be of scalar type.
4640  if (!LHS.get()->getType()->isScalarType()) {
4641    S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4642      << CondTy;
4643    return true;
4644  }
4645  if (!RHS.get()->getType()->isScalarType()) {
4646    S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4647      << CondTy;
4648    return true;
4649  }
4650
4651  // Implicity convert these scalars to the type of the condition.
4652  LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4653  RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4654  return false;
4655}
4656
4657/// \brief Handle when one or both operands are void type.
4658static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4659                                         ExprResult &RHS) {
4660    Expr *LHSExpr = LHS.get();
4661    Expr *RHSExpr = RHS.get();
4662
4663    if (!LHSExpr->getType()->isVoidType())
4664      S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4665        << RHSExpr->getSourceRange();
4666    if (!RHSExpr->getType()->isVoidType())
4667      S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4668        << LHSExpr->getSourceRange();
4669    LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4670    RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4671    return S.Context.VoidTy;
4672}
4673
4674/// \brief Return false if the NullExpr can be promoted to PointerTy,
4675/// true otherwise.
4676static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4677                                        QualType PointerTy) {
4678  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4679      !NullExpr.get()->isNullPointerConstant(S.Context,
4680                                            Expr::NPC_ValueDependentIsNull))
4681    return true;
4682
4683  NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4684  return false;
4685}
4686
4687/// \brief Checks compatibility between two pointers and return the resulting
4688/// type.
4689static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4690                                                     ExprResult &RHS,
4691                                                     SourceLocation Loc) {
4692  QualType LHSTy = LHS.get()->getType();
4693  QualType RHSTy = RHS.get()->getType();
4694
4695  if (S.Context.hasSameType(LHSTy, RHSTy)) {
4696    // Two identical pointers types are always compatible.
4697    return LHSTy;
4698  }
4699
4700  QualType lhptee, rhptee;
4701
4702  // Get the pointee types.
4703  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4704    lhptee = LHSBTy->getPointeeType();
4705    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4706  } else {
4707    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4708    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4709  }
4710
4711  // C99 6.5.15p6: If both operands are pointers to compatible types or to
4712  // differently qualified versions of compatible types, the result type is
4713  // a pointer to an appropriately qualified version of the composite
4714  // type.
4715
4716  // Only CVR-qualifiers exist in the standard, and the differently-qualified
4717  // clause doesn't make sense for our extensions. E.g. address space 2 should
4718  // be incompatible with address space 3: they may live on different devices or
4719  // anything.
4720  Qualifiers lhQual = lhptee.getQualifiers();
4721  Qualifiers rhQual = rhptee.getQualifiers();
4722
4723  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4724  lhQual.removeCVRQualifiers();
4725  rhQual.removeCVRQualifiers();
4726
4727  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4728  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4729
4730  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4731
4732  if (CompositeTy.isNull()) {
4733    S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4734      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4735      << RHS.get()->getSourceRange();
4736    // In this situation, we assume void* type. No especially good
4737    // reason, but this is what gcc does, and we do have to pick
4738    // to get a consistent AST.
4739    QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4740    LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4741    RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4742    return incompatTy;
4743  }
4744
4745  // The pointer types are compatible.
4746  QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4747  ResultTy = S.Context.getPointerType(ResultTy);
4748
4749  LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4750  RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4751  return ResultTy;
4752}
4753
4754/// \brief Return the resulting type when the operands are both block pointers.
4755static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4756                                                          ExprResult &LHS,
4757                                                          ExprResult &RHS,
4758                                                          SourceLocation Loc) {
4759  QualType LHSTy = LHS.get()->getType();
4760  QualType RHSTy = RHS.get()->getType();
4761
4762  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4763    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4764      QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4765      LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4766      RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4767      return destType;
4768    }
4769    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4770      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4771      << RHS.get()->getSourceRange();
4772    return QualType();
4773  }
4774
4775  // We have 2 block pointer types.
4776  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4777}
4778
4779/// \brief Return the resulting type when the operands are both pointers.
4780static QualType
4781checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4782                                            ExprResult &RHS,
4783                                            SourceLocation Loc) {
4784  // get the pointer types
4785  QualType LHSTy = LHS.get()->getType();
4786  QualType RHSTy = RHS.get()->getType();
4787
4788  // get the "pointed to" types
4789  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4790  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4791
4792  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4793  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4794    // Figure out necessary qualifiers (C99 6.5.15p6)
4795    QualType destPointee
4796      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4797    QualType destType = S.Context.getPointerType(destPointee);
4798    // Add qualifiers if necessary.
4799    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4800    // Promote to void*.
4801    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4802    return destType;
4803  }
4804  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4805    QualType destPointee
4806      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4807    QualType destType = S.Context.getPointerType(destPointee);
4808    // Add qualifiers if necessary.
4809    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4810    // Promote to void*.
4811    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4812    return destType;
4813  }
4814
4815  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4816}
4817
4818/// \brief Return false if the first expression is not an integer and the second
4819/// expression is not a pointer, true otherwise.
4820static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4821                                        Expr* PointerExpr, SourceLocation Loc,
4822                                        bool IsIntFirstExpr) {
4823  if (!PointerExpr->getType()->isPointerType() ||
4824      !Int.get()->getType()->isIntegerType())
4825    return false;
4826
4827  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4828  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4829
4830  S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4831    << Expr1->getType() << Expr2->getType()
4832    << Expr1->getSourceRange() << Expr2->getSourceRange();
4833  Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4834                            CK_IntegralToPointer);
4835  return true;
4836}
4837
4838/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4839/// In that case, LHS = cond.
4840/// C99 6.5.15
4841QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4842                                        ExprResult &RHS, ExprValueKind &VK,
4843                                        ExprObjectKind &OK,
4844                                        SourceLocation QuestionLoc) {
4845
4846  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4847  if (!LHSResult.isUsable()) return QualType();
4848  LHS = move(LHSResult);
4849
4850  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4851  if (!RHSResult.isUsable()) return QualType();
4852  RHS = move(RHSResult);
4853
4854  // C++ is sufficiently different to merit its own checker.
4855  if (getLangOpts().CPlusPlus)
4856    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4857
4858  VK = VK_RValue;
4859  OK = OK_Ordinary;
4860
4861  Cond = UsualUnaryConversions(Cond.take());
4862  if (Cond.isInvalid())
4863    return QualType();
4864  LHS = UsualUnaryConversions(LHS.take());
4865  if (LHS.isInvalid())
4866    return QualType();
4867  RHS = UsualUnaryConversions(RHS.take());
4868  if (RHS.isInvalid())
4869    return QualType();
4870
4871  QualType CondTy = Cond.get()->getType();
4872  QualType LHSTy = LHS.get()->getType();
4873  QualType RHSTy = RHS.get()->getType();
4874
4875  // first, check the condition.
4876  if (checkCondition(*this, Cond.get()))
4877    return QualType();
4878
4879  // Now check the two expressions.
4880  if (LHSTy->isVectorType() || RHSTy->isVectorType())
4881    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4882
4883  // OpenCL: If the condition is a vector, and both operands are scalar,
4884  // attempt to implicity convert them to the vector type to act like the
4885  // built in select.
4886  if (getLangOpts().OpenCL && CondTy->isVectorType())
4887    if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4888      return QualType();
4889
4890  // If both operands have arithmetic type, do the usual arithmetic conversions
4891  // to find a common type: C99 6.5.15p3,5.
4892  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4893    UsualArithmeticConversions(LHS, RHS);
4894    if (LHS.isInvalid() || RHS.isInvalid())
4895      return QualType();
4896    return LHS.get()->getType();
4897  }
4898
4899  // If both operands are the same structure or union type, the result is that
4900  // type.
4901  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4902    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4903      if (LHSRT->getDecl() == RHSRT->getDecl())
4904        // "If both the operands have structure or union type, the result has
4905        // that type."  This implies that CV qualifiers are dropped.
4906        return LHSTy.getUnqualifiedType();
4907    // FIXME: Type of conditional expression must be complete in C mode.
4908  }
4909
4910  // C99 6.5.15p5: "If both operands have void type, the result has void type."
4911  // The following || allows only one side to be void (a GCC-ism).
4912  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4913    return checkConditionalVoidType(*this, LHS, RHS);
4914  }
4915
4916  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4917  // the type of the other operand."
4918  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4919  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4920
4921  // All objective-c pointer type analysis is done here.
4922  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4923                                                        QuestionLoc);
4924  if (LHS.isInvalid() || RHS.isInvalid())
4925    return QualType();
4926  if (!compositeType.isNull())
4927    return compositeType;
4928
4929
4930  // Handle block pointer types.
4931  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4932    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4933                                                     QuestionLoc);
4934
4935  // Check constraints for C object pointers types (C99 6.5.15p3,6).
4936  if (LHSTy->isPointerType() && RHSTy->isPointerType())
4937    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4938                                                       QuestionLoc);
4939
4940  // GCC compatibility: soften pointer/integer mismatch.  Note that
4941  // null pointers have been filtered out by this point.
4942  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4943      /*isIntFirstExpr=*/true))
4944    return RHSTy;
4945  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4946      /*isIntFirstExpr=*/false))
4947    return LHSTy;
4948
4949  // Emit a better diagnostic if one of the expressions is a null pointer
4950  // constant and the other is not a pointer type. In this case, the user most
4951  // likely forgot to take the address of the other expression.
4952  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4953    return QualType();
4954
4955  // Otherwise, the operands are not compatible.
4956  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4957    << LHSTy << RHSTy << LHS.get()->getSourceRange()
4958    << RHS.get()->getSourceRange();
4959  return QualType();
4960}
4961
4962/// FindCompositeObjCPointerType - Helper method to find composite type of
4963/// two objective-c pointer types of the two input expressions.
4964QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4965                                            SourceLocation QuestionLoc) {
4966  QualType LHSTy = LHS.get()->getType();
4967  QualType RHSTy = RHS.get()->getType();
4968
4969  // Handle things like Class and struct objc_class*.  Here we case the result
4970  // to the pseudo-builtin, because that will be implicitly cast back to the
4971  // redefinition type if an attempt is made to access its fields.
4972  if (LHSTy->isObjCClassType() &&
4973      (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
4974    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4975    return LHSTy;
4976  }
4977  if (RHSTy->isObjCClassType() &&
4978      (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
4979    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4980    return RHSTy;
4981  }
4982  // And the same for struct objc_object* / id
4983  if (LHSTy->isObjCIdType() &&
4984      (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
4985    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4986    return LHSTy;
4987  }
4988  if (RHSTy->isObjCIdType() &&
4989      (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
4990    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4991    return RHSTy;
4992  }
4993  // And the same for struct objc_selector* / SEL
4994  if (Context.isObjCSelType(LHSTy) &&
4995      (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
4996    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4997    return LHSTy;
4998  }
4999  if (Context.isObjCSelType(RHSTy) &&
5000      (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5001    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5002    return RHSTy;
5003  }
5004  // Check constraints for Objective-C object pointers types.
5005  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5006
5007    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5008      // Two identical object pointer types are always compatible.
5009      return LHSTy;
5010    }
5011    const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5012    const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5013    QualType compositeType = LHSTy;
5014
5015    // If both operands are interfaces and either operand can be
5016    // assigned to the other, use that type as the composite
5017    // type. This allows
5018    //   xxx ? (A*) a : (B*) b
5019    // where B is a subclass of A.
5020    //
5021    // Additionally, as for assignment, if either type is 'id'
5022    // allow silent coercion. Finally, if the types are
5023    // incompatible then make sure to use 'id' as the composite
5024    // type so the result is acceptable for sending messages to.
5025
5026    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5027    // It could return the composite type.
5028    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5029      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5030    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5031      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5032    } else if ((LHSTy->isObjCQualifiedIdType() ||
5033                RHSTy->isObjCQualifiedIdType()) &&
5034               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5035      // Need to handle "id<xx>" explicitly.
5036      // GCC allows qualified id and any Objective-C type to devolve to
5037      // id. Currently localizing to here until clear this should be
5038      // part of ObjCQualifiedIdTypesAreCompatible.
5039      compositeType = Context.getObjCIdType();
5040    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5041      compositeType = Context.getObjCIdType();
5042    } else if (!(compositeType =
5043                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5044      ;
5045    else {
5046      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5047      << LHSTy << RHSTy
5048      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5049      QualType incompatTy = Context.getObjCIdType();
5050      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5051      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5052      return incompatTy;
5053    }
5054    // The object pointer types are compatible.
5055    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5056    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5057    return compositeType;
5058  }
5059  // Check Objective-C object pointer types and 'void *'
5060  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5061    if (getLangOpts().ObjCAutoRefCount) {
5062      // ARC forbids the implicit conversion of object pointers to 'void *',
5063      // so these types are not compatible.
5064      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5065          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5066      LHS = RHS = true;
5067      return QualType();
5068    }
5069    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5070    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5071    QualType destPointee
5072    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5073    QualType destType = Context.getPointerType(destPointee);
5074    // Add qualifiers if necessary.
5075    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5076    // Promote to void*.
5077    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5078    return destType;
5079  }
5080  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5081    if (getLangOpts().ObjCAutoRefCount) {
5082      // ARC forbids the implicit conversion of object pointers to 'void *',
5083      // so these types are not compatible.
5084      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5085          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5086      LHS = RHS = true;
5087      return QualType();
5088    }
5089    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5090    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5091    QualType destPointee
5092    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5093    QualType destType = Context.getPointerType(destPointee);
5094    // Add qualifiers if necessary.
5095    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5096    // Promote to void*.
5097    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5098    return destType;
5099  }
5100  return QualType();
5101}
5102
5103/// SuggestParentheses - Emit a note with a fixit hint that wraps
5104/// ParenRange in parentheses.
5105static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5106                               const PartialDiagnostic &Note,
5107                               SourceRange ParenRange) {
5108  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5109  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5110      EndLoc.isValid()) {
5111    Self.Diag(Loc, Note)
5112      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5113      << FixItHint::CreateInsertion(EndLoc, ")");
5114  } else {
5115    // We can't display the parentheses, so just show the bare note.
5116    Self.Diag(Loc, Note) << ParenRange;
5117  }
5118}
5119
5120static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5121  return Opc >= BO_Mul && Opc <= BO_Shr;
5122}
5123
5124/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5125/// expression, either using a built-in or overloaded operator,
5126/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5127/// expression.
5128static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5129                                   Expr **RHSExprs) {
5130  // Don't strip parenthesis: we should not warn if E is in parenthesis.
5131  E = E->IgnoreImpCasts();
5132  E = E->IgnoreConversionOperator();
5133  E = E->IgnoreImpCasts();
5134
5135  // Built-in binary operator.
5136  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5137    if (IsArithmeticOp(OP->getOpcode())) {
5138      *Opcode = OP->getOpcode();
5139      *RHSExprs = OP->getRHS();
5140      return true;
5141    }
5142  }
5143
5144  // Overloaded operator.
5145  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5146    if (Call->getNumArgs() != 2)
5147      return false;
5148
5149    // Make sure this is really a binary operator that is safe to pass into
5150    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5151    OverloadedOperatorKind OO = Call->getOperator();
5152    if (OO < OO_Plus || OO > OO_Arrow)
5153      return false;
5154
5155    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5156    if (IsArithmeticOp(OpKind)) {
5157      *Opcode = OpKind;
5158      *RHSExprs = Call->getArg(1);
5159      return true;
5160    }
5161  }
5162
5163  return false;
5164}
5165
5166static bool IsLogicOp(BinaryOperatorKind Opc) {
5167  return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5168}
5169
5170/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5171/// or is a logical expression such as (x==y) which has int type, but is
5172/// commonly interpreted as boolean.
5173static bool ExprLooksBoolean(Expr *E) {
5174  E = E->IgnoreParenImpCasts();
5175
5176  if (E->getType()->isBooleanType())
5177    return true;
5178  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5179    return IsLogicOp(OP->getOpcode());
5180  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5181    return OP->getOpcode() == UO_LNot;
5182
5183  return false;
5184}
5185
5186/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5187/// and binary operator are mixed in a way that suggests the programmer assumed
5188/// the conditional operator has higher precedence, for example:
5189/// "int x = a + someBinaryCondition ? 1 : 2".
5190static void DiagnoseConditionalPrecedence(Sema &Self,
5191                                          SourceLocation OpLoc,
5192                                          Expr *Condition,
5193                                          Expr *LHSExpr,
5194                                          Expr *RHSExpr) {
5195  BinaryOperatorKind CondOpcode;
5196  Expr *CondRHS;
5197
5198  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5199    return;
5200  if (!ExprLooksBoolean(CondRHS))
5201    return;
5202
5203  // The condition is an arithmetic binary expression, with a right-
5204  // hand side that looks boolean, so warn.
5205
5206  Self.Diag(OpLoc, diag::warn_precedence_conditional)
5207      << Condition->getSourceRange()
5208      << BinaryOperator::getOpcodeStr(CondOpcode);
5209
5210  SuggestParentheses(Self, OpLoc,
5211    Self.PDiag(diag::note_precedence_conditional_silence)
5212      << BinaryOperator::getOpcodeStr(CondOpcode),
5213    SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5214
5215  SuggestParentheses(Self, OpLoc,
5216    Self.PDiag(diag::note_precedence_conditional_first),
5217    SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5218}
5219
5220/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5221/// in the case of a the GNU conditional expr extension.
5222ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5223                                    SourceLocation ColonLoc,
5224                                    Expr *CondExpr, Expr *LHSExpr,
5225                                    Expr *RHSExpr) {
5226  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5227  // was the condition.
5228  OpaqueValueExpr *opaqueValue = 0;
5229  Expr *commonExpr = 0;
5230  if (LHSExpr == 0) {
5231    commonExpr = CondExpr;
5232
5233    // We usually want to apply unary conversions *before* saving, except
5234    // in the special case of a C++ l-value conditional.
5235    if (!(getLangOpts().CPlusPlus
5236          && !commonExpr->isTypeDependent()
5237          && commonExpr->getValueKind() == RHSExpr->getValueKind()
5238          && commonExpr->isGLValue()
5239          && commonExpr->isOrdinaryOrBitFieldObject()
5240          && RHSExpr->isOrdinaryOrBitFieldObject()
5241          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5242      ExprResult commonRes = UsualUnaryConversions(commonExpr);
5243      if (commonRes.isInvalid())
5244        return ExprError();
5245      commonExpr = commonRes.take();
5246    }
5247
5248    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5249                                                commonExpr->getType(),
5250                                                commonExpr->getValueKind(),
5251                                                commonExpr->getObjectKind(),
5252                                                commonExpr);
5253    LHSExpr = CondExpr = opaqueValue;
5254  }
5255
5256  ExprValueKind VK = VK_RValue;
5257  ExprObjectKind OK = OK_Ordinary;
5258  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5259  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5260                                             VK, OK, QuestionLoc);
5261  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5262      RHS.isInvalid())
5263    return ExprError();
5264
5265  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5266                                RHS.get());
5267
5268  if (!commonExpr)
5269    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5270                                                   LHS.take(), ColonLoc,
5271                                                   RHS.take(), result, VK, OK));
5272
5273  return Owned(new (Context)
5274    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5275                              RHS.take(), QuestionLoc, ColonLoc, result, VK,
5276                              OK));
5277}
5278
5279// checkPointerTypesForAssignment - This is a very tricky routine (despite
5280// being closely modeled after the C99 spec:-). The odd characteristic of this
5281// routine is it effectively iqnores the qualifiers on the top level pointee.
5282// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5283// FIXME: add a couple examples in this comment.
5284static Sema::AssignConvertType
5285checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5286  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5287  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5288
5289  // get the "pointed to" type (ignoring qualifiers at the top level)
5290  const Type *lhptee, *rhptee;
5291  Qualifiers lhq, rhq;
5292  llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5293  llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5294
5295  Sema::AssignConvertType ConvTy = Sema::Compatible;
5296
5297  // C99 6.5.16.1p1: This following citation is common to constraints
5298  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5299  // qualifiers of the type *pointed to* by the right;
5300  Qualifiers lq;
5301
5302  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5303  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5304      lhq.compatiblyIncludesObjCLifetime(rhq)) {
5305    // Ignore lifetime for further calculation.
5306    lhq.removeObjCLifetime();
5307    rhq.removeObjCLifetime();
5308  }
5309
5310  if (!lhq.compatiblyIncludes(rhq)) {
5311    // Treat address-space mismatches as fatal.  TODO: address subspaces
5312    if (lhq.getAddressSpace() != rhq.getAddressSpace())
5313      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5314
5315    // It's okay to add or remove GC or lifetime qualifiers when converting to
5316    // and from void*.
5317    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5318                        .compatiblyIncludes(
5319                                rhq.withoutObjCGCAttr().withoutObjCLifetime())
5320             && (lhptee->isVoidType() || rhptee->isVoidType()))
5321      ; // keep old
5322
5323    // Treat lifetime mismatches as fatal.
5324    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5325      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5326
5327    // For GCC compatibility, other qualifier mismatches are treated
5328    // as still compatible in C.
5329    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5330  }
5331
5332  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5333  // incomplete type and the other is a pointer to a qualified or unqualified
5334  // version of void...
5335  if (lhptee->isVoidType()) {
5336    if (rhptee->isIncompleteOrObjectType())
5337      return ConvTy;
5338
5339    // As an extension, we allow cast to/from void* to function pointer.
5340    assert(rhptee->isFunctionType());
5341    return Sema::FunctionVoidPointer;
5342  }
5343
5344  if (rhptee->isVoidType()) {
5345    if (lhptee->isIncompleteOrObjectType())
5346      return ConvTy;
5347
5348    // As an extension, we allow cast to/from void* to function pointer.
5349    assert(lhptee->isFunctionType());
5350    return Sema::FunctionVoidPointer;
5351  }
5352
5353  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5354  // unqualified versions of compatible types, ...
5355  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5356  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5357    // Check if the pointee types are compatible ignoring the sign.
5358    // We explicitly check for char so that we catch "char" vs
5359    // "unsigned char" on systems where "char" is unsigned.
5360    if (lhptee->isCharType())
5361      ltrans = S.Context.UnsignedCharTy;
5362    else if (lhptee->hasSignedIntegerRepresentation())
5363      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5364
5365    if (rhptee->isCharType())
5366      rtrans = S.Context.UnsignedCharTy;
5367    else if (rhptee->hasSignedIntegerRepresentation())
5368      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5369
5370    if (ltrans == rtrans) {
5371      // Types are compatible ignoring the sign. Qualifier incompatibility
5372      // takes priority over sign incompatibility because the sign
5373      // warning can be disabled.
5374      if (ConvTy != Sema::Compatible)
5375        return ConvTy;
5376
5377      return Sema::IncompatiblePointerSign;
5378    }
5379
5380    // If we are a multi-level pointer, it's possible that our issue is simply
5381    // one of qualification - e.g. char ** -> const char ** is not allowed. If
5382    // the eventual target type is the same and the pointers have the same
5383    // level of indirection, this must be the issue.
5384    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5385      do {
5386        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5387        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5388      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5389
5390      if (lhptee == rhptee)
5391        return Sema::IncompatibleNestedPointerQualifiers;
5392    }
5393
5394    // General pointer incompatibility takes priority over qualifiers.
5395    return Sema::IncompatiblePointer;
5396  }
5397  if (!S.getLangOpts().CPlusPlus &&
5398      S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5399    return Sema::IncompatiblePointer;
5400  return ConvTy;
5401}
5402
5403/// checkBlockPointerTypesForAssignment - This routine determines whether two
5404/// block pointer types are compatible or whether a block and normal pointer
5405/// are compatible. It is more restrict than comparing two function pointer
5406// types.
5407static Sema::AssignConvertType
5408checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5409                                    QualType RHSType) {
5410  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5411  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5412
5413  QualType lhptee, rhptee;
5414
5415  // get the "pointed to" type (ignoring qualifiers at the top level)
5416  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5417  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5418
5419  // In C++, the types have to match exactly.
5420  if (S.getLangOpts().CPlusPlus)
5421    return Sema::IncompatibleBlockPointer;
5422
5423  Sema::AssignConvertType ConvTy = Sema::Compatible;
5424
5425  // For blocks we enforce that qualifiers are identical.
5426  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5427    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5428
5429  if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5430    return Sema::IncompatibleBlockPointer;
5431
5432  return ConvTy;
5433}
5434
5435/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5436/// for assignment compatibility.
5437static Sema::AssignConvertType
5438checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5439                                   QualType RHSType) {
5440  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5441  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5442
5443  if (LHSType->isObjCBuiltinType()) {
5444    // Class is not compatible with ObjC object pointers.
5445    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5446        !RHSType->isObjCQualifiedClassType())
5447      return Sema::IncompatiblePointer;
5448    return Sema::Compatible;
5449  }
5450  if (RHSType->isObjCBuiltinType()) {
5451    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5452        !LHSType->isObjCQualifiedClassType())
5453      return Sema::IncompatiblePointer;
5454    return Sema::Compatible;
5455  }
5456  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5457  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5458
5459  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5460      // make an exception for id<P>
5461      !LHSType->isObjCQualifiedIdType())
5462    return Sema::CompatiblePointerDiscardsQualifiers;
5463
5464  if (S.Context.typesAreCompatible(LHSType, RHSType))
5465    return Sema::Compatible;
5466  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5467    return Sema::IncompatibleObjCQualifiedId;
5468  return Sema::IncompatiblePointer;
5469}
5470
5471Sema::AssignConvertType
5472Sema::CheckAssignmentConstraints(SourceLocation Loc,
5473                                 QualType LHSType, QualType RHSType) {
5474  // Fake up an opaque expression.  We don't actually care about what
5475  // cast operations are required, so if CheckAssignmentConstraints
5476  // adds casts to this they'll be wasted, but fortunately that doesn't
5477  // usually happen on valid code.
5478  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5479  ExprResult RHSPtr = &RHSExpr;
5480  CastKind K = CK_Invalid;
5481
5482  return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5483}
5484
5485/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5486/// has code to accommodate several GCC extensions when type checking
5487/// pointers. Here are some objectionable examples that GCC considers warnings:
5488///
5489///  int a, *pint;
5490///  short *pshort;
5491///  struct foo *pfoo;
5492///
5493///  pint = pshort; // warning: assignment from incompatible pointer type
5494///  a = pint; // warning: assignment makes integer from pointer without a cast
5495///  pint = a; // warning: assignment makes pointer from integer without a cast
5496///  pint = pfoo; // warning: assignment from incompatible pointer type
5497///
5498/// As a result, the code for dealing with pointers is more complex than the
5499/// C99 spec dictates.
5500///
5501/// Sets 'Kind' for any result kind except Incompatible.
5502Sema::AssignConvertType
5503Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5504                                 CastKind &Kind) {
5505  QualType RHSType = RHS.get()->getType();
5506  QualType OrigLHSType = LHSType;
5507
5508  // Get canonical types.  We're not formatting these types, just comparing
5509  // them.
5510  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5511  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5512
5513
5514  // Common case: no conversion required.
5515  if (LHSType == RHSType) {
5516    Kind = CK_NoOp;
5517    return Compatible;
5518  }
5519
5520  // If we have an atomic type, try a non-atomic assignment, then just add an
5521  // atomic qualification step.
5522  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5523    Sema::AssignConvertType result =
5524      CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5525    if (result != Compatible)
5526      return result;
5527    if (Kind != CK_NoOp)
5528      RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5529    Kind = CK_NonAtomicToAtomic;
5530    return Compatible;
5531  }
5532
5533  // If the left-hand side is a reference type, then we are in a
5534  // (rare!) case where we've allowed the use of references in C,
5535  // e.g., as a parameter type in a built-in function. In this case,
5536  // just make sure that the type referenced is compatible with the
5537  // right-hand side type. The caller is responsible for adjusting
5538  // LHSType so that the resulting expression does not have reference
5539  // type.
5540  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5541    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5542      Kind = CK_LValueBitCast;
5543      return Compatible;
5544    }
5545    return Incompatible;
5546  }
5547
5548  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5549  // to the same ExtVector type.
5550  if (LHSType->isExtVectorType()) {
5551    if (RHSType->isExtVectorType())
5552      return Incompatible;
5553    if (RHSType->isArithmeticType()) {
5554      // CK_VectorSplat does T -> vector T, so first cast to the
5555      // element type.
5556      QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5557      if (elType != RHSType) {
5558        Kind = PrepareScalarCast(RHS, elType);
5559        RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5560      }
5561      Kind = CK_VectorSplat;
5562      return Compatible;
5563    }
5564  }
5565
5566  // Conversions to or from vector type.
5567  if (LHSType->isVectorType() || RHSType->isVectorType()) {
5568    if (LHSType->isVectorType() && RHSType->isVectorType()) {
5569      // Allow assignments of an AltiVec vector type to an equivalent GCC
5570      // vector type and vice versa
5571      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5572        Kind = CK_BitCast;
5573        return Compatible;
5574      }
5575
5576      // If we are allowing lax vector conversions, and LHS and RHS are both
5577      // vectors, the total size only needs to be the same. This is a bitcast;
5578      // no bits are changed but the result type is different.
5579      if (getLangOpts().LaxVectorConversions &&
5580          (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5581        Kind = CK_BitCast;
5582        return IncompatibleVectors;
5583      }
5584    }
5585    return Incompatible;
5586  }
5587
5588  // Arithmetic conversions.
5589  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5590      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5591    Kind = PrepareScalarCast(RHS, LHSType);
5592    return Compatible;
5593  }
5594
5595  // Conversions to normal pointers.
5596  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5597    // U* -> T*
5598    if (isa<PointerType>(RHSType)) {
5599      Kind = CK_BitCast;
5600      return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5601    }
5602
5603    // int -> T*
5604    if (RHSType->isIntegerType()) {
5605      Kind = CK_IntegralToPointer; // FIXME: null?
5606      return IntToPointer;
5607    }
5608
5609    // C pointers are not compatible with ObjC object pointers,
5610    // with two exceptions:
5611    if (isa<ObjCObjectPointerType>(RHSType)) {
5612      //  - conversions to void*
5613      if (LHSPointer->getPointeeType()->isVoidType()) {
5614        Kind = CK_BitCast;
5615        return Compatible;
5616      }
5617
5618      //  - conversions from 'Class' to the redefinition type
5619      if (RHSType->isObjCClassType() &&
5620          Context.hasSameType(LHSType,
5621                              Context.getObjCClassRedefinitionType())) {
5622        Kind = CK_BitCast;
5623        return Compatible;
5624      }
5625
5626      Kind = CK_BitCast;
5627      return IncompatiblePointer;
5628    }
5629
5630    // U^ -> void*
5631    if (RHSType->getAs<BlockPointerType>()) {
5632      if (LHSPointer->getPointeeType()->isVoidType()) {
5633        Kind = CK_BitCast;
5634        return Compatible;
5635      }
5636    }
5637
5638    return Incompatible;
5639  }
5640
5641  // Conversions to block pointers.
5642  if (isa<BlockPointerType>(LHSType)) {
5643    // U^ -> T^
5644    if (RHSType->isBlockPointerType()) {
5645      Kind = CK_BitCast;
5646      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5647    }
5648
5649    // int or null -> T^
5650    if (RHSType->isIntegerType()) {
5651      Kind = CK_IntegralToPointer; // FIXME: null
5652      return IntToBlockPointer;
5653    }
5654
5655    // id -> T^
5656    if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5657      Kind = CK_AnyPointerToBlockPointerCast;
5658      return Compatible;
5659    }
5660
5661    // void* -> T^
5662    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5663      if (RHSPT->getPointeeType()->isVoidType()) {
5664        Kind = CK_AnyPointerToBlockPointerCast;
5665        return Compatible;
5666      }
5667
5668    return Incompatible;
5669  }
5670
5671  // Conversions to Objective-C pointers.
5672  if (isa<ObjCObjectPointerType>(LHSType)) {
5673    // A* -> B*
5674    if (RHSType->isObjCObjectPointerType()) {
5675      Kind = CK_BitCast;
5676      Sema::AssignConvertType result =
5677        checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5678      if (getLangOpts().ObjCAutoRefCount &&
5679          result == Compatible &&
5680          !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5681        result = IncompatibleObjCWeakRef;
5682      return result;
5683    }
5684
5685    // int or null -> A*
5686    if (RHSType->isIntegerType()) {
5687      Kind = CK_IntegralToPointer; // FIXME: null
5688      return IntToPointer;
5689    }
5690
5691    // In general, C pointers are not compatible with ObjC object pointers,
5692    // with two exceptions:
5693    if (isa<PointerType>(RHSType)) {
5694      Kind = CK_CPointerToObjCPointerCast;
5695
5696      //  - conversions from 'void*'
5697      if (RHSType->isVoidPointerType()) {
5698        return Compatible;
5699      }
5700
5701      //  - conversions to 'Class' from its redefinition type
5702      if (LHSType->isObjCClassType() &&
5703          Context.hasSameType(RHSType,
5704                              Context.getObjCClassRedefinitionType())) {
5705        return Compatible;
5706      }
5707
5708      return IncompatiblePointer;
5709    }
5710
5711    // T^ -> A*
5712    if (RHSType->isBlockPointerType()) {
5713      maybeExtendBlockObject(*this, RHS);
5714      Kind = CK_BlockPointerToObjCPointerCast;
5715      return Compatible;
5716    }
5717
5718    return Incompatible;
5719  }
5720
5721  // Conversions from pointers that are not covered by the above.
5722  if (isa<PointerType>(RHSType)) {
5723    // T* -> _Bool
5724    if (LHSType == Context.BoolTy) {
5725      Kind = CK_PointerToBoolean;
5726      return Compatible;
5727    }
5728
5729    // T* -> int
5730    if (LHSType->isIntegerType()) {
5731      Kind = CK_PointerToIntegral;
5732      return PointerToInt;
5733    }
5734
5735    return Incompatible;
5736  }
5737
5738  // Conversions from Objective-C pointers that are not covered by the above.
5739  if (isa<ObjCObjectPointerType>(RHSType)) {
5740    // T* -> _Bool
5741    if (LHSType == Context.BoolTy) {
5742      Kind = CK_PointerToBoolean;
5743      return Compatible;
5744    }
5745
5746    // T* -> int
5747    if (LHSType->isIntegerType()) {
5748      Kind = CK_PointerToIntegral;
5749      return PointerToInt;
5750    }
5751
5752    return Incompatible;
5753  }
5754
5755  // struct A -> struct B
5756  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5757    if (Context.typesAreCompatible(LHSType, RHSType)) {
5758      Kind = CK_NoOp;
5759      return Compatible;
5760    }
5761  }
5762
5763  return Incompatible;
5764}
5765
5766/// \brief Constructs a transparent union from an expression that is
5767/// used to initialize the transparent union.
5768static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5769                                      ExprResult &EResult, QualType UnionType,
5770                                      FieldDecl *Field) {
5771  // Build an initializer list that designates the appropriate member
5772  // of the transparent union.
5773  Expr *E = EResult.take();
5774  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5775                                                   &E, 1,
5776                                                   SourceLocation());
5777  Initializer->setType(UnionType);
5778  Initializer->setInitializedFieldInUnion(Field);
5779
5780  // Build a compound literal constructing a value of the transparent
5781  // union type from this initializer list.
5782  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5783  EResult = S.Owned(
5784    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5785                                VK_RValue, Initializer, false));
5786}
5787
5788Sema::AssignConvertType
5789Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5790                                               ExprResult &RHS) {
5791  QualType RHSType = RHS.get()->getType();
5792
5793  // If the ArgType is a Union type, we want to handle a potential
5794  // transparent_union GCC extension.
5795  const RecordType *UT = ArgType->getAsUnionType();
5796  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5797    return Incompatible;
5798
5799  // The field to initialize within the transparent union.
5800  RecordDecl *UD = UT->getDecl();
5801  FieldDecl *InitField = 0;
5802  // It's compatible if the expression matches any of the fields.
5803  for (RecordDecl::field_iterator it = UD->field_begin(),
5804         itend = UD->field_end();
5805       it != itend; ++it) {
5806    if (it->getType()->isPointerType()) {
5807      // If the transparent union contains a pointer type, we allow:
5808      // 1) void pointer
5809      // 2) null pointer constant
5810      if (RHSType->isPointerType())
5811        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5812          RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5813          InitField = *it;
5814          break;
5815        }
5816
5817      if (RHS.get()->isNullPointerConstant(Context,
5818                                           Expr::NPC_ValueDependentIsNull)) {
5819        RHS = ImpCastExprToType(RHS.take(), it->getType(),
5820                                CK_NullToPointer);
5821        InitField = *it;
5822        break;
5823      }
5824    }
5825
5826    CastKind Kind = CK_Invalid;
5827    if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5828          == Compatible) {
5829      RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5830      InitField = *it;
5831      break;
5832    }
5833  }
5834
5835  if (!InitField)
5836    return Incompatible;
5837
5838  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5839  return Compatible;
5840}
5841
5842Sema::AssignConvertType
5843Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5844                                       bool Diagnose) {
5845  if (getLangOpts().CPlusPlus) {
5846    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5847      // C++ 5.17p3: If the left operand is not of class type, the
5848      // expression is implicitly converted (C++ 4) to the
5849      // cv-unqualified type of the left operand.
5850      ExprResult Res;
5851      if (Diagnose) {
5852        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5853                                        AA_Assigning);
5854      } else {
5855        ImplicitConversionSequence ICS =
5856            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5857                                  /*SuppressUserConversions=*/false,
5858                                  /*AllowExplicit=*/false,
5859                                  /*InOverloadResolution=*/false,
5860                                  /*CStyle=*/false,
5861                                  /*AllowObjCWritebackConversion=*/false);
5862        if (ICS.isFailure())
5863          return Incompatible;
5864        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5865                                        ICS, AA_Assigning);
5866      }
5867      if (Res.isInvalid())
5868        return Incompatible;
5869      Sema::AssignConvertType result = Compatible;
5870      if (getLangOpts().ObjCAutoRefCount &&
5871          !CheckObjCARCUnavailableWeakConversion(LHSType,
5872                                                 RHS.get()->getType()))
5873        result = IncompatibleObjCWeakRef;
5874      RHS = move(Res);
5875      return result;
5876    }
5877
5878    // FIXME: Currently, we fall through and treat C++ classes like C
5879    // structures.
5880    // FIXME: We also fall through for atomics; not sure what should
5881    // happen there, though.
5882  }
5883
5884  // C99 6.5.16.1p1: the left operand is a pointer and the right is
5885  // a null pointer constant.
5886  if ((LHSType->isPointerType() ||
5887       LHSType->isObjCObjectPointerType() ||
5888       LHSType->isBlockPointerType())
5889      && RHS.get()->isNullPointerConstant(Context,
5890                                          Expr::NPC_ValueDependentIsNull)) {
5891    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5892    return Compatible;
5893  }
5894
5895  // This check seems unnatural, however it is necessary to ensure the proper
5896  // conversion of functions/arrays. If the conversion were done for all
5897  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5898  // expressions that suppress this implicit conversion (&, sizeof).
5899  //
5900  // Suppress this for references: C++ 8.5.3p5.
5901  if (!LHSType->isReferenceType()) {
5902    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5903    if (RHS.isInvalid())
5904      return Incompatible;
5905  }
5906
5907  CastKind Kind = CK_Invalid;
5908  Sema::AssignConvertType result =
5909    CheckAssignmentConstraints(LHSType, RHS, Kind);
5910
5911  // C99 6.5.16.1p2: The value of the right operand is converted to the
5912  // type of the assignment expression.
5913  // CheckAssignmentConstraints allows the left-hand side to be a reference,
5914  // so that we can use references in built-in functions even in C.
5915  // The getNonReferenceType() call makes sure that the resulting expression
5916  // does not have reference type.
5917  if (result != Incompatible && RHS.get()->getType() != LHSType)
5918    RHS = ImpCastExprToType(RHS.take(),
5919                            LHSType.getNonLValueExprType(Context), Kind);
5920  return result;
5921}
5922
5923QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5924                               ExprResult &RHS) {
5925  Diag(Loc, diag::err_typecheck_invalid_operands)
5926    << LHS.get()->getType() << RHS.get()->getType()
5927    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5928  return QualType();
5929}
5930
5931QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5932                                   SourceLocation Loc, bool IsCompAssign) {
5933  if (!IsCompAssign) {
5934    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5935    if (LHS.isInvalid())
5936      return QualType();
5937  }
5938  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5939  if (RHS.isInvalid())
5940    return QualType();
5941
5942  // For conversion purposes, we ignore any qualifiers.
5943  // For example, "const float" and "float" are equivalent.
5944  QualType LHSType =
5945    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5946  QualType RHSType =
5947    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5948
5949  // If the vector types are identical, return.
5950  if (LHSType == RHSType)
5951    return LHSType;
5952
5953  // Handle the case of equivalent AltiVec and GCC vector types
5954  if (LHSType->isVectorType() && RHSType->isVectorType() &&
5955      Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5956    if (LHSType->isExtVectorType()) {
5957      RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5958      return LHSType;
5959    }
5960
5961    if (!IsCompAssign)
5962      LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5963    return RHSType;
5964  }
5965
5966  if (getLangOpts().LaxVectorConversions &&
5967      Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
5968    // If we are allowing lax vector conversions, and LHS and RHS are both
5969    // vectors, the total size only needs to be the same. This is a
5970    // bitcast; no bits are changed but the result type is different.
5971    // FIXME: Should we really be allowing this?
5972    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5973    return LHSType;
5974  }
5975
5976  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5977  // swap back (so that we don't reverse the inputs to a subtract, for instance.
5978  bool swapped = false;
5979  if (RHSType->isExtVectorType() && !IsCompAssign) {
5980    swapped = true;
5981    std::swap(RHS, LHS);
5982    std::swap(RHSType, LHSType);
5983  }
5984
5985  // Handle the case of an ext vector and scalar.
5986  if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
5987    QualType EltTy = LV->getElementType();
5988    if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5989      int order = Context.getIntegerTypeOrder(EltTy, RHSType);
5990      if (order > 0)
5991        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
5992      if (order >= 0) {
5993        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5994        if (swapped) std::swap(RHS, LHS);
5995        return LHSType;
5996      }
5997    }
5998    if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5999        RHSType->isRealFloatingType()) {
6000      int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6001      if (order > 0)
6002        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6003      if (order >= 0) {
6004        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6005        if (swapped) std::swap(RHS, LHS);
6006        return LHSType;
6007      }
6008    }
6009  }
6010
6011  // Vectors of different size or scalar and non-ext-vector are errors.
6012  if (swapped) std::swap(RHS, LHS);
6013  Diag(Loc, diag::err_typecheck_vector_not_convertable)
6014    << LHS.get()->getType() << RHS.get()->getType()
6015    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6016  return QualType();
6017}
6018
6019// checkArithmeticNull - Detect when a NULL constant is used improperly in an
6020// expression.  These are mainly cases where the null pointer is used as an
6021// integer instead of a pointer.
6022static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6023                                SourceLocation Loc, bool IsCompare) {
6024  // The canonical way to check for a GNU null is with isNullPointerConstant,
6025  // but we use a bit of a hack here for speed; this is a relatively
6026  // hot path, and isNullPointerConstant is slow.
6027  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6028  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6029
6030  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6031
6032  // Avoid analyzing cases where the result will either be invalid (and
6033  // diagnosed as such) or entirely valid and not something to warn about.
6034  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6035      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6036    return;
6037
6038  // Comparison operations would not make sense with a null pointer no matter
6039  // what the other expression is.
6040  if (!IsCompare) {
6041    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6042        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6043        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6044    return;
6045  }
6046
6047  // The rest of the operations only make sense with a null pointer
6048  // if the other expression is a pointer.
6049  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6050      NonNullType->canDecayToPointerType())
6051    return;
6052
6053  S.Diag(Loc, diag::warn_null_in_comparison_operation)
6054      << LHSNull /* LHS is NULL */ << NonNullType
6055      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6056}
6057
6058QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6059                                           SourceLocation Loc,
6060                                           bool IsCompAssign, bool IsDiv) {
6061  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6062
6063  if (LHS.get()->getType()->isVectorType() ||
6064      RHS.get()->getType()->isVectorType())
6065    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6066
6067  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6068  if (LHS.isInvalid() || RHS.isInvalid())
6069    return QualType();
6070
6071
6072  if (compType.isNull() || !compType->isArithmeticType())
6073    return InvalidOperands(Loc, LHS, RHS);
6074
6075  // Check for division by zero.
6076  if (IsDiv &&
6077      RHS.get()->isNullPointerConstant(Context,
6078                                       Expr::NPC_ValueDependentIsNotNull))
6079    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6080                                          << RHS.get()->getSourceRange());
6081
6082  return compType;
6083}
6084
6085QualType Sema::CheckRemainderOperands(
6086  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6087  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6088
6089  if (LHS.get()->getType()->isVectorType() ||
6090      RHS.get()->getType()->isVectorType()) {
6091    if (LHS.get()->getType()->hasIntegerRepresentation() &&
6092        RHS.get()->getType()->hasIntegerRepresentation())
6093      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6094    return InvalidOperands(Loc, LHS, RHS);
6095  }
6096
6097  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6098  if (LHS.isInvalid() || RHS.isInvalid())
6099    return QualType();
6100
6101  if (compType.isNull() || !compType->isIntegerType())
6102    return InvalidOperands(Loc, LHS, RHS);
6103
6104  // Check for remainder by zero.
6105  if (RHS.get()->isNullPointerConstant(Context,
6106                                       Expr::NPC_ValueDependentIsNotNull))
6107    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6108                                 << RHS.get()->getSourceRange());
6109
6110  return compType;
6111}
6112
6113/// \brief Diagnose invalid arithmetic on two void pointers.
6114static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6115                                                Expr *LHSExpr, Expr *RHSExpr) {
6116  S.Diag(Loc, S.getLangOpts().CPlusPlus
6117                ? diag::err_typecheck_pointer_arith_void_type
6118                : diag::ext_gnu_void_ptr)
6119    << 1 /* two pointers */ << LHSExpr->getSourceRange()
6120                            << RHSExpr->getSourceRange();
6121}
6122
6123/// \brief Diagnose invalid arithmetic on a void pointer.
6124static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6125                                            Expr *Pointer) {
6126  S.Diag(Loc, S.getLangOpts().CPlusPlus
6127                ? diag::err_typecheck_pointer_arith_void_type
6128                : diag::ext_gnu_void_ptr)
6129    << 0 /* one pointer */ << Pointer->getSourceRange();
6130}
6131
6132/// \brief Diagnose invalid arithmetic on two function pointers.
6133static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6134                                                    Expr *LHS, Expr *RHS) {
6135  assert(LHS->getType()->isAnyPointerType());
6136  assert(RHS->getType()->isAnyPointerType());
6137  S.Diag(Loc, S.getLangOpts().CPlusPlus
6138                ? diag::err_typecheck_pointer_arith_function_type
6139                : diag::ext_gnu_ptr_func_arith)
6140    << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6141    // We only show the second type if it differs from the first.
6142    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6143                                                   RHS->getType())
6144    << RHS->getType()->getPointeeType()
6145    << LHS->getSourceRange() << RHS->getSourceRange();
6146}
6147
6148/// \brief Diagnose invalid arithmetic on a function pointer.
6149static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6150                                                Expr *Pointer) {
6151  assert(Pointer->getType()->isAnyPointerType());
6152  S.Diag(Loc, S.getLangOpts().CPlusPlus
6153                ? diag::err_typecheck_pointer_arith_function_type
6154                : diag::ext_gnu_ptr_func_arith)
6155    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6156    << 0 /* one pointer, so only one type */
6157    << Pointer->getSourceRange();
6158}
6159
6160/// \brief Emit error if Operand is incomplete pointer type
6161///
6162/// \returns True if pointer has incomplete type
6163static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6164                                                 Expr *Operand) {
6165  if ((Operand->getType()->isPointerType() &&
6166       !Operand->getType()->isDependentType()) ||
6167      Operand->getType()->isObjCObjectPointerType()) {
6168    QualType PointeeTy = Operand->getType()->getPointeeType();
6169    if (S.RequireCompleteType(
6170          Loc, PointeeTy,
6171          diag::err_typecheck_arithmetic_incomplete_type,
6172          PointeeTy, Operand->getSourceRange()))
6173      return true;
6174  }
6175  return false;
6176}
6177
6178/// \brief Check the validity of an arithmetic pointer operand.
6179///
6180/// If the operand has pointer type, this code will check for pointer types
6181/// which are invalid in arithmetic operations. These will be diagnosed
6182/// appropriately, including whether or not the use is supported as an
6183/// extension.
6184///
6185/// \returns True when the operand is valid to use (even if as an extension).
6186static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6187                                            Expr *Operand) {
6188  if (!Operand->getType()->isAnyPointerType()) return true;
6189
6190  QualType PointeeTy = Operand->getType()->getPointeeType();
6191  if (PointeeTy->isVoidType()) {
6192    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6193    return !S.getLangOpts().CPlusPlus;
6194  }
6195  if (PointeeTy->isFunctionType()) {
6196    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6197    return !S.getLangOpts().CPlusPlus;
6198  }
6199
6200  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6201
6202  return true;
6203}
6204
6205/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6206/// operands.
6207///
6208/// This routine will diagnose any invalid arithmetic on pointer operands much
6209/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6210/// for emitting a single diagnostic even for operations where both LHS and RHS
6211/// are (potentially problematic) pointers.
6212///
6213/// \returns True when the operand is valid to use (even if as an extension).
6214static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6215                                                Expr *LHSExpr, Expr *RHSExpr) {
6216  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6217  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6218  if (!isLHSPointer && !isRHSPointer) return true;
6219
6220  QualType LHSPointeeTy, RHSPointeeTy;
6221  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6222  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6223
6224  // Check for arithmetic on pointers to incomplete types.
6225  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6226  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6227  if (isLHSVoidPtr || isRHSVoidPtr) {
6228    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6229    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6230    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6231
6232    return !S.getLangOpts().CPlusPlus;
6233  }
6234
6235  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6236  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6237  if (isLHSFuncPtr || isRHSFuncPtr) {
6238    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6239    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6240                                                                RHSExpr);
6241    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6242
6243    return !S.getLangOpts().CPlusPlus;
6244  }
6245
6246  if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6247  if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
6248
6249  return true;
6250}
6251
6252/// \brief Check bad cases where we step over interface counts.
6253static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6254                                                   SourceLocation OpLoc,
6255                                                   Expr *Op) {
6256  assert(Op->getType()->isAnyPointerType());
6257  QualType PointeeTy = Op->getType()->getPointeeType();
6258  if (!PointeeTy->isObjCObjectType() || S.LangOpts.ObjCRuntime.isFragile())
6259    return true;
6260
6261  S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6262    << PointeeTy << Op->getSourceRange();
6263  return false;
6264}
6265
6266/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6267/// literal.
6268static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6269                                  Expr *LHSExpr, Expr *RHSExpr) {
6270  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6271  Expr* IndexExpr = RHSExpr;
6272  if (!StrExpr) {
6273    StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6274    IndexExpr = LHSExpr;
6275  }
6276
6277  bool IsStringPlusInt = StrExpr &&
6278      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6279  if (!IsStringPlusInt)
6280    return;
6281
6282  llvm::APSInt index;
6283  if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6284    unsigned StrLenWithNull = StrExpr->getLength() + 1;
6285    if (index.isNonNegative() &&
6286        index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6287                              index.isUnsigned()))
6288      return;
6289  }
6290
6291  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6292  Self.Diag(OpLoc, diag::warn_string_plus_int)
6293      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6294
6295  // Only print a fixit for "str" + int, not for int + "str".
6296  if (IndexExpr == RHSExpr) {
6297    SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6298    Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6299        << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6300        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6301        << FixItHint::CreateInsertion(EndLoc, "]");
6302  } else
6303    Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6304}
6305
6306/// \brief Emit error when two pointers are incompatible.
6307static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6308                                           Expr *LHSExpr, Expr *RHSExpr) {
6309  assert(LHSExpr->getType()->isAnyPointerType());
6310  assert(RHSExpr->getType()->isAnyPointerType());
6311  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6312    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6313    << RHSExpr->getSourceRange();
6314}
6315
6316QualType Sema::CheckAdditionOperands( // C99 6.5.6
6317    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6318    QualType* CompLHSTy) {
6319  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6320
6321  if (LHS.get()->getType()->isVectorType() ||
6322      RHS.get()->getType()->isVectorType()) {
6323    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6324    if (CompLHSTy) *CompLHSTy = compType;
6325    return compType;
6326  }
6327
6328  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6329  if (LHS.isInvalid() || RHS.isInvalid())
6330    return QualType();
6331
6332  // Diagnose "string literal" '+' int.
6333  if (Opc == BO_Add)
6334    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6335
6336  // handle the common case first (both operands are arithmetic).
6337  if (!compType.isNull() && compType->isArithmeticType()) {
6338    if (CompLHSTy) *CompLHSTy = compType;
6339    return compType;
6340  }
6341
6342  // Put any potential pointer into PExp
6343  Expr* PExp = LHS.get(), *IExp = RHS.get();
6344  if (IExp->getType()->isAnyPointerType())
6345    std::swap(PExp, IExp);
6346
6347  if (!PExp->getType()->isAnyPointerType())
6348    return InvalidOperands(Loc, LHS, RHS);
6349
6350  if (!IExp->getType()->isIntegerType())
6351    return InvalidOperands(Loc, LHS, RHS);
6352
6353  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6354    return QualType();
6355
6356  // Diagnose bad cases where we step over interface counts.
6357  if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6358    return QualType();
6359
6360  // Check array bounds for pointer arithemtic
6361  CheckArrayAccess(PExp, IExp);
6362
6363  if (CompLHSTy) {
6364    QualType LHSTy = Context.isPromotableBitField(LHS.get());
6365    if (LHSTy.isNull()) {
6366      LHSTy = LHS.get()->getType();
6367      if (LHSTy->isPromotableIntegerType())
6368        LHSTy = Context.getPromotedIntegerType(LHSTy);
6369    }
6370    *CompLHSTy = LHSTy;
6371  }
6372
6373  return PExp->getType();
6374}
6375
6376// C99 6.5.6
6377QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6378                                        SourceLocation Loc,
6379                                        QualType* CompLHSTy) {
6380  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6381
6382  if (LHS.get()->getType()->isVectorType() ||
6383      RHS.get()->getType()->isVectorType()) {
6384    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6385    if (CompLHSTy) *CompLHSTy = compType;
6386    return compType;
6387  }
6388
6389  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6390  if (LHS.isInvalid() || RHS.isInvalid())
6391    return QualType();
6392
6393  // Enforce type constraints: C99 6.5.6p3.
6394
6395  // Handle the common case first (both operands are arithmetic).
6396  if (!compType.isNull() && compType->isArithmeticType()) {
6397    if (CompLHSTy) *CompLHSTy = compType;
6398    return compType;
6399  }
6400
6401  // Either ptr - int   or   ptr - ptr.
6402  if (LHS.get()->getType()->isAnyPointerType()) {
6403    QualType lpointee = LHS.get()->getType()->getPointeeType();
6404
6405    // Diagnose bad cases where we step over interface counts.
6406    if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
6407      return QualType();
6408
6409    // The result type of a pointer-int computation is the pointer type.
6410    if (RHS.get()->getType()->isIntegerType()) {
6411      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6412        return QualType();
6413
6414      // Check array bounds for pointer arithemtic
6415      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6416                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6417
6418      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6419      return LHS.get()->getType();
6420    }
6421
6422    // Handle pointer-pointer subtractions.
6423    if (const PointerType *RHSPTy
6424          = RHS.get()->getType()->getAs<PointerType>()) {
6425      QualType rpointee = RHSPTy->getPointeeType();
6426
6427      if (getLangOpts().CPlusPlus) {
6428        // Pointee types must be the same: C++ [expr.add]
6429        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6430          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6431        }
6432      } else {
6433        // Pointee types must be compatible C99 6.5.6p3
6434        if (!Context.typesAreCompatible(
6435                Context.getCanonicalType(lpointee).getUnqualifiedType(),
6436                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6437          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6438          return QualType();
6439        }
6440      }
6441
6442      if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6443                                               LHS.get(), RHS.get()))
6444        return QualType();
6445
6446      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6447      return Context.getPointerDiffType();
6448    }
6449  }
6450
6451  return InvalidOperands(Loc, LHS, RHS);
6452}
6453
6454static bool isScopedEnumerationType(QualType T) {
6455  if (const EnumType *ET = dyn_cast<EnumType>(T))
6456    return ET->getDecl()->isScoped();
6457  return false;
6458}
6459
6460static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6461                                   SourceLocation Loc, unsigned Opc,
6462                                   QualType LHSType) {
6463  llvm::APSInt Right;
6464  // Check right/shifter operand
6465  if (RHS.get()->isValueDependent() ||
6466      !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6467    return;
6468
6469  if (Right.isNegative()) {
6470    S.DiagRuntimeBehavior(Loc, RHS.get(),
6471                          S.PDiag(diag::warn_shift_negative)
6472                            << RHS.get()->getSourceRange());
6473    return;
6474  }
6475  llvm::APInt LeftBits(Right.getBitWidth(),
6476                       S.Context.getTypeSize(LHS.get()->getType()));
6477  if (Right.uge(LeftBits)) {
6478    S.DiagRuntimeBehavior(Loc, RHS.get(),
6479                          S.PDiag(diag::warn_shift_gt_typewidth)
6480                            << RHS.get()->getSourceRange());
6481    return;
6482  }
6483  if (Opc != BO_Shl)
6484    return;
6485
6486  // When left shifting an ICE which is signed, we can check for overflow which
6487  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6488  // integers have defined behavior modulo one more than the maximum value
6489  // representable in the result type, so never warn for those.
6490  llvm::APSInt Left;
6491  if (LHS.get()->isValueDependent() ||
6492      !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6493      LHSType->hasUnsignedIntegerRepresentation())
6494    return;
6495  llvm::APInt ResultBits =
6496      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6497  if (LeftBits.uge(ResultBits))
6498    return;
6499  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6500  Result = Result.shl(Right);
6501
6502  // Print the bit representation of the signed integer as an unsigned
6503  // hexadecimal number.
6504  SmallString<40> HexResult;
6505  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6506
6507  // If we are only missing a sign bit, this is less likely to result in actual
6508  // bugs -- if the result is cast back to an unsigned type, it will have the
6509  // expected value. Thus we place this behind a different warning that can be
6510  // turned off separately if needed.
6511  if (LeftBits == ResultBits - 1) {
6512    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6513        << HexResult.str() << LHSType
6514        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6515    return;
6516  }
6517
6518  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6519    << HexResult.str() << Result.getMinSignedBits() << LHSType
6520    << Left.getBitWidth() << LHS.get()->getSourceRange()
6521    << RHS.get()->getSourceRange();
6522}
6523
6524// C99 6.5.7
6525QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6526                                  SourceLocation Loc, unsigned Opc,
6527                                  bool IsCompAssign) {
6528  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6529
6530  // C99 6.5.7p2: Each of the operands shall have integer type.
6531  if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6532      !RHS.get()->getType()->hasIntegerRepresentation())
6533    return InvalidOperands(Loc, LHS, RHS);
6534
6535  // C++0x: Don't allow scoped enums. FIXME: Use something better than
6536  // hasIntegerRepresentation() above instead of this.
6537  if (isScopedEnumerationType(LHS.get()->getType()) ||
6538      isScopedEnumerationType(RHS.get()->getType())) {
6539    return InvalidOperands(Loc, LHS, RHS);
6540  }
6541
6542  // Vector shifts promote their scalar inputs to vector type.
6543  if (LHS.get()->getType()->isVectorType() ||
6544      RHS.get()->getType()->isVectorType())
6545    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6546
6547  // Shifts don't perform usual arithmetic conversions, they just do integer
6548  // promotions on each operand. C99 6.5.7p3
6549
6550  // For the LHS, do usual unary conversions, but then reset them away
6551  // if this is a compound assignment.
6552  ExprResult OldLHS = LHS;
6553  LHS = UsualUnaryConversions(LHS.take());
6554  if (LHS.isInvalid())
6555    return QualType();
6556  QualType LHSType = LHS.get()->getType();
6557  if (IsCompAssign) LHS = OldLHS;
6558
6559  // The RHS is simpler.
6560  RHS = UsualUnaryConversions(RHS.take());
6561  if (RHS.isInvalid())
6562    return QualType();
6563
6564  // Sanity-check shift operands
6565  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6566
6567  // "The type of the result is that of the promoted left operand."
6568  return LHSType;
6569}
6570
6571static bool IsWithinTemplateSpecialization(Decl *D) {
6572  if (DeclContext *DC = D->getDeclContext()) {
6573    if (isa<ClassTemplateSpecializationDecl>(DC))
6574      return true;
6575    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6576      return FD->isFunctionTemplateSpecialization();
6577  }
6578  return false;
6579}
6580
6581/// If two different enums are compared, raise a warning.
6582static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6583                                ExprResult &RHS) {
6584  QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6585  QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6586
6587  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6588  if (!LHSEnumType)
6589    return;
6590  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6591  if (!RHSEnumType)
6592    return;
6593
6594  // Ignore anonymous enums.
6595  if (!LHSEnumType->getDecl()->getIdentifier())
6596    return;
6597  if (!RHSEnumType->getDecl()->getIdentifier())
6598    return;
6599
6600  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6601    return;
6602
6603  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6604      << LHSStrippedType << RHSStrippedType
6605      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6606}
6607
6608/// \brief Diagnose bad pointer comparisons.
6609static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6610                                              ExprResult &LHS, ExprResult &RHS,
6611                                              bool IsError) {
6612  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6613                      : diag::ext_typecheck_comparison_of_distinct_pointers)
6614    << LHS.get()->getType() << RHS.get()->getType()
6615    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6616}
6617
6618/// \brief Returns false if the pointers are converted to a composite type,
6619/// true otherwise.
6620static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6621                                           ExprResult &LHS, ExprResult &RHS) {
6622  // C++ [expr.rel]p2:
6623  //   [...] Pointer conversions (4.10) and qualification
6624  //   conversions (4.4) are performed on pointer operands (or on
6625  //   a pointer operand and a null pointer constant) to bring
6626  //   them to their composite pointer type. [...]
6627  //
6628  // C++ [expr.eq]p1 uses the same notion for (in)equality
6629  // comparisons of pointers.
6630
6631  // C++ [expr.eq]p2:
6632  //   In addition, pointers to members can be compared, or a pointer to
6633  //   member and a null pointer constant. Pointer to member conversions
6634  //   (4.11) and qualification conversions (4.4) are performed to bring
6635  //   them to a common type. If one operand is a null pointer constant,
6636  //   the common type is the type of the other operand. Otherwise, the
6637  //   common type is a pointer to member type similar (4.4) to the type
6638  //   of one of the operands, with a cv-qualification signature (4.4)
6639  //   that is the union of the cv-qualification signatures of the operand
6640  //   types.
6641
6642  QualType LHSType = LHS.get()->getType();
6643  QualType RHSType = RHS.get()->getType();
6644  assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6645         (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6646
6647  bool NonStandardCompositeType = false;
6648  bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6649  QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6650  if (T.isNull()) {
6651    diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6652    return true;
6653  }
6654
6655  if (NonStandardCompositeType)
6656    S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6657      << LHSType << RHSType << T << LHS.get()->getSourceRange()
6658      << RHS.get()->getSourceRange();
6659
6660  LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6661  RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6662  return false;
6663}
6664
6665static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6666                                                    ExprResult &LHS,
6667                                                    ExprResult &RHS,
6668                                                    bool IsError) {
6669  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6670                      : diag::ext_typecheck_comparison_of_fptr_to_void)
6671    << LHS.get()->getType() << RHS.get()->getType()
6672    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6673}
6674
6675static bool isObjCObjectLiteral(ExprResult &E) {
6676  switch (E.get()->getStmtClass()) {
6677  case Stmt::ObjCArrayLiteralClass:
6678  case Stmt::ObjCDictionaryLiteralClass:
6679  case Stmt::ObjCStringLiteralClass:
6680  case Stmt::ObjCBoxedExprClass:
6681    return true;
6682  default:
6683    // Note that ObjCBoolLiteral is NOT an object literal!
6684    return false;
6685  }
6686}
6687
6688static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6689                                                       SourceLocation Loc,
6690                                                       ExprResult &LHS,
6691                                                       ExprResult &RHS,
6692                                                       bool CanFix = false) {
6693  Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6694
6695  unsigned LiteralKind;
6696  switch (Literal->getStmtClass()) {
6697  case Stmt::ObjCStringLiteralClass:
6698    // "string literal"
6699    LiteralKind = 0;
6700    break;
6701  case Stmt::ObjCArrayLiteralClass:
6702    // "array literal"
6703    LiteralKind = 1;
6704    break;
6705  case Stmt::ObjCDictionaryLiteralClass:
6706    // "dictionary literal"
6707    LiteralKind = 2;
6708    break;
6709  case Stmt::ObjCBoxedExprClass: {
6710    Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6711    switch (Inner->getStmtClass()) {
6712    case Stmt::IntegerLiteralClass:
6713    case Stmt::FloatingLiteralClass:
6714    case Stmt::CharacterLiteralClass:
6715    case Stmt::ObjCBoolLiteralExprClass:
6716    case Stmt::CXXBoolLiteralExprClass:
6717      // "numeric literal"
6718      LiteralKind = 3;
6719      break;
6720    case Stmt::ImplicitCastExprClass: {
6721      CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6722      // Boolean literals can be represented by implicit casts.
6723      if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6724        LiteralKind = 3;
6725        break;
6726      }
6727      // FALLTHROUGH
6728    }
6729    default:
6730      // "boxed expression"
6731      LiteralKind = 4;
6732      break;
6733    }
6734    break;
6735  }
6736  default:
6737    llvm_unreachable("Unknown Objective-C object literal kind");
6738  }
6739
6740  return S.Diag(Loc, diag::err_objc_literal_comparison)
6741           << LiteralKind << CanFix << Literal->getSourceRange();
6742}
6743
6744static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6745                                           ExprResult &LHS,
6746                                           ExprResult &RHS,
6747                                           BinaryOperatorKind Op) {
6748  assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6749
6750  // Get the LHS object's interface type.
6751  QualType Type = LHS.get()->getType();
6752  QualType InterfaceType;
6753  if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6754    InterfaceType = PTy->getPointeeType();
6755    if (const ObjCObjectType *iQFaceTy =
6756        InterfaceType->getAsObjCQualifiedInterfaceType())
6757      InterfaceType = iQFaceTy->getBaseType();
6758  } else {
6759    // If this is not actually an Objective-C object, bail out.
6760    return ExprEmpty();
6761  }
6762
6763  // If the RHS isn't an Objective-C object, bail out.
6764  if (!RHS.get()->getType()->isObjCObjectPointerType())
6765    return ExprEmpty();
6766
6767  // Try to find the -isEqual: method.
6768  Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6769  ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6770                                                      InterfaceType,
6771                                                      /*instance=*/true);
6772  bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6773
6774  if (!Method && ReceiverIsId) {
6775    Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6776                                                /*receiverId=*/true,
6777                                                /*warn=*/false);
6778  }
6779
6780  if (!Method)
6781    return ExprEmpty();
6782
6783  QualType T = Method->param_begin()[0]->getType();
6784  if (!T->isObjCObjectPointerType())
6785    return ExprEmpty();
6786
6787  QualType R = Method->getResultType();
6788  if (!R->isScalarType())
6789    return ExprEmpty();
6790
6791  // At this point we know we have a good -isEqual: method.
6792  // Emit the diagnostic and fixit.
6793  DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6794                                                         LHS, RHS, true);
6795
6796  Expr *LHSExpr = LHS.take();
6797  Expr *RHSExpr = RHS.take();
6798
6799  SourceLocation Start = LHSExpr->getLocStart();
6800  SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6801  SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6802
6803  Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6804       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6805       << FixItHint::CreateInsertion(End, "]");
6806
6807  // Finally, build the call to -isEqual: (and possible logical not).
6808  ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6809                                           /*SuperLoc=*/SourceLocation(),
6810                                           IsEqualSel, Method,
6811                                           OpLoc, OpLoc, OpLoc,
6812                                           MultiExprArg(S, &RHSExpr, 1),
6813                                           /*isImplicit=*/false);
6814
6815  ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6816
6817  if (Op == BO_NE)
6818    return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6819  return CallCond;
6820}
6821
6822// C99 6.5.8, C++ [expr.rel]
6823QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6824                                    SourceLocation Loc, unsigned OpaqueOpc,
6825                                    bool IsRelational) {
6826  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6827
6828  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6829
6830  // Handle vector comparisons separately.
6831  if (LHS.get()->getType()->isVectorType() ||
6832      RHS.get()->getType()->isVectorType())
6833    return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6834
6835  QualType LHSType = LHS.get()->getType();
6836  QualType RHSType = RHS.get()->getType();
6837
6838  Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6839  Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6840
6841  checkEnumComparison(*this, Loc, LHS, RHS);
6842
6843  if (!LHSType->hasFloatingRepresentation() &&
6844      !(LHSType->isBlockPointerType() && IsRelational) &&
6845      !LHS.get()->getLocStart().isMacroID() &&
6846      !RHS.get()->getLocStart().isMacroID()) {
6847    // For non-floating point types, check for self-comparisons of the form
6848    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6849    // often indicate logic errors in the program.
6850    //
6851    // NOTE: Don't warn about comparison expressions resulting from macro
6852    // expansion. Also don't warn about comparisons which are only self
6853    // comparisons within a template specialization. The warnings should catch
6854    // obvious cases in the definition of the template anyways. The idea is to
6855    // warn when the typed comparison operator will always evaluate to the same
6856    // result.
6857    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6858      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6859        if (DRL->getDecl() == DRR->getDecl() &&
6860            !IsWithinTemplateSpecialization(DRL->getDecl())) {
6861          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6862                              << 0 // self-
6863                              << (Opc == BO_EQ
6864                                  || Opc == BO_LE
6865                                  || Opc == BO_GE));
6866        } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6867                   !DRL->getDecl()->getType()->isReferenceType() &&
6868                   !DRR->getDecl()->getType()->isReferenceType()) {
6869            // what is it always going to eval to?
6870            char always_evals_to;
6871            switch(Opc) {
6872            case BO_EQ: // e.g. array1 == array2
6873              always_evals_to = 0; // false
6874              break;
6875            case BO_NE: // e.g. array1 != array2
6876              always_evals_to = 1; // true
6877              break;
6878            default:
6879              // best we can say is 'a constant'
6880              always_evals_to = 2; // e.g. array1 <= array2
6881              break;
6882            }
6883            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6884                                << 1 // array
6885                                << always_evals_to);
6886        }
6887      }
6888    }
6889
6890    if (isa<CastExpr>(LHSStripped))
6891      LHSStripped = LHSStripped->IgnoreParenCasts();
6892    if (isa<CastExpr>(RHSStripped))
6893      RHSStripped = RHSStripped->IgnoreParenCasts();
6894
6895    // Warn about comparisons against a string constant (unless the other
6896    // operand is null), the user probably wants strcmp.
6897    Expr *literalString = 0;
6898    Expr *literalStringStripped = 0;
6899    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6900        !RHSStripped->isNullPointerConstant(Context,
6901                                            Expr::NPC_ValueDependentIsNull)) {
6902      literalString = LHS.get();
6903      literalStringStripped = LHSStripped;
6904    } else if ((isa<StringLiteral>(RHSStripped) ||
6905                isa<ObjCEncodeExpr>(RHSStripped)) &&
6906               !LHSStripped->isNullPointerConstant(Context,
6907                                            Expr::NPC_ValueDependentIsNull)) {
6908      literalString = RHS.get();
6909      literalStringStripped = RHSStripped;
6910    }
6911
6912    if (literalString) {
6913      std::string resultComparison;
6914      switch (Opc) {
6915      case BO_LT: resultComparison = ") < 0"; break;
6916      case BO_GT: resultComparison = ") > 0"; break;
6917      case BO_LE: resultComparison = ") <= 0"; break;
6918      case BO_GE: resultComparison = ") >= 0"; break;
6919      case BO_EQ: resultComparison = ") == 0"; break;
6920      case BO_NE: resultComparison = ") != 0"; break;
6921      default: llvm_unreachable("Invalid comparison operator");
6922      }
6923
6924      DiagRuntimeBehavior(Loc, 0,
6925        PDiag(diag::warn_stringcompare)
6926          << isa<ObjCEncodeExpr>(literalStringStripped)
6927          << literalString->getSourceRange());
6928    }
6929  }
6930
6931  // C99 6.5.8p3 / C99 6.5.9p4
6932  if (LHS.get()->getType()->isArithmeticType() &&
6933      RHS.get()->getType()->isArithmeticType()) {
6934    UsualArithmeticConversions(LHS, RHS);
6935    if (LHS.isInvalid() || RHS.isInvalid())
6936      return QualType();
6937  }
6938  else {
6939    LHS = UsualUnaryConversions(LHS.take());
6940    if (LHS.isInvalid())
6941      return QualType();
6942
6943    RHS = UsualUnaryConversions(RHS.take());
6944    if (RHS.isInvalid())
6945      return QualType();
6946  }
6947
6948  LHSType = LHS.get()->getType();
6949  RHSType = RHS.get()->getType();
6950
6951  // The result of comparisons is 'bool' in C++, 'int' in C.
6952  QualType ResultTy = Context.getLogicalOperationType();
6953
6954  if (IsRelational) {
6955    if (LHSType->isRealType() && RHSType->isRealType())
6956      return ResultTy;
6957  } else {
6958    // Check for comparisons of floating point operands using != and ==.
6959    if (LHSType->hasFloatingRepresentation())
6960      CheckFloatComparison(Loc, LHS.get(), RHS.get());
6961
6962    if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
6963      return ResultTy;
6964  }
6965
6966  bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
6967                                              Expr::NPC_ValueDependentIsNull);
6968  bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
6969                                              Expr::NPC_ValueDependentIsNull);
6970
6971  // All of the following pointer-related warnings are GCC extensions, except
6972  // when handling null pointer constants.
6973  if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
6974    QualType LCanPointeeTy =
6975      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6976    QualType RCanPointeeTy =
6977      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6978
6979    if (getLangOpts().CPlusPlus) {
6980      if (LCanPointeeTy == RCanPointeeTy)
6981        return ResultTy;
6982      if (!IsRelational &&
6983          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6984        // Valid unless comparison between non-null pointer and function pointer
6985        // This is a gcc extension compatibility comparison.
6986        // In a SFINAE context, we treat this as a hard error to maintain
6987        // conformance with the C++ standard.
6988        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6989            && !LHSIsNull && !RHSIsNull) {
6990          diagnoseFunctionPointerToVoidComparison(
6991              *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
6992
6993          if (isSFINAEContext())
6994            return QualType();
6995
6996          RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6997          return ResultTy;
6998        }
6999      }
7000
7001      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7002        return QualType();
7003      else
7004        return ResultTy;
7005    }
7006    // C99 6.5.9p2 and C99 6.5.8p2
7007    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7008                                   RCanPointeeTy.getUnqualifiedType())) {
7009      // Valid unless a relational comparison of function pointers
7010      if (IsRelational && LCanPointeeTy->isFunctionType()) {
7011        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7012          << LHSType << RHSType << LHS.get()->getSourceRange()
7013          << RHS.get()->getSourceRange();
7014      }
7015    } else if (!IsRelational &&
7016               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7017      // Valid unless comparison between non-null pointer and function pointer
7018      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7019          && !LHSIsNull && !RHSIsNull)
7020        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7021                                                /*isError*/false);
7022    } else {
7023      // Invalid
7024      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7025    }
7026    if (LCanPointeeTy != RCanPointeeTy) {
7027      if (LHSIsNull && !RHSIsNull)
7028        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7029      else
7030        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7031    }
7032    return ResultTy;
7033  }
7034
7035  if (getLangOpts().CPlusPlus) {
7036    // Comparison of nullptr_t with itself.
7037    if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7038      return ResultTy;
7039
7040    // Comparison of pointers with null pointer constants and equality
7041    // comparisons of member pointers to null pointer constants.
7042    if (RHSIsNull &&
7043        ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7044         (!IsRelational &&
7045          (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7046      RHS = ImpCastExprToType(RHS.take(), LHSType,
7047                        LHSType->isMemberPointerType()
7048                          ? CK_NullToMemberPointer
7049                          : CK_NullToPointer);
7050      return ResultTy;
7051    }
7052    if (LHSIsNull &&
7053        ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7054         (!IsRelational &&
7055          (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7056      LHS = ImpCastExprToType(LHS.take(), RHSType,
7057                        RHSType->isMemberPointerType()
7058                          ? CK_NullToMemberPointer
7059                          : CK_NullToPointer);
7060      return ResultTy;
7061    }
7062
7063    // Comparison of member pointers.
7064    if (!IsRelational &&
7065        LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7066      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7067        return QualType();
7068      else
7069        return ResultTy;
7070    }
7071
7072    // Handle scoped enumeration types specifically, since they don't promote
7073    // to integers.
7074    if (LHS.get()->getType()->isEnumeralType() &&
7075        Context.hasSameUnqualifiedType(LHS.get()->getType(),
7076                                       RHS.get()->getType()))
7077      return ResultTy;
7078  }
7079
7080  // Handle block pointer types.
7081  if (!IsRelational && LHSType->isBlockPointerType() &&
7082      RHSType->isBlockPointerType()) {
7083    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7084    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7085
7086    if (!LHSIsNull && !RHSIsNull &&
7087        !Context.typesAreCompatible(lpointee, rpointee)) {
7088      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7089        << LHSType << RHSType << LHS.get()->getSourceRange()
7090        << RHS.get()->getSourceRange();
7091    }
7092    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7093    return ResultTy;
7094  }
7095
7096  // Allow block pointers to be compared with null pointer constants.
7097  if (!IsRelational
7098      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7099          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7100    if (!LHSIsNull && !RHSIsNull) {
7101      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7102             ->getPointeeType()->isVoidType())
7103            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7104                ->getPointeeType()->isVoidType())))
7105        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7106          << LHSType << RHSType << LHS.get()->getSourceRange()
7107          << RHS.get()->getSourceRange();
7108    }
7109    if (LHSIsNull && !RHSIsNull)
7110      LHS = ImpCastExprToType(LHS.take(), RHSType,
7111                              RHSType->isPointerType() ? CK_BitCast
7112                                : CK_AnyPointerToBlockPointerCast);
7113    else
7114      RHS = ImpCastExprToType(RHS.take(), LHSType,
7115                              LHSType->isPointerType() ? CK_BitCast
7116                                : CK_AnyPointerToBlockPointerCast);
7117    return ResultTy;
7118  }
7119
7120  if (LHSType->isObjCObjectPointerType() ||
7121      RHSType->isObjCObjectPointerType()) {
7122    const PointerType *LPT = LHSType->getAs<PointerType>();
7123    const PointerType *RPT = RHSType->getAs<PointerType>();
7124    if (LPT || RPT) {
7125      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7126      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7127
7128      if (!LPtrToVoid && !RPtrToVoid &&
7129          !Context.typesAreCompatible(LHSType, RHSType)) {
7130        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7131                                          /*isError*/false);
7132      }
7133      if (LHSIsNull && !RHSIsNull)
7134        LHS = ImpCastExprToType(LHS.take(), RHSType,
7135                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7136      else
7137        RHS = ImpCastExprToType(RHS.take(), LHSType,
7138                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7139      return ResultTy;
7140    }
7141    if (LHSType->isObjCObjectPointerType() &&
7142        RHSType->isObjCObjectPointerType()) {
7143      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7144        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7145                                          /*isError*/false);
7146      if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7147        diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7148
7149      if (LHSIsNull && !RHSIsNull)
7150        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7151      else
7152        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7153      return ResultTy;
7154    }
7155  }
7156  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7157      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7158    unsigned DiagID = 0;
7159    bool isError = false;
7160    if ((LHSIsNull && LHSType->isIntegerType()) ||
7161        (RHSIsNull && RHSType->isIntegerType())) {
7162      if (IsRelational && !getLangOpts().CPlusPlus)
7163        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7164    } else if (IsRelational && !getLangOpts().CPlusPlus)
7165      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7166    else if (getLangOpts().CPlusPlus) {
7167      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7168      isError = true;
7169    } else
7170      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7171
7172    if (DiagID) {
7173      Diag(Loc, DiagID)
7174        << LHSType << RHSType << LHS.get()->getSourceRange()
7175        << RHS.get()->getSourceRange();
7176      if (isError)
7177        return QualType();
7178    }
7179
7180    if (LHSType->isIntegerType())
7181      LHS = ImpCastExprToType(LHS.take(), RHSType,
7182                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7183    else
7184      RHS = ImpCastExprToType(RHS.take(), LHSType,
7185                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7186    return ResultTy;
7187  }
7188
7189  // Handle block pointers.
7190  if (!IsRelational && RHSIsNull
7191      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7192    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7193    return ResultTy;
7194  }
7195  if (!IsRelational && LHSIsNull
7196      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7197    LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7198    return ResultTy;
7199  }
7200
7201  return InvalidOperands(Loc, LHS, RHS);
7202}
7203
7204
7205// Return a signed type that is of identical size and number of elements.
7206// For floating point vectors, return an integer type of identical size
7207// and number of elements.
7208QualType Sema::GetSignedVectorType(QualType V) {
7209  const VectorType *VTy = V->getAs<VectorType>();
7210  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7211  if (TypeSize == Context.getTypeSize(Context.CharTy))
7212    return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7213  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7214    return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7215  else if (TypeSize == Context.getTypeSize(Context.IntTy))
7216    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7217  else if (TypeSize == Context.getTypeSize(Context.LongTy))
7218    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7219  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7220         "Unhandled vector element size in vector compare");
7221  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7222}
7223
7224/// CheckVectorCompareOperands - vector comparisons are a clang extension that
7225/// operates on extended vector types.  Instead of producing an IntTy result,
7226/// like a scalar comparison, a vector comparison produces a vector of integer
7227/// types.
7228QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7229                                          SourceLocation Loc,
7230                                          bool IsRelational) {
7231  // Check to make sure we're operating on vectors of the same type and width,
7232  // Allowing one side to be a scalar of element type.
7233  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7234  if (vType.isNull())
7235    return vType;
7236
7237  QualType LHSType = LHS.get()->getType();
7238
7239  // If AltiVec, the comparison results in a numeric type, i.e.
7240  // bool for C++, int for C
7241  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7242    return Context.getLogicalOperationType();
7243
7244  // For non-floating point types, check for self-comparisons of the form
7245  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7246  // often indicate logic errors in the program.
7247  if (!LHSType->hasFloatingRepresentation()) {
7248    if (DeclRefExpr* DRL
7249          = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7250      if (DeclRefExpr* DRR
7251            = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7252        if (DRL->getDecl() == DRR->getDecl())
7253          DiagRuntimeBehavior(Loc, 0,
7254                              PDiag(diag::warn_comparison_always)
7255                                << 0 // self-
7256                                << 2 // "a constant"
7257                              );
7258  }
7259
7260  // Check for comparisons of floating point operands using != and ==.
7261  if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7262    assert (RHS.get()->getType()->hasFloatingRepresentation());
7263    CheckFloatComparison(Loc, LHS.get(), RHS.get());
7264  }
7265
7266  // Return a signed type for the vector.
7267  return GetSignedVectorType(LHSType);
7268}
7269
7270QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7271                                          SourceLocation Loc) {
7272  // Ensure that either both operands are of the same vector type, or
7273  // one operand is of a vector type and the other is of its element type.
7274  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7275  if (vType.isNull() || vType->isFloatingType())
7276    return InvalidOperands(Loc, LHS, RHS);
7277
7278  return GetSignedVectorType(LHS.get()->getType());
7279}
7280
7281inline QualType Sema::CheckBitwiseOperands(
7282  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7283  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7284
7285  if (LHS.get()->getType()->isVectorType() ||
7286      RHS.get()->getType()->isVectorType()) {
7287    if (LHS.get()->getType()->hasIntegerRepresentation() &&
7288        RHS.get()->getType()->hasIntegerRepresentation())
7289      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7290
7291    return InvalidOperands(Loc, LHS, RHS);
7292  }
7293
7294  ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7295  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7296                                                 IsCompAssign);
7297  if (LHSResult.isInvalid() || RHSResult.isInvalid())
7298    return QualType();
7299  LHS = LHSResult.take();
7300  RHS = RHSResult.take();
7301
7302  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7303    return compType;
7304  return InvalidOperands(Loc, LHS, RHS);
7305}
7306
7307inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7308  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7309
7310  // Check vector operands differently.
7311  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7312    return CheckVectorLogicalOperands(LHS, RHS, Loc);
7313
7314  // Diagnose cases where the user write a logical and/or but probably meant a
7315  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7316  // is a constant.
7317  if (LHS.get()->getType()->isIntegerType() &&
7318      !LHS.get()->getType()->isBooleanType() &&
7319      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7320      // Don't warn in macros or template instantiations.
7321      !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7322    // If the RHS can be constant folded, and if it constant folds to something
7323    // that isn't 0 or 1 (which indicate a potential logical operation that
7324    // happened to fold to true/false) then warn.
7325    // Parens on the RHS are ignored.
7326    llvm::APSInt Result;
7327    if (RHS.get()->EvaluateAsInt(Result, Context))
7328      if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7329          (Result != 0 && Result != 1)) {
7330        Diag(Loc, diag::warn_logical_instead_of_bitwise)
7331          << RHS.get()->getSourceRange()
7332          << (Opc == BO_LAnd ? "&&" : "||");
7333        // Suggest replacing the logical operator with the bitwise version
7334        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7335            << (Opc == BO_LAnd ? "&" : "|")
7336            << FixItHint::CreateReplacement(SourceRange(
7337                Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7338                                                getLangOpts())),
7339                                            Opc == BO_LAnd ? "&" : "|");
7340        if (Opc == BO_LAnd)
7341          // Suggest replacing "Foo() && kNonZero" with "Foo()"
7342          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7343              << FixItHint::CreateRemoval(
7344                  SourceRange(
7345                      Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7346                                                 0, getSourceManager(),
7347                                                 getLangOpts()),
7348                      RHS.get()->getLocEnd()));
7349      }
7350  }
7351
7352  if (!Context.getLangOpts().CPlusPlus) {
7353    LHS = UsualUnaryConversions(LHS.take());
7354    if (LHS.isInvalid())
7355      return QualType();
7356
7357    RHS = UsualUnaryConversions(RHS.take());
7358    if (RHS.isInvalid())
7359      return QualType();
7360
7361    if (!LHS.get()->getType()->isScalarType() ||
7362        !RHS.get()->getType()->isScalarType())
7363      return InvalidOperands(Loc, LHS, RHS);
7364
7365    return Context.IntTy;
7366  }
7367
7368  // The following is safe because we only use this method for
7369  // non-overloadable operands.
7370
7371  // C++ [expr.log.and]p1
7372  // C++ [expr.log.or]p1
7373  // The operands are both contextually converted to type bool.
7374  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7375  if (LHSRes.isInvalid())
7376    return InvalidOperands(Loc, LHS, RHS);
7377  LHS = move(LHSRes);
7378
7379  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7380  if (RHSRes.isInvalid())
7381    return InvalidOperands(Loc, LHS, RHS);
7382  RHS = move(RHSRes);
7383
7384  // C++ [expr.log.and]p2
7385  // C++ [expr.log.or]p2
7386  // The result is a bool.
7387  return Context.BoolTy;
7388}
7389
7390/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7391/// is a read-only property; return true if so. A readonly property expression
7392/// depends on various declarations and thus must be treated specially.
7393///
7394static bool IsReadonlyProperty(Expr *E, Sema &S) {
7395  const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7396  if (!PropExpr) return false;
7397  if (PropExpr->isImplicitProperty()) return false;
7398
7399  ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7400  QualType BaseType = PropExpr->isSuperReceiver() ?
7401                            PropExpr->getSuperReceiverType() :
7402                            PropExpr->getBase()->getType();
7403
7404  if (const ObjCObjectPointerType *OPT =
7405      BaseType->getAsObjCInterfacePointerType())
7406    if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7407      if (S.isPropertyReadonly(PDecl, IFace))
7408        return true;
7409  return false;
7410}
7411
7412static bool IsReadonlyMessage(Expr *E, Sema &S) {
7413  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7414  if (!ME) return false;
7415  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7416  ObjCMessageExpr *Base =
7417    dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7418  if (!Base) return false;
7419  return Base->getMethodDecl() != 0;
7420}
7421
7422/// Is the given expression (which must be 'const') a reference to a
7423/// variable which was originally non-const, but which has become
7424/// 'const' due to being captured within a block?
7425enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7426static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7427  assert(E->isLValue() && E->getType().isConstQualified());
7428  E = E->IgnoreParens();
7429
7430  // Must be a reference to a declaration from an enclosing scope.
7431  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7432  if (!DRE) return NCCK_None;
7433  if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7434
7435  // The declaration must be a variable which is not declared 'const'.
7436  VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7437  if (!var) return NCCK_None;
7438  if (var->getType().isConstQualified()) return NCCK_None;
7439  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7440
7441  // Decide whether the first capture was for a block or a lambda.
7442  DeclContext *DC = S.CurContext;
7443  while (DC->getParent() != var->getDeclContext())
7444    DC = DC->getParent();
7445  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7446}
7447
7448/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7449/// emit an error and return true.  If so, return false.
7450static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7451  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7452  SourceLocation OrigLoc = Loc;
7453  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7454                                                              &Loc);
7455  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7456    IsLV = Expr::MLV_ReadonlyProperty;
7457  else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7458    IsLV = Expr::MLV_InvalidMessageExpression;
7459  if (IsLV == Expr::MLV_Valid)
7460    return false;
7461
7462  unsigned Diag = 0;
7463  bool NeedType = false;
7464  switch (IsLV) { // C99 6.5.16p2
7465  case Expr::MLV_ConstQualified:
7466    Diag = diag::err_typecheck_assign_const;
7467
7468    // Use a specialized diagnostic when we're assigning to an object
7469    // from an enclosing function or block.
7470    if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7471      if (NCCK == NCCK_Block)
7472        Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7473      else
7474        Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7475      break;
7476    }
7477
7478    // In ARC, use some specialized diagnostics for occasions where we
7479    // infer 'const'.  These are always pseudo-strong variables.
7480    if (S.getLangOpts().ObjCAutoRefCount) {
7481      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7482      if (declRef && isa<VarDecl>(declRef->getDecl())) {
7483        VarDecl *var = cast<VarDecl>(declRef->getDecl());
7484
7485        // Use the normal diagnostic if it's pseudo-__strong but the
7486        // user actually wrote 'const'.
7487        if (var->isARCPseudoStrong() &&
7488            (!var->getTypeSourceInfo() ||
7489             !var->getTypeSourceInfo()->getType().isConstQualified())) {
7490          // There are two pseudo-strong cases:
7491          //  - self
7492          ObjCMethodDecl *method = S.getCurMethodDecl();
7493          if (method && var == method->getSelfDecl())
7494            Diag = method->isClassMethod()
7495              ? diag::err_typecheck_arc_assign_self_class_method
7496              : diag::err_typecheck_arc_assign_self;
7497
7498          //  - fast enumeration variables
7499          else
7500            Diag = diag::err_typecheck_arr_assign_enumeration;
7501
7502          SourceRange Assign;
7503          if (Loc != OrigLoc)
7504            Assign = SourceRange(OrigLoc, OrigLoc);
7505          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7506          // We need to preserve the AST regardless, so migration tool
7507          // can do its job.
7508          return false;
7509        }
7510      }
7511    }
7512
7513    break;
7514  case Expr::MLV_ArrayType:
7515  case Expr::MLV_ArrayTemporary:
7516    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7517    NeedType = true;
7518    break;
7519  case Expr::MLV_NotObjectType:
7520    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7521    NeedType = true;
7522    break;
7523  case Expr::MLV_LValueCast:
7524    Diag = diag::err_typecheck_lvalue_casts_not_supported;
7525    break;
7526  case Expr::MLV_Valid:
7527    llvm_unreachable("did not take early return for MLV_Valid");
7528  case Expr::MLV_InvalidExpression:
7529  case Expr::MLV_MemberFunction:
7530  case Expr::MLV_ClassTemporary:
7531    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7532    break;
7533  case Expr::MLV_IncompleteType:
7534  case Expr::MLV_IncompleteVoidType:
7535    return S.RequireCompleteType(Loc, E->getType(),
7536             diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7537  case Expr::MLV_DuplicateVectorComponents:
7538    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7539    break;
7540  case Expr::MLV_ReadonlyProperty:
7541  case Expr::MLV_NoSetterProperty:
7542    llvm_unreachable("readonly properties should be processed differently");
7543  case Expr::MLV_InvalidMessageExpression:
7544    Diag = diag::error_readonly_message_assignment;
7545    break;
7546  case Expr::MLV_SubObjCPropertySetting:
7547    Diag = diag::error_no_subobject_property_setting;
7548    break;
7549  }
7550
7551  SourceRange Assign;
7552  if (Loc != OrigLoc)
7553    Assign = SourceRange(OrigLoc, OrigLoc);
7554  if (NeedType)
7555    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7556  else
7557    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7558  return true;
7559}
7560
7561
7562
7563// C99 6.5.16.1
7564QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7565                                       SourceLocation Loc,
7566                                       QualType CompoundType) {
7567  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7568
7569  // Verify that LHS is a modifiable lvalue, and emit error if not.
7570  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7571    return QualType();
7572
7573  QualType LHSType = LHSExpr->getType();
7574  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7575                                             CompoundType;
7576  AssignConvertType ConvTy;
7577  if (CompoundType.isNull()) {
7578    QualType LHSTy(LHSType);
7579    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7580    if (RHS.isInvalid())
7581      return QualType();
7582    // Special case of NSObject attributes on c-style pointer types.
7583    if (ConvTy == IncompatiblePointer &&
7584        ((Context.isObjCNSObjectType(LHSType) &&
7585          RHSType->isObjCObjectPointerType()) ||
7586         (Context.isObjCNSObjectType(RHSType) &&
7587          LHSType->isObjCObjectPointerType())))
7588      ConvTy = Compatible;
7589
7590    if (ConvTy == Compatible &&
7591        LHSType->isObjCObjectType())
7592        Diag(Loc, diag::err_objc_object_assignment)
7593          << LHSType;
7594
7595    // If the RHS is a unary plus or minus, check to see if they = and + are
7596    // right next to each other.  If so, the user may have typo'd "x =+ 4"
7597    // instead of "x += 4".
7598    Expr *RHSCheck = RHS.get();
7599    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7600      RHSCheck = ICE->getSubExpr();
7601    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7602      if ((UO->getOpcode() == UO_Plus ||
7603           UO->getOpcode() == UO_Minus) &&
7604          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7605          // Only if the two operators are exactly adjacent.
7606          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7607          // And there is a space or other character before the subexpr of the
7608          // unary +/-.  We don't want to warn on "x=-1".
7609          Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7610          UO->getSubExpr()->getLocStart().isFileID()) {
7611        Diag(Loc, diag::warn_not_compound_assign)
7612          << (UO->getOpcode() == UO_Plus ? "+" : "-")
7613          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7614      }
7615    }
7616
7617    if (ConvTy == Compatible) {
7618      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7619        checkRetainCycles(LHSExpr, RHS.get());
7620      else if (getLangOpts().ObjCAutoRefCount)
7621        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7622    }
7623  } else {
7624    // Compound assignment "x += y"
7625    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7626  }
7627
7628  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7629                               RHS.get(), AA_Assigning))
7630    return QualType();
7631
7632  CheckForNullPointerDereference(*this, LHSExpr);
7633
7634  // C99 6.5.16p3: The type of an assignment expression is the type of the
7635  // left operand unless the left operand has qualified type, in which case
7636  // it is the unqualified version of the type of the left operand.
7637  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7638  // is converted to the type of the assignment expression (above).
7639  // C++ 5.17p1: the type of the assignment expression is that of its left
7640  // operand.
7641  return (getLangOpts().CPlusPlus
7642          ? LHSType : LHSType.getUnqualifiedType());
7643}
7644
7645// C99 6.5.17
7646static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7647                                   SourceLocation Loc) {
7648  LHS = S.CheckPlaceholderExpr(LHS.take());
7649  RHS = S.CheckPlaceholderExpr(RHS.take());
7650  if (LHS.isInvalid() || RHS.isInvalid())
7651    return QualType();
7652
7653  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7654  // operands, but not unary promotions.
7655  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7656
7657  // So we treat the LHS as a ignored value, and in C++ we allow the
7658  // containing site to determine what should be done with the RHS.
7659  LHS = S.IgnoredValueConversions(LHS.take());
7660  if (LHS.isInvalid())
7661    return QualType();
7662
7663  S.DiagnoseUnusedExprResult(LHS.get());
7664
7665  if (!S.getLangOpts().CPlusPlus) {
7666    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7667    if (RHS.isInvalid())
7668      return QualType();
7669    if (!RHS.get()->getType()->isVoidType())
7670      S.RequireCompleteType(Loc, RHS.get()->getType(),
7671                            diag::err_incomplete_type);
7672  }
7673
7674  return RHS.get()->getType();
7675}
7676
7677/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7678/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7679static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7680                                               ExprValueKind &VK,
7681                                               SourceLocation OpLoc,
7682                                               bool IsInc, bool IsPrefix) {
7683  if (Op->isTypeDependent())
7684    return S.Context.DependentTy;
7685
7686  QualType ResType = Op->getType();
7687  // Atomic types can be used for increment / decrement where the non-atomic
7688  // versions can, so ignore the _Atomic() specifier for the purpose of
7689  // checking.
7690  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7691    ResType = ResAtomicType->getValueType();
7692
7693  assert(!ResType.isNull() && "no type for increment/decrement expression");
7694
7695  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7696    // Decrement of bool is not allowed.
7697    if (!IsInc) {
7698      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7699      return QualType();
7700    }
7701    // Increment of bool sets it to true, but is deprecated.
7702    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7703  } else if (ResType->isRealType()) {
7704    // OK!
7705  } else if (ResType->isAnyPointerType()) {
7706    // C99 6.5.2.4p2, 6.5.6p2
7707    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7708      return QualType();
7709
7710    // Diagnose bad cases where we step over interface counts.
7711    else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
7712      return QualType();
7713  } else if (ResType->isAnyComplexType()) {
7714    // C99 does not support ++/-- on complex types, we allow as an extension.
7715    S.Diag(OpLoc, diag::ext_integer_increment_complex)
7716      << ResType << Op->getSourceRange();
7717  } else if (ResType->isPlaceholderType()) {
7718    ExprResult PR = S.CheckPlaceholderExpr(Op);
7719    if (PR.isInvalid()) return QualType();
7720    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7721                                          IsInc, IsPrefix);
7722  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7723    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7724  } else {
7725    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7726      << ResType << int(IsInc) << Op->getSourceRange();
7727    return QualType();
7728  }
7729  // At this point, we know we have a real, complex or pointer type.
7730  // Now make sure the operand is a modifiable lvalue.
7731  if (CheckForModifiableLvalue(Op, OpLoc, S))
7732    return QualType();
7733  // In C++, a prefix increment is the same type as the operand. Otherwise
7734  // (in C or with postfix), the increment is the unqualified type of the
7735  // operand.
7736  if (IsPrefix && S.getLangOpts().CPlusPlus) {
7737    VK = VK_LValue;
7738    return ResType;
7739  } else {
7740    VK = VK_RValue;
7741    return ResType.getUnqualifiedType();
7742  }
7743}
7744
7745
7746/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7747/// This routine allows us to typecheck complex/recursive expressions
7748/// where the declaration is needed for type checking. We only need to
7749/// handle cases when the expression references a function designator
7750/// or is an lvalue. Here are some examples:
7751///  - &(x) => x
7752///  - &*****f => f for f a function designator.
7753///  - &s.xx => s
7754///  - &s.zz[1].yy -> s, if zz is an array
7755///  - *(x + 1) -> x, if x is an array
7756///  - &"123"[2] -> 0
7757///  - & __real__ x -> x
7758static ValueDecl *getPrimaryDecl(Expr *E) {
7759  switch (E->getStmtClass()) {
7760  case Stmt::DeclRefExprClass:
7761    return cast<DeclRefExpr>(E)->getDecl();
7762  case Stmt::MemberExprClass:
7763    // If this is an arrow operator, the address is an offset from
7764    // the base's value, so the object the base refers to is
7765    // irrelevant.
7766    if (cast<MemberExpr>(E)->isArrow())
7767      return 0;
7768    // Otherwise, the expression refers to a part of the base
7769    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7770  case Stmt::ArraySubscriptExprClass: {
7771    // FIXME: This code shouldn't be necessary!  We should catch the implicit
7772    // promotion of register arrays earlier.
7773    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7774    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7775      if (ICE->getSubExpr()->getType()->isArrayType())
7776        return getPrimaryDecl(ICE->getSubExpr());
7777    }
7778    return 0;
7779  }
7780  case Stmt::UnaryOperatorClass: {
7781    UnaryOperator *UO = cast<UnaryOperator>(E);
7782
7783    switch(UO->getOpcode()) {
7784    case UO_Real:
7785    case UO_Imag:
7786    case UO_Extension:
7787      return getPrimaryDecl(UO->getSubExpr());
7788    default:
7789      return 0;
7790    }
7791  }
7792  case Stmt::ParenExprClass:
7793    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7794  case Stmt::ImplicitCastExprClass:
7795    // If the result of an implicit cast is an l-value, we care about
7796    // the sub-expression; otherwise, the result here doesn't matter.
7797    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7798  default:
7799    return 0;
7800  }
7801}
7802
7803namespace {
7804  enum {
7805    AO_Bit_Field = 0,
7806    AO_Vector_Element = 1,
7807    AO_Property_Expansion = 2,
7808    AO_Register_Variable = 3,
7809    AO_No_Error = 4
7810  };
7811}
7812/// \brief Diagnose invalid operand for address of operations.
7813///
7814/// \param Type The type of operand which cannot have its address taken.
7815static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7816                                         Expr *E, unsigned Type) {
7817  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7818}
7819
7820/// CheckAddressOfOperand - The operand of & must be either a function
7821/// designator or an lvalue designating an object. If it is an lvalue, the
7822/// object cannot be declared with storage class register or be a bit field.
7823/// Note: The usual conversions are *not* applied to the operand of the &
7824/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7825/// In C++, the operand might be an overloaded function name, in which case
7826/// we allow the '&' but retain the overloaded-function type.
7827static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7828                                      SourceLocation OpLoc) {
7829  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7830    if (PTy->getKind() == BuiltinType::Overload) {
7831      if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7832        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7833          << OrigOp.get()->getSourceRange();
7834        return QualType();
7835      }
7836
7837      return S.Context.OverloadTy;
7838    }
7839
7840    if (PTy->getKind() == BuiltinType::UnknownAny)
7841      return S.Context.UnknownAnyTy;
7842
7843    if (PTy->getKind() == BuiltinType::BoundMember) {
7844      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7845        << OrigOp.get()->getSourceRange();
7846      return QualType();
7847    }
7848
7849    OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7850    if (OrigOp.isInvalid()) return QualType();
7851  }
7852
7853  if (OrigOp.get()->isTypeDependent())
7854    return S.Context.DependentTy;
7855
7856  assert(!OrigOp.get()->getType()->isPlaceholderType());
7857
7858  // Make sure to ignore parentheses in subsequent checks
7859  Expr *op = OrigOp.get()->IgnoreParens();
7860
7861  if (S.getLangOpts().C99) {
7862    // Implement C99-only parts of addressof rules.
7863    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7864      if (uOp->getOpcode() == UO_Deref)
7865        // Per C99 6.5.3.2, the address of a deref always returns a valid result
7866        // (assuming the deref expression is valid).
7867        return uOp->getSubExpr()->getType();
7868    }
7869    // Technically, there should be a check for array subscript
7870    // expressions here, but the result of one is always an lvalue anyway.
7871  }
7872  ValueDecl *dcl = getPrimaryDecl(op);
7873  Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7874  unsigned AddressOfError = AO_No_Error;
7875
7876  if (lval == Expr::LV_ClassTemporary) {
7877    bool sfinae = S.isSFINAEContext();
7878    S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7879                         : diag::ext_typecheck_addrof_class_temporary)
7880      << op->getType() << op->getSourceRange();
7881    if (sfinae)
7882      return QualType();
7883  } else if (isa<ObjCSelectorExpr>(op)) {
7884    return S.Context.getPointerType(op->getType());
7885  } else if (lval == Expr::LV_MemberFunction) {
7886    // If it's an instance method, make a member pointer.
7887    // The expression must have exactly the form &A::foo.
7888
7889    // If the underlying expression isn't a decl ref, give up.
7890    if (!isa<DeclRefExpr>(op)) {
7891      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7892        << OrigOp.get()->getSourceRange();
7893      return QualType();
7894    }
7895    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7896    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7897
7898    // The id-expression was parenthesized.
7899    if (OrigOp.get() != DRE) {
7900      S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7901        << OrigOp.get()->getSourceRange();
7902
7903    // The method was named without a qualifier.
7904    } else if (!DRE->getQualifier()) {
7905      S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7906        << op->getSourceRange();
7907    }
7908
7909    return S.Context.getMemberPointerType(op->getType(),
7910              S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7911  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7912    // C99 6.5.3.2p1
7913    // The operand must be either an l-value or a function designator
7914    if (!op->getType()->isFunctionType()) {
7915      // Use a special diagnostic for loads from property references.
7916      if (isa<PseudoObjectExpr>(op)) {
7917        AddressOfError = AO_Property_Expansion;
7918      } else {
7919        // FIXME: emit more specific diag...
7920        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7921          << op->getSourceRange();
7922        return QualType();
7923      }
7924    }
7925  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7926    // The operand cannot be a bit-field
7927    AddressOfError = AO_Bit_Field;
7928  } else if (op->getObjectKind() == OK_VectorComponent) {
7929    // The operand cannot be an element of a vector
7930    AddressOfError = AO_Vector_Element;
7931  } else if (dcl) { // C99 6.5.3.2p1
7932    // We have an lvalue with a decl. Make sure the decl is not declared
7933    // with the register storage-class specifier.
7934    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7935      // in C++ it is not error to take address of a register
7936      // variable (c++03 7.1.1P3)
7937      if (vd->getStorageClass() == SC_Register &&
7938          !S.getLangOpts().CPlusPlus) {
7939        AddressOfError = AO_Register_Variable;
7940      }
7941    } else if (isa<FunctionTemplateDecl>(dcl)) {
7942      return S.Context.OverloadTy;
7943    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7944      // Okay: we can take the address of a field.
7945      // Could be a pointer to member, though, if there is an explicit
7946      // scope qualifier for the class.
7947      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7948        DeclContext *Ctx = dcl->getDeclContext();
7949        if (Ctx && Ctx->isRecord()) {
7950          if (dcl->getType()->isReferenceType()) {
7951            S.Diag(OpLoc,
7952                   diag::err_cannot_form_pointer_to_member_of_reference_type)
7953              << dcl->getDeclName() << dcl->getType();
7954            return QualType();
7955          }
7956
7957          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7958            Ctx = Ctx->getParent();
7959          return S.Context.getMemberPointerType(op->getType(),
7960                S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7961        }
7962      }
7963    } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
7964      llvm_unreachable("Unknown/unexpected decl type");
7965  }
7966
7967  if (AddressOfError != AO_No_Error) {
7968    diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7969    return QualType();
7970  }
7971
7972  if (lval == Expr::LV_IncompleteVoidType) {
7973    // Taking the address of a void variable is technically illegal, but we
7974    // allow it in cases which are otherwise valid.
7975    // Example: "extern void x; void* y = &x;".
7976    S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7977  }
7978
7979  // If the operand has type "type", the result has type "pointer to type".
7980  if (op->getType()->isObjCObjectType())
7981    return S.Context.getObjCObjectPointerType(op->getType());
7982  return S.Context.getPointerType(op->getType());
7983}
7984
7985/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7986static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7987                                        SourceLocation OpLoc) {
7988  if (Op->isTypeDependent())
7989    return S.Context.DependentTy;
7990
7991  ExprResult ConvResult = S.UsualUnaryConversions(Op);
7992  if (ConvResult.isInvalid())
7993    return QualType();
7994  Op = ConvResult.take();
7995  QualType OpTy = Op->getType();
7996  QualType Result;
7997
7998  if (isa<CXXReinterpretCastExpr>(Op)) {
7999    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8000    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8001                                     Op->getSourceRange());
8002  }
8003
8004  // Note that per both C89 and C99, indirection is always legal, even if OpTy
8005  // is an incomplete type or void.  It would be possible to warn about
8006  // dereferencing a void pointer, but it's completely well-defined, and such a
8007  // warning is unlikely to catch any mistakes.
8008  if (const PointerType *PT = OpTy->getAs<PointerType>())
8009    Result = PT->getPointeeType();
8010  else if (const ObjCObjectPointerType *OPT =
8011             OpTy->getAs<ObjCObjectPointerType>())
8012    Result = OPT->getPointeeType();
8013  else {
8014    ExprResult PR = S.CheckPlaceholderExpr(Op);
8015    if (PR.isInvalid()) return QualType();
8016    if (PR.take() != Op)
8017      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8018  }
8019
8020  if (Result.isNull()) {
8021    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8022      << OpTy << Op->getSourceRange();
8023    return QualType();
8024  }
8025
8026  // Dereferences are usually l-values...
8027  VK = VK_LValue;
8028
8029  // ...except that certain expressions are never l-values in C.
8030  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8031    VK = VK_RValue;
8032
8033  return Result;
8034}
8035
8036static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8037  tok::TokenKind Kind) {
8038  BinaryOperatorKind Opc;
8039  switch (Kind) {
8040  default: llvm_unreachable("Unknown binop!");
8041  case tok::periodstar:           Opc = BO_PtrMemD; break;
8042  case tok::arrowstar:            Opc = BO_PtrMemI; break;
8043  case tok::star:                 Opc = BO_Mul; break;
8044  case tok::slash:                Opc = BO_Div; break;
8045  case tok::percent:              Opc = BO_Rem; break;
8046  case tok::plus:                 Opc = BO_Add; break;
8047  case tok::minus:                Opc = BO_Sub; break;
8048  case tok::lessless:             Opc = BO_Shl; break;
8049  case tok::greatergreater:       Opc = BO_Shr; break;
8050  case tok::lessequal:            Opc = BO_LE; break;
8051  case tok::less:                 Opc = BO_LT; break;
8052  case tok::greaterequal:         Opc = BO_GE; break;
8053  case tok::greater:              Opc = BO_GT; break;
8054  case tok::exclaimequal:         Opc = BO_NE; break;
8055  case tok::equalequal:           Opc = BO_EQ; break;
8056  case tok::amp:                  Opc = BO_And; break;
8057  case tok::caret:                Opc = BO_Xor; break;
8058  case tok::pipe:                 Opc = BO_Or; break;
8059  case tok::ampamp:               Opc = BO_LAnd; break;
8060  case tok::pipepipe:             Opc = BO_LOr; break;
8061  case tok::equal:                Opc = BO_Assign; break;
8062  case tok::starequal:            Opc = BO_MulAssign; break;
8063  case tok::slashequal:           Opc = BO_DivAssign; break;
8064  case tok::percentequal:         Opc = BO_RemAssign; break;
8065  case tok::plusequal:            Opc = BO_AddAssign; break;
8066  case tok::minusequal:           Opc = BO_SubAssign; break;
8067  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8068  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8069  case tok::ampequal:             Opc = BO_AndAssign; break;
8070  case tok::caretequal:           Opc = BO_XorAssign; break;
8071  case tok::pipeequal:            Opc = BO_OrAssign; break;
8072  case tok::comma:                Opc = BO_Comma; break;
8073  }
8074  return Opc;
8075}
8076
8077static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8078  tok::TokenKind Kind) {
8079  UnaryOperatorKind Opc;
8080  switch (Kind) {
8081  default: llvm_unreachable("Unknown unary op!");
8082  case tok::plusplus:     Opc = UO_PreInc; break;
8083  case tok::minusminus:   Opc = UO_PreDec; break;
8084  case tok::amp:          Opc = UO_AddrOf; break;
8085  case tok::star:         Opc = UO_Deref; break;
8086  case tok::plus:         Opc = UO_Plus; break;
8087  case tok::minus:        Opc = UO_Minus; break;
8088  case tok::tilde:        Opc = UO_Not; break;
8089  case tok::exclaim:      Opc = UO_LNot; break;
8090  case tok::kw___real:    Opc = UO_Real; break;
8091  case tok::kw___imag:    Opc = UO_Imag; break;
8092  case tok::kw___extension__: Opc = UO_Extension; break;
8093  }
8094  return Opc;
8095}
8096
8097/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8098/// This warning is only emitted for builtin assignment operations. It is also
8099/// suppressed in the event of macro expansions.
8100static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8101                                   SourceLocation OpLoc) {
8102  if (!S.ActiveTemplateInstantiations.empty())
8103    return;
8104  if (OpLoc.isInvalid() || OpLoc.isMacroID())
8105    return;
8106  LHSExpr = LHSExpr->IgnoreParenImpCasts();
8107  RHSExpr = RHSExpr->IgnoreParenImpCasts();
8108  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8109  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8110  if (!LHSDeclRef || !RHSDeclRef ||
8111      LHSDeclRef->getLocation().isMacroID() ||
8112      RHSDeclRef->getLocation().isMacroID())
8113    return;
8114  const ValueDecl *LHSDecl =
8115    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8116  const ValueDecl *RHSDecl =
8117    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8118  if (LHSDecl != RHSDecl)
8119    return;
8120  if (LHSDecl->getType().isVolatileQualified())
8121    return;
8122  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8123    if (RefTy->getPointeeType().isVolatileQualified())
8124      return;
8125
8126  S.Diag(OpLoc, diag::warn_self_assignment)
8127      << LHSDeclRef->getType()
8128      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8129}
8130
8131/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8132/// operator @p Opc at location @c TokLoc. This routine only supports
8133/// built-in operations; ActOnBinOp handles overloaded operators.
8134ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8135                                    BinaryOperatorKind Opc,
8136                                    Expr *LHSExpr, Expr *RHSExpr) {
8137  if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8138    // The syntax only allows initializer lists on the RHS of assignment,
8139    // so we don't need to worry about accepting invalid code for
8140    // non-assignment operators.
8141    // C++11 5.17p9:
8142    //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8143    //   of x = {} is x = T().
8144    InitializationKind Kind =
8145        InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8146    InitializedEntity Entity =
8147        InitializedEntity::InitializeTemporary(LHSExpr->getType());
8148    InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8149    ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8150                                      MultiExprArg(&RHSExpr, 1));
8151    if (Init.isInvalid())
8152      return Init;
8153    RHSExpr = Init.take();
8154  }
8155
8156  ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8157  QualType ResultTy;     // Result type of the binary operator.
8158  // The following two variables are used for compound assignment operators
8159  QualType CompLHSTy;    // Type of LHS after promotions for computation
8160  QualType CompResultTy; // Type of computation result
8161  ExprValueKind VK = VK_RValue;
8162  ExprObjectKind OK = OK_Ordinary;
8163
8164  switch (Opc) {
8165  case BO_Assign:
8166    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8167    if (getLangOpts().CPlusPlus &&
8168        LHS.get()->getObjectKind() != OK_ObjCProperty) {
8169      VK = LHS.get()->getValueKind();
8170      OK = LHS.get()->getObjectKind();
8171    }
8172    if (!ResultTy.isNull())
8173      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8174    break;
8175  case BO_PtrMemD:
8176  case BO_PtrMemI:
8177    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8178                                            Opc == BO_PtrMemI);
8179    break;
8180  case BO_Mul:
8181  case BO_Div:
8182    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8183                                           Opc == BO_Div);
8184    break;
8185  case BO_Rem:
8186    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8187    break;
8188  case BO_Add:
8189    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8190    break;
8191  case BO_Sub:
8192    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8193    break;
8194  case BO_Shl:
8195  case BO_Shr:
8196    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8197    break;
8198  case BO_LE:
8199  case BO_LT:
8200  case BO_GE:
8201  case BO_GT:
8202    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8203    break;
8204  case BO_EQ:
8205  case BO_NE:
8206    if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8207      ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8208                                                        LHS, RHS, Opc);
8209      if (IsEqualCall.isUsable())
8210        return IsEqualCall;
8211      // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8212    }
8213    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8214    break;
8215  case BO_And:
8216  case BO_Xor:
8217  case BO_Or:
8218    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8219    break;
8220  case BO_LAnd:
8221  case BO_LOr:
8222    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8223    break;
8224  case BO_MulAssign:
8225  case BO_DivAssign:
8226    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8227                                               Opc == BO_DivAssign);
8228    CompLHSTy = CompResultTy;
8229    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8230      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8231    break;
8232  case BO_RemAssign:
8233    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8234    CompLHSTy = CompResultTy;
8235    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8236      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8237    break;
8238  case BO_AddAssign:
8239    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8240    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8241      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8242    break;
8243  case BO_SubAssign:
8244    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8245    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8246      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8247    break;
8248  case BO_ShlAssign:
8249  case BO_ShrAssign:
8250    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8251    CompLHSTy = CompResultTy;
8252    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8253      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8254    break;
8255  case BO_AndAssign:
8256  case BO_XorAssign:
8257  case BO_OrAssign:
8258    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8259    CompLHSTy = CompResultTy;
8260    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8261      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8262    break;
8263  case BO_Comma:
8264    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8265    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8266      VK = RHS.get()->getValueKind();
8267      OK = RHS.get()->getObjectKind();
8268    }
8269    break;
8270  }
8271  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8272    return ExprError();
8273
8274  // Check for array bounds violations for both sides of the BinaryOperator
8275  CheckArrayAccess(LHS.get());
8276  CheckArrayAccess(RHS.get());
8277
8278  if (CompResultTy.isNull())
8279    return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8280                                              ResultTy, VK, OK, OpLoc));
8281  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8282      OK_ObjCProperty) {
8283    VK = VK_LValue;
8284    OK = LHS.get()->getObjectKind();
8285  }
8286  return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8287                                                    ResultTy, VK, OK, CompLHSTy,
8288                                                    CompResultTy, OpLoc));
8289}
8290
8291/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8292/// operators are mixed in a way that suggests that the programmer forgot that
8293/// comparison operators have higher precedence. The most typical example of
8294/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8295static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8296                                      SourceLocation OpLoc, Expr *LHSExpr,
8297                                      Expr *RHSExpr) {
8298  typedef BinaryOperator BinOp;
8299  BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8300                RHSopc = static_cast<BinOp::Opcode>(-1);
8301  if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8302    LHSopc = BO->getOpcode();
8303  if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8304    RHSopc = BO->getOpcode();
8305
8306  // Subs are not binary operators.
8307  if (LHSopc == -1 && RHSopc == -1)
8308    return;
8309
8310  // Bitwise operations are sometimes used as eager logical ops.
8311  // Don't diagnose this.
8312  if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8313      (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8314    return;
8315
8316  bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8317  bool isRightComp = BinOp::isComparisonOp(RHSopc);
8318  if (!isLeftComp && !isRightComp) return;
8319
8320  SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8321                                                   OpLoc)
8322                                     : SourceRange(OpLoc, RHSExpr->getLocEnd());
8323  std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8324                                 : BinOp::getOpcodeStr(RHSopc);
8325  SourceRange ParensRange = isLeftComp ?
8326      SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8327                  RHSExpr->getLocEnd())
8328    : SourceRange(LHSExpr->getLocStart(),
8329                  cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8330
8331  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8332    << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8333  SuggestParentheses(Self, OpLoc,
8334    Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
8335    (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8336  SuggestParentheses(Self, OpLoc,
8337    Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8338    ParensRange);
8339}
8340
8341/// \brief It accepts a '&' expr that is inside a '|' one.
8342/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8343/// in parentheses.
8344static void
8345EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8346                                       BinaryOperator *Bop) {
8347  assert(Bop->getOpcode() == BO_And);
8348  Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8349      << Bop->getSourceRange() << OpLoc;
8350  SuggestParentheses(Self, Bop->getOperatorLoc(),
8351    Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8352    Bop->getSourceRange());
8353}
8354
8355/// \brief It accepts a '&&' expr that is inside a '||' one.
8356/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8357/// in parentheses.
8358static void
8359EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8360                                       BinaryOperator *Bop) {
8361  assert(Bop->getOpcode() == BO_LAnd);
8362  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8363      << Bop->getSourceRange() << OpLoc;
8364  SuggestParentheses(Self, Bop->getOperatorLoc(),
8365    Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8366    Bop->getSourceRange());
8367}
8368
8369/// \brief Returns true if the given expression can be evaluated as a constant
8370/// 'true'.
8371static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8372  bool Res;
8373  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8374}
8375
8376/// \brief Returns true if the given expression can be evaluated as a constant
8377/// 'false'.
8378static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8379  bool Res;
8380  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8381}
8382
8383/// \brief Look for '&&' in the left hand of a '||' expr.
8384static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8385                                             Expr *LHSExpr, Expr *RHSExpr) {
8386  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8387    if (Bop->getOpcode() == BO_LAnd) {
8388      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8389      if (EvaluatesAsFalse(S, RHSExpr))
8390        return;
8391      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8392      if (!EvaluatesAsTrue(S, Bop->getLHS()))
8393        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8394    } else if (Bop->getOpcode() == BO_LOr) {
8395      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8396        // If it's "a || b && 1 || c" we didn't warn earlier for
8397        // "a || b && 1", but warn now.
8398        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8399          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8400      }
8401    }
8402  }
8403}
8404
8405/// \brief Look for '&&' in the right hand of a '||' expr.
8406static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8407                                             Expr *LHSExpr, Expr *RHSExpr) {
8408  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8409    if (Bop->getOpcode() == BO_LAnd) {
8410      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8411      if (EvaluatesAsFalse(S, LHSExpr))
8412        return;
8413      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8414      if (!EvaluatesAsTrue(S, Bop->getRHS()))
8415        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8416    }
8417  }
8418}
8419
8420/// \brief Look for '&' in the left or right hand of a '|' expr.
8421static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8422                                             Expr *OrArg) {
8423  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8424    if (Bop->getOpcode() == BO_And)
8425      return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8426  }
8427}
8428
8429/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8430/// precedence.
8431static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8432                                    SourceLocation OpLoc, Expr *LHSExpr,
8433                                    Expr *RHSExpr){
8434  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8435  if (BinaryOperator::isBitwiseOp(Opc))
8436    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8437
8438  // Diagnose "arg1 & arg2 | arg3"
8439  if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8440    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8441    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8442  }
8443
8444  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8445  // We don't warn for 'assert(a || b && "bad")' since this is safe.
8446  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8447    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8448    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8449  }
8450}
8451
8452// Binary Operators.  'Tok' is the token for the operator.
8453ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8454                            tok::TokenKind Kind,
8455                            Expr *LHSExpr, Expr *RHSExpr) {
8456  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8457  assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8458  assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8459
8460  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8461  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8462
8463  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8464}
8465
8466/// Build an overloaded binary operator expression in the given scope.
8467static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8468                                       BinaryOperatorKind Opc,
8469                                       Expr *LHS, Expr *RHS) {
8470  // Find all of the overloaded operators visible from this
8471  // point. We perform both an operator-name lookup from the local
8472  // scope and an argument-dependent lookup based on the types of
8473  // the arguments.
8474  UnresolvedSet<16> Functions;
8475  OverloadedOperatorKind OverOp
8476    = BinaryOperator::getOverloadedOperator(Opc);
8477  if (Sc && OverOp != OO_None)
8478    S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8479                                   RHS->getType(), Functions);
8480
8481  // Build the (potentially-overloaded, potentially-dependent)
8482  // binary operation.
8483  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8484}
8485
8486ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8487                            BinaryOperatorKind Opc,
8488                            Expr *LHSExpr, Expr *RHSExpr) {
8489  // We want to end up calling one of checkPseudoObjectAssignment
8490  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8491  // both expressions are overloadable or either is type-dependent),
8492  // or CreateBuiltinBinOp (in any other case).  We also want to get
8493  // any placeholder types out of the way.
8494
8495  // Handle pseudo-objects in the LHS.
8496  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8497    // Assignments with a pseudo-object l-value need special analysis.
8498    if (pty->getKind() == BuiltinType::PseudoObject &&
8499        BinaryOperator::isAssignmentOp(Opc))
8500      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8501
8502    // Don't resolve overloads if the other type is overloadable.
8503    if (pty->getKind() == BuiltinType::Overload) {
8504      // We can't actually test that if we still have a placeholder,
8505      // though.  Fortunately, none of the exceptions we see in that
8506      // code below are valid when the LHS is an overload set.  Note
8507      // that an overload set can be dependently-typed, but it never
8508      // instantiates to having an overloadable type.
8509      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8510      if (resolvedRHS.isInvalid()) return ExprError();
8511      RHSExpr = resolvedRHS.take();
8512
8513      if (RHSExpr->isTypeDependent() ||
8514          RHSExpr->getType()->isOverloadableType())
8515        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8516    }
8517
8518    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8519    if (LHS.isInvalid()) return ExprError();
8520    LHSExpr = LHS.take();
8521  }
8522
8523  // Handle pseudo-objects in the RHS.
8524  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8525    // An overload in the RHS can potentially be resolved by the type
8526    // being assigned to.
8527    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8528      if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8529        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8530
8531      if (LHSExpr->getType()->isOverloadableType())
8532        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8533
8534      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8535    }
8536
8537    // Don't resolve overloads if the other type is overloadable.
8538    if (pty->getKind() == BuiltinType::Overload &&
8539        LHSExpr->getType()->isOverloadableType())
8540      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8541
8542    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8543    if (!resolvedRHS.isUsable()) return ExprError();
8544    RHSExpr = resolvedRHS.take();
8545  }
8546
8547  if (getLangOpts().CPlusPlus) {
8548    // If either expression is type-dependent, always build an
8549    // overloaded op.
8550    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8551      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8552
8553    // Otherwise, build an overloaded op if either expression has an
8554    // overloadable type.
8555    if (LHSExpr->getType()->isOverloadableType() ||
8556        RHSExpr->getType()->isOverloadableType())
8557      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8558  }
8559
8560  // Build a built-in binary operation.
8561  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8562}
8563
8564ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8565                                      UnaryOperatorKind Opc,
8566                                      Expr *InputExpr) {
8567  ExprResult Input = Owned(InputExpr);
8568  ExprValueKind VK = VK_RValue;
8569  ExprObjectKind OK = OK_Ordinary;
8570  QualType resultType;
8571  switch (Opc) {
8572  case UO_PreInc:
8573  case UO_PreDec:
8574  case UO_PostInc:
8575  case UO_PostDec:
8576    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8577                                                Opc == UO_PreInc ||
8578                                                Opc == UO_PostInc,
8579                                                Opc == UO_PreInc ||
8580                                                Opc == UO_PreDec);
8581    break;
8582  case UO_AddrOf:
8583    resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8584    break;
8585  case UO_Deref: {
8586    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8587    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8588    break;
8589  }
8590  case UO_Plus:
8591  case UO_Minus:
8592    Input = UsualUnaryConversions(Input.take());
8593    if (Input.isInvalid()) return ExprError();
8594    resultType = Input.get()->getType();
8595    if (resultType->isDependentType())
8596      break;
8597    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8598        resultType->isVectorType())
8599      break;
8600    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8601             resultType->isEnumeralType())
8602      break;
8603    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8604             Opc == UO_Plus &&
8605             resultType->isPointerType())
8606      break;
8607
8608    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8609      << resultType << Input.get()->getSourceRange());
8610
8611  case UO_Not: // bitwise complement
8612    Input = UsualUnaryConversions(Input.take());
8613    if (Input.isInvalid()) return ExprError();
8614    resultType = Input.get()->getType();
8615    if (resultType->isDependentType())
8616      break;
8617    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8618    if (resultType->isComplexType() || resultType->isComplexIntegerType())
8619      // C99 does not support '~' for complex conjugation.
8620      Diag(OpLoc, diag::ext_integer_complement_complex)
8621        << resultType << Input.get()->getSourceRange();
8622    else if (resultType->hasIntegerRepresentation())
8623      break;
8624    else {
8625      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8626        << resultType << Input.get()->getSourceRange());
8627    }
8628    break;
8629
8630  case UO_LNot: // logical negation
8631    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8632    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8633    if (Input.isInvalid()) return ExprError();
8634    resultType = Input.get()->getType();
8635
8636    // Though we still have to promote half FP to float...
8637    if (resultType->isHalfType()) {
8638      Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8639      resultType = Context.FloatTy;
8640    }
8641
8642    if (resultType->isDependentType())
8643      break;
8644    if (resultType->isScalarType()) {
8645      // C99 6.5.3.3p1: ok, fallthrough;
8646      if (Context.getLangOpts().CPlusPlus) {
8647        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8648        // operand contextually converted to bool.
8649        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8650                                  ScalarTypeToBooleanCastKind(resultType));
8651      }
8652    } else if (resultType->isExtVectorType()) {
8653      // Vector logical not returns the signed variant of the operand type.
8654      resultType = GetSignedVectorType(resultType);
8655      break;
8656    } else {
8657      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8658        << resultType << Input.get()->getSourceRange());
8659    }
8660
8661    // LNot always has type int. C99 6.5.3.3p5.
8662    // In C++, it's bool. C++ 5.3.1p8
8663    resultType = Context.getLogicalOperationType();
8664    break;
8665  case UO_Real:
8666  case UO_Imag:
8667    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8668    // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8669    // complex l-values to ordinary l-values and all other values to r-values.
8670    if (Input.isInvalid()) return ExprError();
8671    if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8672      if (Input.get()->getValueKind() != VK_RValue &&
8673          Input.get()->getObjectKind() == OK_Ordinary)
8674        VK = Input.get()->getValueKind();
8675    } else if (!getLangOpts().CPlusPlus) {
8676      // In C, a volatile scalar is read by __imag. In C++, it is not.
8677      Input = DefaultLvalueConversion(Input.take());
8678    }
8679    break;
8680  case UO_Extension:
8681    resultType = Input.get()->getType();
8682    VK = Input.get()->getValueKind();
8683    OK = Input.get()->getObjectKind();
8684    break;
8685  }
8686  if (resultType.isNull() || Input.isInvalid())
8687    return ExprError();
8688
8689  // Check for array bounds violations in the operand of the UnaryOperator,
8690  // except for the '*' and '&' operators that have to be handled specially
8691  // by CheckArrayAccess (as there are special cases like &array[arraysize]
8692  // that are explicitly defined as valid by the standard).
8693  if (Opc != UO_AddrOf && Opc != UO_Deref)
8694    CheckArrayAccess(Input.get());
8695
8696  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8697                                           VK, OK, OpLoc));
8698}
8699
8700/// \brief Determine whether the given expression is a qualified member
8701/// access expression, of a form that could be turned into a pointer to member
8702/// with the address-of operator.
8703static bool isQualifiedMemberAccess(Expr *E) {
8704  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8705    if (!DRE->getQualifier())
8706      return false;
8707
8708    ValueDecl *VD = DRE->getDecl();
8709    if (!VD->isCXXClassMember())
8710      return false;
8711
8712    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8713      return true;
8714    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8715      return Method->isInstance();
8716
8717    return false;
8718  }
8719
8720  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8721    if (!ULE->getQualifier())
8722      return false;
8723
8724    for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8725                                           DEnd = ULE->decls_end();
8726         D != DEnd; ++D) {
8727      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8728        if (Method->isInstance())
8729          return true;
8730      } else {
8731        // Overload set does not contain methods.
8732        break;
8733      }
8734    }
8735
8736    return false;
8737  }
8738
8739  return false;
8740}
8741
8742ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8743                              UnaryOperatorKind Opc, Expr *Input) {
8744  // First things first: handle placeholders so that the
8745  // overloaded-operator check considers the right type.
8746  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8747    // Increment and decrement of pseudo-object references.
8748    if (pty->getKind() == BuiltinType::PseudoObject &&
8749        UnaryOperator::isIncrementDecrementOp(Opc))
8750      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8751
8752    // extension is always a builtin operator.
8753    if (Opc == UO_Extension)
8754      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8755
8756    // & gets special logic for several kinds of placeholder.
8757    // The builtin code knows what to do.
8758    if (Opc == UO_AddrOf &&
8759        (pty->getKind() == BuiltinType::Overload ||
8760         pty->getKind() == BuiltinType::UnknownAny ||
8761         pty->getKind() == BuiltinType::BoundMember))
8762      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8763
8764    // Anything else needs to be handled now.
8765    ExprResult Result = CheckPlaceholderExpr(Input);
8766    if (Result.isInvalid()) return ExprError();
8767    Input = Result.take();
8768  }
8769
8770  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8771      UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8772      !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8773    // Find all of the overloaded operators visible from this
8774    // point. We perform both an operator-name lookup from the local
8775    // scope and an argument-dependent lookup based on the types of
8776    // the arguments.
8777    UnresolvedSet<16> Functions;
8778    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8779    if (S && OverOp != OO_None)
8780      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8781                                   Functions);
8782
8783    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8784  }
8785
8786  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8787}
8788
8789// Unary Operators.  'Tok' is the token for the operator.
8790ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8791                              tok::TokenKind Op, Expr *Input) {
8792  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8793}
8794
8795/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8796ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8797                                LabelDecl *TheDecl) {
8798  TheDecl->setUsed();
8799  // Create the AST node.  The address of a label always has type 'void*'.
8800  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8801                                       Context.getPointerType(Context.VoidTy)));
8802}
8803
8804/// Given the last statement in a statement-expression, check whether
8805/// the result is a producing expression (like a call to an
8806/// ns_returns_retained function) and, if so, rebuild it to hoist the
8807/// release out of the full-expression.  Otherwise, return null.
8808/// Cannot fail.
8809static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8810  // Should always be wrapped with one of these.
8811  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8812  if (!cleanups) return 0;
8813
8814  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8815  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8816    return 0;
8817
8818  // Splice out the cast.  This shouldn't modify any interesting
8819  // features of the statement.
8820  Expr *producer = cast->getSubExpr();
8821  assert(producer->getType() == cast->getType());
8822  assert(producer->getValueKind() == cast->getValueKind());
8823  cleanups->setSubExpr(producer);
8824  return cleanups;
8825}
8826
8827void Sema::ActOnStartStmtExpr() {
8828  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8829}
8830
8831void Sema::ActOnStmtExprError() {
8832  // Note that function is also called by TreeTransform when leaving a
8833  // StmtExpr scope without rebuilding anything.
8834
8835  DiscardCleanupsInEvaluationContext();
8836  PopExpressionEvaluationContext();
8837}
8838
8839ExprResult
8840Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8841                    SourceLocation RPLoc) { // "({..})"
8842  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8843  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8844
8845  if (hasAnyUnrecoverableErrorsInThisFunction())
8846    DiscardCleanupsInEvaluationContext();
8847  assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8848  PopExpressionEvaluationContext();
8849
8850  bool isFileScope
8851    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8852  if (isFileScope)
8853    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8854
8855  // FIXME: there are a variety of strange constraints to enforce here, for
8856  // example, it is not possible to goto into a stmt expression apparently.
8857  // More semantic analysis is needed.
8858
8859  // If there are sub stmts in the compound stmt, take the type of the last one
8860  // as the type of the stmtexpr.
8861  QualType Ty = Context.VoidTy;
8862  bool StmtExprMayBindToTemp = false;
8863  if (!Compound->body_empty()) {
8864    Stmt *LastStmt = Compound->body_back();
8865    LabelStmt *LastLabelStmt = 0;
8866    // If LastStmt is a label, skip down through into the body.
8867    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8868      LastLabelStmt = Label;
8869      LastStmt = Label->getSubStmt();
8870    }
8871
8872    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8873      // Do function/array conversion on the last expression, but not
8874      // lvalue-to-rvalue.  However, initialize an unqualified type.
8875      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8876      if (LastExpr.isInvalid())
8877        return ExprError();
8878      Ty = LastExpr.get()->getType().getUnqualifiedType();
8879
8880      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8881        // In ARC, if the final expression ends in a consume, splice
8882        // the consume out and bind it later.  In the alternate case
8883        // (when dealing with a retainable type), the result
8884        // initialization will create a produce.  In both cases the
8885        // result will be +1, and we'll need to balance that out with
8886        // a bind.
8887        if (Expr *rebuiltLastStmt
8888              = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8889          LastExpr = rebuiltLastStmt;
8890        } else {
8891          LastExpr = PerformCopyInitialization(
8892                            InitializedEntity::InitializeResult(LPLoc,
8893                                                                Ty,
8894                                                                false),
8895                                                   SourceLocation(),
8896                                               LastExpr);
8897        }
8898
8899        if (LastExpr.isInvalid())
8900          return ExprError();
8901        if (LastExpr.get() != 0) {
8902          if (!LastLabelStmt)
8903            Compound->setLastStmt(LastExpr.take());
8904          else
8905            LastLabelStmt->setSubStmt(LastExpr.take());
8906          StmtExprMayBindToTemp = true;
8907        }
8908      }
8909    }
8910  }
8911
8912  // FIXME: Check that expression type is complete/non-abstract; statement
8913  // expressions are not lvalues.
8914  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8915  if (StmtExprMayBindToTemp)
8916    return MaybeBindToTemporary(ResStmtExpr);
8917  return Owned(ResStmtExpr);
8918}
8919
8920ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8921                                      TypeSourceInfo *TInfo,
8922                                      OffsetOfComponent *CompPtr,
8923                                      unsigned NumComponents,
8924                                      SourceLocation RParenLoc) {
8925  QualType ArgTy = TInfo->getType();
8926  bool Dependent = ArgTy->isDependentType();
8927  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8928
8929  // We must have at least one component that refers to the type, and the first
8930  // one is known to be a field designator.  Verify that the ArgTy represents
8931  // a struct/union/class.
8932  if (!Dependent && !ArgTy->isRecordType())
8933    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8934                       << ArgTy << TypeRange);
8935
8936  // Type must be complete per C99 7.17p3 because a declaring a variable
8937  // with an incomplete type would be ill-formed.
8938  if (!Dependent
8939      && RequireCompleteType(BuiltinLoc, ArgTy,
8940                             diag::err_offsetof_incomplete_type, TypeRange))
8941    return ExprError();
8942
8943  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8944  // GCC extension, diagnose them.
8945  // FIXME: This diagnostic isn't actually visible because the location is in
8946  // a system header!
8947  if (NumComponents != 1)
8948    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8949      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8950
8951  bool DidWarnAboutNonPOD = false;
8952  QualType CurrentType = ArgTy;
8953  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8954  SmallVector<OffsetOfNode, 4> Comps;
8955  SmallVector<Expr*, 4> Exprs;
8956  for (unsigned i = 0; i != NumComponents; ++i) {
8957    const OffsetOfComponent &OC = CompPtr[i];
8958    if (OC.isBrackets) {
8959      // Offset of an array sub-field.  TODO: Should we allow vector elements?
8960      if (!CurrentType->isDependentType()) {
8961        const ArrayType *AT = Context.getAsArrayType(CurrentType);
8962        if(!AT)
8963          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8964                           << CurrentType);
8965        CurrentType = AT->getElementType();
8966      } else
8967        CurrentType = Context.DependentTy;
8968
8969      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8970      if (IdxRval.isInvalid())
8971        return ExprError();
8972      Expr *Idx = IdxRval.take();
8973
8974      // The expression must be an integral expression.
8975      // FIXME: An integral constant expression?
8976      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8977          !Idx->getType()->isIntegerType())
8978        return ExprError(Diag(Idx->getLocStart(),
8979                              diag::err_typecheck_subscript_not_integer)
8980                         << Idx->getSourceRange());
8981
8982      // Record this array index.
8983      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8984      Exprs.push_back(Idx);
8985      continue;
8986    }
8987
8988    // Offset of a field.
8989    if (CurrentType->isDependentType()) {
8990      // We have the offset of a field, but we can't look into the dependent
8991      // type. Just record the identifier of the field.
8992      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8993      CurrentType = Context.DependentTy;
8994      continue;
8995    }
8996
8997    // We need to have a complete type to look into.
8998    if (RequireCompleteType(OC.LocStart, CurrentType,
8999                            diag::err_offsetof_incomplete_type))
9000      return ExprError();
9001
9002    // Look for the designated field.
9003    const RecordType *RC = CurrentType->getAs<RecordType>();
9004    if (!RC)
9005      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9006                       << CurrentType);
9007    RecordDecl *RD = RC->getDecl();
9008
9009    // C++ [lib.support.types]p5:
9010    //   The macro offsetof accepts a restricted set of type arguments in this
9011    //   International Standard. type shall be a POD structure or a POD union
9012    //   (clause 9).
9013    // C++11 [support.types]p4:
9014    //   If type is not a standard-layout class (Clause 9), the results are
9015    //   undefined.
9016    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9017      bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9018      unsigned DiagID =
9019        LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9020                            : diag::warn_offsetof_non_pod_type;
9021
9022      if (!IsSafe && !DidWarnAboutNonPOD &&
9023          DiagRuntimeBehavior(BuiltinLoc, 0,
9024                              PDiag(DiagID)
9025                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9026                              << CurrentType))
9027        DidWarnAboutNonPOD = true;
9028    }
9029
9030    // Look for the field.
9031    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9032    LookupQualifiedName(R, RD);
9033    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9034    IndirectFieldDecl *IndirectMemberDecl = 0;
9035    if (!MemberDecl) {
9036      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9037        MemberDecl = IndirectMemberDecl->getAnonField();
9038    }
9039
9040    if (!MemberDecl)
9041      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9042                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9043                                                              OC.LocEnd));
9044
9045    // C99 7.17p3:
9046    //   (If the specified member is a bit-field, the behavior is undefined.)
9047    //
9048    // We diagnose this as an error.
9049    if (MemberDecl->isBitField()) {
9050      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9051        << MemberDecl->getDeclName()
9052        << SourceRange(BuiltinLoc, RParenLoc);
9053      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9054      return ExprError();
9055    }
9056
9057    RecordDecl *Parent = MemberDecl->getParent();
9058    if (IndirectMemberDecl)
9059      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9060
9061    // If the member was found in a base class, introduce OffsetOfNodes for
9062    // the base class indirections.
9063    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9064                       /*DetectVirtual=*/false);
9065    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9066      CXXBasePath &Path = Paths.front();
9067      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9068           B != BEnd; ++B)
9069        Comps.push_back(OffsetOfNode(B->Base));
9070    }
9071
9072    if (IndirectMemberDecl) {
9073      for (IndirectFieldDecl::chain_iterator FI =
9074           IndirectMemberDecl->chain_begin(),
9075           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9076        assert(isa<FieldDecl>(*FI));
9077        Comps.push_back(OffsetOfNode(OC.LocStart,
9078                                     cast<FieldDecl>(*FI), OC.LocEnd));
9079      }
9080    } else
9081      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9082
9083    CurrentType = MemberDecl->getType().getNonReferenceType();
9084  }
9085
9086  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9087                                    TInfo, Comps.data(), Comps.size(),
9088                                    Exprs.data(), Exprs.size(), RParenLoc));
9089}
9090
9091ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9092                                      SourceLocation BuiltinLoc,
9093                                      SourceLocation TypeLoc,
9094                                      ParsedType ParsedArgTy,
9095                                      OffsetOfComponent *CompPtr,
9096                                      unsigned NumComponents,
9097                                      SourceLocation RParenLoc) {
9098
9099  TypeSourceInfo *ArgTInfo;
9100  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9101  if (ArgTy.isNull())
9102    return ExprError();
9103
9104  if (!ArgTInfo)
9105    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9106
9107  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9108                              RParenLoc);
9109}
9110
9111
9112ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9113                                 Expr *CondExpr,
9114                                 Expr *LHSExpr, Expr *RHSExpr,
9115                                 SourceLocation RPLoc) {
9116  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9117
9118  ExprValueKind VK = VK_RValue;
9119  ExprObjectKind OK = OK_Ordinary;
9120  QualType resType;
9121  bool ValueDependent = false;
9122  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9123    resType = Context.DependentTy;
9124    ValueDependent = true;
9125  } else {
9126    // The conditional expression is required to be a constant expression.
9127    llvm::APSInt condEval(32);
9128    ExprResult CondICE
9129      = VerifyIntegerConstantExpression(CondExpr, &condEval,
9130          diag::err_typecheck_choose_expr_requires_constant, false);
9131    if (CondICE.isInvalid())
9132      return ExprError();
9133    CondExpr = CondICE.take();
9134
9135    // If the condition is > zero, then the AST type is the same as the LSHExpr.
9136    Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9137
9138    resType = ActiveExpr->getType();
9139    ValueDependent = ActiveExpr->isValueDependent();
9140    VK = ActiveExpr->getValueKind();
9141    OK = ActiveExpr->getObjectKind();
9142  }
9143
9144  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9145                                        resType, VK, OK, RPLoc,
9146                                        resType->isDependentType(),
9147                                        ValueDependent));
9148}
9149
9150//===----------------------------------------------------------------------===//
9151// Clang Extensions.
9152//===----------------------------------------------------------------------===//
9153
9154/// ActOnBlockStart - This callback is invoked when a block literal is started.
9155void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9156  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9157  PushBlockScope(CurScope, Block);
9158  CurContext->addDecl(Block);
9159  if (CurScope)
9160    PushDeclContext(CurScope, Block);
9161  else
9162    CurContext = Block;
9163
9164  getCurBlock()->HasImplicitReturnType = true;
9165
9166  // Enter a new evaluation context to insulate the block from any
9167  // cleanups from the enclosing full-expression.
9168  PushExpressionEvaluationContext(PotentiallyEvaluated);
9169}
9170
9171void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9172                               Scope *CurScope) {
9173  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9174  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9175  BlockScopeInfo *CurBlock = getCurBlock();
9176
9177  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9178  QualType T = Sig->getType();
9179
9180  // FIXME: We should allow unexpanded parameter packs here, but that would,
9181  // in turn, make the block expression contain unexpanded parameter packs.
9182  if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9183    // Drop the parameters.
9184    FunctionProtoType::ExtProtoInfo EPI;
9185    EPI.HasTrailingReturn = false;
9186    EPI.TypeQuals |= DeclSpec::TQ_const;
9187    T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9188                                EPI);
9189    Sig = Context.getTrivialTypeSourceInfo(T);
9190  }
9191
9192  // GetTypeForDeclarator always produces a function type for a block
9193  // literal signature.  Furthermore, it is always a FunctionProtoType
9194  // unless the function was written with a typedef.
9195  assert(T->isFunctionType() &&
9196         "GetTypeForDeclarator made a non-function block signature");
9197
9198  // Look for an explicit signature in that function type.
9199  FunctionProtoTypeLoc ExplicitSignature;
9200
9201  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9202  if (isa<FunctionProtoTypeLoc>(tmp)) {
9203    ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9204
9205    // Check whether that explicit signature was synthesized by
9206    // GetTypeForDeclarator.  If so, don't save that as part of the
9207    // written signature.
9208    if (ExplicitSignature.getLocalRangeBegin() ==
9209        ExplicitSignature.getLocalRangeEnd()) {
9210      // This would be much cheaper if we stored TypeLocs instead of
9211      // TypeSourceInfos.
9212      TypeLoc Result = ExplicitSignature.getResultLoc();
9213      unsigned Size = Result.getFullDataSize();
9214      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9215      Sig->getTypeLoc().initializeFullCopy(Result, Size);
9216
9217      ExplicitSignature = FunctionProtoTypeLoc();
9218    }
9219  }
9220
9221  CurBlock->TheDecl->setSignatureAsWritten(Sig);
9222  CurBlock->FunctionType = T;
9223
9224  const FunctionType *Fn = T->getAs<FunctionType>();
9225  QualType RetTy = Fn->getResultType();
9226  bool isVariadic =
9227    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9228
9229  CurBlock->TheDecl->setIsVariadic(isVariadic);
9230
9231  // Don't allow returning a objc interface by value.
9232  if (RetTy->isObjCObjectType()) {
9233    Diag(ParamInfo.getLocStart(),
9234         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9235    return;
9236  }
9237
9238  // Context.DependentTy is used as a placeholder for a missing block
9239  // return type.  TODO:  what should we do with declarators like:
9240  //   ^ * { ... }
9241  // If the answer is "apply template argument deduction"....
9242  if (RetTy != Context.DependentTy) {
9243    CurBlock->ReturnType = RetTy;
9244    CurBlock->TheDecl->setBlockMissingReturnType(false);
9245    CurBlock->HasImplicitReturnType = false;
9246  }
9247
9248  // Push block parameters from the declarator if we had them.
9249  SmallVector<ParmVarDecl*, 8> Params;
9250  if (ExplicitSignature) {
9251    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9252      ParmVarDecl *Param = ExplicitSignature.getArg(I);
9253      if (Param->getIdentifier() == 0 &&
9254          !Param->isImplicit() &&
9255          !Param->isInvalidDecl() &&
9256          !getLangOpts().CPlusPlus)
9257        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9258      Params.push_back(Param);
9259    }
9260
9261  // Fake up parameter variables if we have a typedef, like
9262  //   ^ fntype { ... }
9263  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9264    for (FunctionProtoType::arg_type_iterator
9265           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9266      ParmVarDecl *Param =
9267        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9268                                   ParamInfo.getLocStart(),
9269                                   *I);
9270      Params.push_back(Param);
9271    }
9272  }
9273
9274  // Set the parameters on the block decl.
9275  if (!Params.empty()) {
9276    CurBlock->TheDecl->setParams(Params);
9277    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9278                             CurBlock->TheDecl->param_end(),
9279                             /*CheckParameterNames=*/false);
9280  }
9281
9282  // Finally we can process decl attributes.
9283  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9284
9285  // Put the parameter variables in scope.  We can bail out immediately
9286  // if we don't have any.
9287  if (Params.empty())
9288    return;
9289
9290  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9291         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9292    (*AI)->setOwningFunction(CurBlock->TheDecl);
9293
9294    // If this has an identifier, add it to the scope stack.
9295    if ((*AI)->getIdentifier()) {
9296      CheckShadow(CurBlock->TheScope, *AI);
9297
9298      PushOnScopeChains(*AI, CurBlock->TheScope);
9299    }
9300  }
9301}
9302
9303/// ActOnBlockError - If there is an error parsing a block, this callback
9304/// is invoked to pop the information about the block from the action impl.
9305void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9306  // Leave the expression-evaluation context.
9307  DiscardCleanupsInEvaluationContext();
9308  PopExpressionEvaluationContext();
9309
9310  // Pop off CurBlock, handle nested blocks.
9311  PopDeclContext();
9312  PopFunctionScopeInfo();
9313}
9314
9315/// ActOnBlockStmtExpr - This is called when the body of a block statement
9316/// literal was successfully completed.  ^(int x){...}
9317ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9318                                    Stmt *Body, Scope *CurScope) {
9319  // If blocks are disabled, emit an error.
9320  if (!LangOpts.Blocks)
9321    Diag(CaretLoc, diag::err_blocks_disable);
9322
9323  // Leave the expression-evaluation context.
9324  if (hasAnyUnrecoverableErrorsInThisFunction())
9325    DiscardCleanupsInEvaluationContext();
9326  assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9327  PopExpressionEvaluationContext();
9328
9329  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9330
9331  PopDeclContext();
9332
9333  QualType RetTy = Context.VoidTy;
9334  if (!BSI->ReturnType.isNull())
9335    RetTy = BSI->ReturnType;
9336
9337  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9338  QualType BlockTy;
9339
9340  // Set the captured variables on the block.
9341  // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9342  SmallVector<BlockDecl::Capture, 4> Captures;
9343  for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9344    CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9345    if (Cap.isThisCapture())
9346      continue;
9347    BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9348                              Cap.isNested(), Cap.getCopyExpr());
9349    Captures.push_back(NewCap);
9350  }
9351  BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9352                            BSI->CXXThisCaptureIndex != 0);
9353
9354  // If the user wrote a function type in some form, try to use that.
9355  if (!BSI->FunctionType.isNull()) {
9356    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9357
9358    FunctionType::ExtInfo Ext = FTy->getExtInfo();
9359    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9360
9361    // Turn protoless block types into nullary block types.
9362    if (isa<FunctionNoProtoType>(FTy)) {
9363      FunctionProtoType::ExtProtoInfo EPI;
9364      EPI.ExtInfo = Ext;
9365      BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9366
9367    // Otherwise, if we don't need to change anything about the function type,
9368    // preserve its sugar structure.
9369    } else if (FTy->getResultType() == RetTy &&
9370               (!NoReturn || FTy->getNoReturnAttr())) {
9371      BlockTy = BSI->FunctionType;
9372
9373    // Otherwise, make the minimal modifications to the function type.
9374    } else {
9375      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9376      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9377      EPI.TypeQuals = 0; // FIXME: silently?
9378      EPI.ExtInfo = Ext;
9379      BlockTy = Context.getFunctionType(RetTy,
9380                                        FPT->arg_type_begin(),
9381                                        FPT->getNumArgs(),
9382                                        EPI);
9383    }
9384
9385  // If we don't have a function type, just build one from nothing.
9386  } else {
9387    FunctionProtoType::ExtProtoInfo EPI;
9388    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9389    BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9390  }
9391
9392  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9393                           BSI->TheDecl->param_end());
9394  BlockTy = Context.getBlockPointerType(BlockTy);
9395
9396  // If needed, diagnose invalid gotos and switches in the block.
9397  if (getCurFunction()->NeedsScopeChecking() &&
9398      !hasAnyUnrecoverableErrorsInThisFunction())
9399    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9400
9401  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9402
9403  computeNRVO(Body, getCurBlock());
9404
9405  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9406  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9407  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9408
9409  // If the block isn't obviously global, i.e. it captures anything at
9410  // all, then we need to do a few things in the surrounding context:
9411  if (Result->getBlockDecl()->hasCaptures()) {
9412    // First, this expression has a new cleanup object.
9413    ExprCleanupObjects.push_back(Result->getBlockDecl());
9414    ExprNeedsCleanups = true;
9415
9416    // It also gets a branch-protected scope if any of the captured
9417    // variables needs destruction.
9418    for (BlockDecl::capture_const_iterator
9419           ci = Result->getBlockDecl()->capture_begin(),
9420           ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9421      const VarDecl *var = ci->getVariable();
9422      if (var->getType().isDestructedType() != QualType::DK_none) {
9423        getCurFunction()->setHasBranchProtectedScope();
9424        break;
9425      }
9426    }
9427  }
9428
9429  return Owned(Result);
9430}
9431
9432ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9433                                        Expr *E, ParsedType Ty,
9434                                        SourceLocation RPLoc) {
9435  TypeSourceInfo *TInfo;
9436  GetTypeFromParser(Ty, &TInfo);
9437  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9438}
9439
9440ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9441                                Expr *E, TypeSourceInfo *TInfo,
9442                                SourceLocation RPLoc) {
9443  Expr *OrigExpr = E;
9444
9445  // Get the va_list type
9446  QualType VaListType = Context.getBuiltinVaListType();
9447  if (VaListType->isArrayType()) {
9448    // Deal with implicit array decay; for example, on x86-64,
9449    // va_list is an array, but it's supposed to decay to
9450    // a pointer for va_arg.
9451    VaListType = Context.getArrayDecayedType(VaListType);
9452    // Make sure the input expression also decays appropriately.
9453    ExprResult Result = UsualUnaryConversions(E);
9454    if (Result.isInvalid())
9455      return ExprError();
9456    E = Result.take();
9457  } else {
9458    // Otherwise, the va_list argument must be an l-value because
9459    // it is modified by va_arg.
9460    if (!E->isTypeDependent() &&
9461        CheckForModifiableLvalue(E, BuiltinLoc, *this))
9462      return ExprError();
9463  }
9464
9465  if (!E->isTypeDependent() &&
9466      !Context.hasSameType(VaListType, E->getType())) {
9467    return ExprError(Diag(E->getLocStart(),
9468                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
9469      << OrigExpr->getType() << E->getSourceRange());
9470  }
9471
9472  if (!TInfo->getType()->isDependentType()) {
9473    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9474                            diag::err_second_parameter_to_va_arg_incomplete,
9475                            TInfo->getTypeLoc()))
9476      return ExprError();
9477
9478    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9479                               TInfo->getType(),
9480                               diag::err_second_parameter_to_va_arg_abstract,
9481                               TInfo->getTypeLoc()))
9482      return ExprError();
9483
9484    if (!TInfo->getType().isPODType(Context)) {
9485      Diag(TInfo->getTypeLoc().getBeginLoc(),
9486           TInfo->getType()->isObjCLifetimeType()
9487             ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9488             : diag::warn_second_parameter_to_va_arg_not_pod)
9489        << TInfo->getType()
9490        << TInfo->getTypeLoc().getSourceRange();
9491    }
9492
9493    // Check for va_arg where arguments of the given type will be promoted
9494    // (i.e. this va_arg is guaranteed to have undefined behavior).
9495    QualType PromoteType;
9496    if (TInfo->getType()->isPromotableIntegerType()) {
9497      PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9498      if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9499        PromoteType = QualType();
9500    }
9501    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9502      PromoteType = Context.DoubleTy;
9503    if (!PromoteType.isNull())
9504      Diag(TInfo->getTypeLoc().getBeginLoc(),
9505          diag::warn_second_parameter_to_va_arg_never_compatible)
9506        << TInfo->getType()
9507        << PromoteType
9508        << TInfo->getTypeLoc().getSourceRange();
9509  }
9510
9511  QualType T = TInfo->getType().getNonLValueExprType(Context);
9512  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9513}
9514
9515ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9516  // The type of __null will be int or long, depending on the size of
9517  // pointers on the target.
9518  QualType Ty;
9519  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9520  if (pw == Context.getTargetInfo().getIntWidth())
9521    Ty = Context.IntTy;
9522  else if (pw == Context.getTargetInfo().getLongWidth())
9523    Ty = Context.LongTy;
9524  else if (pw == Context.getTargetInfo().getLongLongWidth())
9525    Ty = Context.LongLongTy;
9526  else {
9527    llvm_unreachable("I don't know size of pointer!");
9528  }
9529
9530  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9531}
9532
9533static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9534                                           Expr *SrcExpr, FixItHint &Hint) {
9535  if (!SemaRef.getLangOpts().ObjC1)
9536    return;
9537
9538  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9539  if (!PT)
9540    return;
9541
9542  // Check if the destination is of type 'id'.
9543  if (!PT->isObjCIdType()) {
9544    // Check if the destination is the 'NSString' interface.
9545    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9546    if (!ID || !ID->getIdentifier()->isStr("NSString"))
9547      return;
9548  }
9549
9550  // Ignore any parens, implicit casts (should only be
9551  // array-to-pointer decays), and not-so-opaque values.  The last is
9552  // important for making this trigger for property assignments.
9553  SrcExpr = SrcExpr->IgnoreParenImpCasts();
9554  if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9555    if (OV->getSourceExpr())
9556      SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9557
9558  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9559  if (!SL || !SL->isAscii())
9560    return;
9561
9562  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9563}
9564
9565bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9566                                    SourceLocation Loc,
9567                                    QualType DstType, QualType SrcType,
9568                                    Expr *SrcExpr, AssignmentAction Action,
9569                                    bool *Complained) {
9570  if (Complained)
9571    *Complained = false;
9572
9573  // Decode the result (notice that AST's are still created for extensions).
9574  bool CheckInferredResultType = false;
9575  bool isInvalid = false;
9576  unsigned DiagKind = 0;
9577  FixItHint Hint;
9578  ConversionFixItGenerator ConvHints;
9579  bool MayHaveConvFixit = false;
9580  bool MayHaveFunctionDiff = false;
9581
9582  switch (ConvTy) {
9583  case Compatible: return false;
9584  case PointerToInt:
9585    DiagKind = diag::ext_typecheck_convert_pointer_int;
9586    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9587    MayHaveConvFixit = true;
9588    break;
9589  case IntToPointer:
9590    DiagKind = diag::ext_typecheck_convert_int_pointer;
9591    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9592    MayHaveConvFixit = true;
9593    break;
9594  case IncompatiblePointer:
9595    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9596    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9597    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9598      SrcType->isObjCObjectPointerType();
9599    if (Hint.isNull() && !CheckInferredResultType) {
9600      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9601    }
9602    MayHaveConvFixit = true;
9603    break;
9604  case IncompatiblePointerSign:
9605    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9606    break;
9607  case FunctionVoidPointer:
9608    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9609    break;
9610  case IncompatiblePointerDiscardsQualifiers: {
9611    // Perform array-to-pointer decay if necessary.
9612    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9613
9614    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9615    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9616    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9617      DiagKind = diag::err_typecheck_incompatible_address_space;
9618      break;
9619
9620
9621    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9622      DiagKind = diag::err_typecheck_incompatible_ownership;
9623      break;
9624    }
9625
9626    llvm_unreachable("unknown error case for discarding qualifiers!");
9627    // fallthrough
9628  }
9629  case CompatiblePointerDiscardsQualifiers:
9630    // If the qualifiers lost were because we were applying the
9631    // (deprecated) C++ conversion from a string literal to a char*
9632    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9633    // Ideally, this check would be performed in
9634    // checkPointerTypesForAssignment. However, that would require a
9635    // bit of refactoring (so that the second argument is an
9636    // expression, rather than a type), which should be done as part
9637    // of a larger effort to fix checkPointerTypesForAssignment for
9638    // C++ semantics.
9639    if (getLangOpts().CPlusPlus &&
9640        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9641      return false;
9642    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9643    break;
9644  case IncompatibleNestedPointerQualifiers:
9645    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9646    break;
9647  case IntToBlockPointer:
9648    DiagKind = diag::err_int_to_block_pointer;
9649    break;
9650  case IncompatibleBlockPointer:
9651    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9652    break;
9653  case IncompatibleObjCQualifiedId:
9654    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9655    // it can give a more specific diagnostic.
9656    DiagKind = diag::warn_incompatible_qualified_id;
9657    break;
9658  case IncompatibleVectors:
9659    DiagKind = diag::warn_incompatible_vectors;
9660    break;
9661  case IncompatibleObjCWeakRef:
9662    DiagKind = diag::err_arc_weak_unavailable_assign;
9663    break;
9664  case Incompatible:
9665    DiagKind = diag::err_typecheck_convert_incompatible;
9666    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9667    MayHaveConvFixit = true;
9668    isInvalid = true;
9669    MayHaveFunctionDiff = true;
9670    break;
9671  }
9672
9673  QualType FirstType, SecondType;
9674  switch (Action) {
9675  case AA_Assigning:
9676  case AA_Initializing:
9677    // The destination type comes first.
9678    FirstType = DstType;
9679    SecondType = SrcType;
9680    break;
9681
9682  case AA_Returning:
9683  case AA_Passing:
9684  case AA_Converting:
9685  case AA_Sending:
9686  case AA_Casting:
9687    // The source type comes first.
9688    FirstType = SrcType;
9689    SecondType = DstType;
9690    break;
9691  }
9692
9693  PartialDiagnostic FDiag = PDiag(DiagKind);
9694  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9695
9696  // If we can fix the conversion, suggest the FixIts.
9697  assert(ConvHints.isNull() || Hint.isNull());
9698  if (!ConvHints.isNull()) {
9699    for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9700         HE = ConvHints.Hints.end(); HI != HE; ++HI)
9701      FDiag << *HI;
9702  } else {
9703    FDiag << Hint;
9704  }
9705  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9706
9707  if (MayHaveFunctionDiff)
9708    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9709
9710  Diag(Loc, FDiag);
9711
9712  if (SecondType == Context.OverloadTy)
9713    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9714                              FirstType);
9715
9716  if (CheckInferredResultType)
9717    EmitRelatedResultTypeNote(SrcExpr);
9718
9719  if (Complained)
9720    *Complained = true;
9721  return isInvalid;
9722}
9723
9724ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9725                                                 llvm::APSInt *Result) {
9726  class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9727  public:
9728    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9729      S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9730    }
9731  } Diagnoser;
9732
9733  return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9734}
9735
9736ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9737                                                 llvm::APSInt *Result,
9738                                                 unsigned DiagID,
9739                                                 bool AllowFold) {
9740  class IDDiagnoser : public VerifyICEDiagnoser {
9741    unsigned DiagID;
9742
9743  public:
9744    IDDiagnoser(unsigned DiagID)
9745      : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9746
9747    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9748      S.Diag(Loc, DiagID) << SR;
9749    }
9750  } Diagnoser(DiagID);
9751
9752  return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9753}
9754
9755void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9756                                            SourceRange SR) {
9757  S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9758}
9759
9760ExprResult
9761Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9762                                      VerifyICEDiagnoser &Diagnoser,
9763                                      bool AllowFold) {
9764  SourceLocation DiagLoc = E->getLocStart();
9765
9766  if (getLangOpts().CPlusPlus0x) {
9767    // C++11 [expr.const]p5:
9768    //   If an expression of literal class type is used in a context where an
9769    //   integral constant expression is required, then that class type shall
9770    //   have a single non-explicit conversion function to an integral or
9771    //   unscoped enumeration type
9772    ExprResult Converted;
9773    if (!Diagnoser.Suppress) {
9774      class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9775      public:
9776        CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9777
9778        virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9779                                                 QualType T) {
9780          return S.Diag(Loc, diag::err_ice_not_integral) << T;
9781        }
9782
9783        virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9784                                                     SourceLocation Loc,
9785                                                     QualType T) {
9786          return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9787        }
9788
9789        virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9790                                                       SourceLocation Loc,
9791                                                       QualType T,
9792                                                       QualType ConvTy) {
9793          return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9794        }
9795
9796        virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9797                                                   CXXConversionDecl *Conv,
9798                                                   QualType ConvTy) {
9799          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9800                   << ConvTy->isEnumeralType() << ConvTy;
9801        }
9802
9803        virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9804                                                    QualType T) {
9805          return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9806        }
9807
9808        virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9809                                                CXXConversionDecl *Conv,
9810                                                QualType ConvTy) {
9811          return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9812                   << ConvTy->isEnumeralType() << ConvTy;
9813        }
9814
9815        virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9816                                                     SourceLocation Loc,
9817                                                     QualType T,
9818                                                     QualType ConvTy) {
9819          return DiagnosticBuilder::getEmpty();
9820        }
9821      } ConvertDiagnoser;
9822
9823      Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9824                                                     ConvertDiagnoser,
9825                                             /*AllowScopedEnumerations*/ false);
9826    } else {
9827      // The caller wants to silently enquire whether this is an ICE. Don't
9828      // produce any diagnostics if it isn't.
9829      class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9830      public:
9831        SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9832
9833        virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9834                                                 QualType T) {
9835          return DiagnosticBuilder::getEmpty();
9836        }
9837
9838        virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9839                                                     SourceLocation Loc,
9840                                                     QualType T) {
9841          return DiagnosticBuilder::getEmpty();
9842        }
9843
9844        virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9845                                                       SourceLocation Loc,
9846                                                       QualType T,
9847                                                       QualType ConvTy) {
9848          return DiagnosticBuilder::getEmpty();
9849        }
9850
9851        virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9852                                                   CXXConversionDecl *Conv,
9853                                                   QualType ConvTy) {
9854          return DiagnosticBuilder::getEmpty();
9855        }
9856
9857        virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9858                                                    QualType T) {
9859          return DiagnosticBuilder::getEmpty();
9860        }
9861
9862        virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9863                                                CXXConversionDecl *Conv,
9864                                                QualType ConvTy) {
9865          return DiagnosticBuilder::getEmpty();
9866        }
9867
9868        virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9869                                                     SourceLocation Loc,
9870                                                     QualType T,
9871                                                     QualType ConvTy) {
9872          return DiagnosticBuilder::getEmpty();
9873        }
9874      } ConvertDiagnoser;
9875
9876      Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9877                                                     ConvertDiagnoser, false);
9878    }
9879    if (Converted.isInvalid())
9880      return Converted;
9881    E = Converted.take();
9882    if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9883      return ExprError();
9884  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9885    // An ICE must be of integral or unscoped enumeration type.
9886    if (!Diagnoser.Suppress)
9887      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9888    return ExprError();
9889  }
9890
9891  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9892  // in the non-ICE case.
9893  if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9894    if (Result)
9895      *Result = E->EvaluateKnownConstInt(Context);
9896    return Owned(E);
9897  }
9898
9899  Expr::EvalResult EvalResult;
9900  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9901  EvalResult.Diag = &Notes;
9902
9903  // Try to evaluate the expression, and produce diagnostics explaining why it's
9904  // not a constant expression as a side-effect.
9905  bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9906                EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9907
9908  // In C++11, we can rely on diagnostics being produced for any expression
9909  // which is not a constant expression. If no diagnostics were produced, then
9910  // this is a constant expression.
9911  if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
9912    if (Result)
9913      *Result = EvalResult.Val.getInt();
9914    return Owned(E);
9915  }
9916
9917  // If our only note is the usual "invalid subexpression" note, just point
9918  // the caret at its location rather than producing an essentially
9919  // redundant note.
9920  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9921        diag::note_invalid_subexpr_in_const_expr) {
9922    DiagLoc = Notes[0].first;
9923    Notes.clear();
9924  }
9925
9926  if (!Folded || !AllowFold) {
9927    if (!Diagnoser.Suppress) {
9928      Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9929      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9930        Diag(Notes[I].first, Notes[I].second);
9931    }
9932
9933    return ExprError();
9934  }
9935
9936  Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
9937  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9938    Diag(Notes[I].first, Notes[I].second);
9939
9940  if (Result)
9941    *Result = EvalResult.Val.getInt();
9942  return Owned(E);
9943}
9944
9945namespace {
9946  // Handle the case where we conclude a expression which we speculatively
9947  // considered to be unevaluated is actually evaluated.
9948  class TransformToPE : public TreeTransform<TransformToPE> {
9949    typedef TreeTransform<TransformToPE> BaseTransform;
9950
9951  public:
9952    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9953
9954    // Make sure we redo semantic analysis
9955    bool AlwaysRebuild() { return true; }
9956
9957    // Make sure we handle LabelStmts correctly.
9958    // FIXME: This does the right thing, but maybe we need a more general
9959    // fix to TreeTransform?
9960    StmtResult TransformLabelStmt(LabelStmt *S) {
9961      S->getDecl()->setStmt(0);
9962      return BaseTransform::TransformLabelStmt(S);
9963    }
9964
9965    // We need to special-case DeclRefExprs referring to FieldDecls which
9966    // are not part of a member pointer formation; normal TreeTransforming
9967    // doesn't catch this case because of the way we represent them in the AST.
9968    // FIXME: This is a bit ugly; is it really the best way to handle this
9969    // case?
9970    //
9971    // Error on DeclRefExprs referring to FieldDecls.
9972    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9973      if (isa<FieldDecl>(E->getDecl()) &&
9974          SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9975        return SemaRef.Diag(E->getLocation(),
9976                            diag::err_invalid_non_static_member_use)
9977            << E->getDecl() << E->getSourceRange();
9978
9979      return BaseTransform::TransformDeclRefExpr(E);
9980    }
9981
9982    // Exception: filter out member pointer formation
9983    ExprResult TransformUnaryOperator(UnaryOperator *E) {
9984      if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9985        return E;
9986
9987      return BaseTransform::TransformUnaryOperator(E);
9988    }
9989
9990    ExprResult TransformLambdaExpr(LambdaExpr *E) {
9991      // Lambdas never need to be transformed.
9992      return E;
9993    }
9994  };
9995}
9996
9997ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
9998  assert(ExprEvalContexts.back().Context == Unevaluated &&
9999         "Should only transform unevaluated expressions");
10000  ExprEvalContexts.back().Context =
10001      ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10002  if (ExprEvalContexts.back().Context == Unevaluated)
10003    return E;
10004  return TransformToPE(*this).TransformExpr(E);
10005}
10006
10007void
10008Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10009                                      Decl *LambdaContextDecl,
10010                                      bool IsDecltype) {
10011  ExprEvalContexts.push_back(
10012             ExpressionEvaluationContextRecord(NewContext,
10013                                               ExprCleanupObjects.size(),
10014                                               ExprNeedsCleanups,
10015                                               LambdaContextDecl,
10016                                               IsDecltype));
10017  ExprNeedsCleanups = false;
10018  if (!MaybeODRUseExprs.empty())
10019    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10020}
10021
10022void Sema::PopExpressionEvaluationContext() {
10023  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10024
10025  if (!Rec.Lambdas.empty()) {
10026    if (Rec.Context == Unevaluated) {
10027      // C++11 [expr.prim.lambda]p2:
10028      //   A lambda-expression shall not appear in an unevaluated operand
10029      //   (Clause 5).
10030      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10031        Diag(Rec.Lambdas[I]->getLocStart(),
10032             diag::err_lambda_unevaluated_operand);
10033    } else {
10034      // Mark the capture expressions odr-used. This was deferred
10035      // during lambda expression creation.
10036      for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10037        LambdaExpr *Lambda = Rec.Lambdas[I];
10038        for (LambdaExpr::capture_init_iterator
10039                  C = Lambda->capture_init_begin(),
10040               CEnd = Lambda->capture_init_end();
10041             C != CEnd; ++C) {
10042          MarkDeclarationsReferencedInExpr(*C);
10043        }
10044      }
10045    }
10046  }
10047
10048  // When are coming out of an unevaluated context, clear out any
10049  // temporaries that we may have created as part of the evaluation of
10050  // the expression in that context: they aren't relevant because they
10051  // will never be constructed.
10052  if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10053    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10054                             ExprCleanupObjects.end());
10055    ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10056    CleanupVarDeclMarking();
10057    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10058  // Otherwise, merge the contexts together.
10059  } else {
10060    ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10061    MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10062                            Rec.SavedMaybeODRUseExprs.end());
10063  }
10064
10065  // Pop the current expression evaluation context off the stack.
10066  ExprEvalContexts.pop_back();
10067}
10068
10069void Sema::DiscardCleanupsInEvaluationContext() {
10070  ExprCleanupObjects.erase(
10071         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10072         ExprCleanupObjects.end());
10073  ExprNeedsCleanups = false;
10074  MaybeODRUseExprs.clear();
10075}
10076
10077ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10078  if (!E->getType()->isVariablyModifiedType())
10079    return E;
10080  return TranformToPotentiallyEvaluated(E);
10081}
10082
10083static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10084  // Do not mark anything as "used" within a dependent context; wait for
10085  // an instantiation.
10086  if (SemaRef.CurContext->isDependentContext())
10087    return false;
10088
10089  switch (SemaRef.ExprEvalContexts.back().Context) {
10090    case Sema::Unevaluated:
10091      // We are in an expression that is not potentially evaluated; do nothing.
10092      // (Depending on how you read the standard, we actually do need to do
10093      // something here for null pointer constants, but the standard's
10094      // definition of a null pointer constant is completely crazy.)
10095      return false;
10096
10097    case Sema::ConstantEvaluated:
10098    case Sema::PotentiallyEvaluated:
10099      // We are in a potentially evaluated expression (or a constant-expression
10100      // in C++03); we need to do implicit template instantiation, implicitly
10101      // define class members, and mark most declarations as used.
10102      return true;
10103
10104    case Sema::PotentiallyEvaluatedIfUsed:
10105      // Referenced declarations will only be used if the construct in the
10106      // containing expression is used.
10107      return false;
10108  }
10109  llvm_unreachable("Invalid context");
10110}
10111
10112/// \brief Mark a function referenced, and check whether it is odr-used
10113/// (C++ [basic.def.odr]p2, C99 6.9p3)
10114void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10115  assert(Func && "No function?");
10116
10117  Func->setReferenced();
10118
10119  // Don't mark this function as used multiple times, unless it's a constexpr
10120  // function which we need to instantiate.
10121  if (Func->isUsed(false) &&
10122      !(Func->isConstexpr() && !Func->getBody() &&
10123        Func->isImplicitlyInstantiable()))
10124    return;
10125
10126  if (!IsPotentiallyEvaluatedContext(*this))
10127    return;
10128
10129  // Note that this declaration has been used.
10130  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10131    if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10132      if (Constructor->isDefaultConstructor()) {
10133        if (Constructor->isTrivial())
10134          return;
10135        if (!Constructor->isUsed(false))
10136          DefineImplicitDefaultConstructor(Loc, Constructor);
10137      } else if (Constructor->isCopyConstructor()) {
10138        if (!Constructor->isUsed(false))
10139          DefineImplicitCopyConstructor(Loc, Constructor);
10140      } else if (Constructor->isMoveConstructor()) {
10141        if (!Constructor->isUsed(false))
10142          DefineImplicitMoveConstructor(Loc, Constructor);
10143      }
10144    }
10145
10146    MarkVTableUsed(Loc, Constructor->getParent());
10147  } else if (CXXDestructorDecl *Destructor =
10148                 dyn_cast<CXXDestructorDecl>(Func)) {
10149    if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10150        !Destructor->isUsed(false))
10151      DefineImplicitDestructor(Loc, Destructor);
10152    if (Destructor->isVirtual())
10153      MarkVTableUsed(Loc, Destructor->getParent());
10154  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10155    if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10156        MethodDecl->isOverloadedOperator() &&
10157        MethodDecl->getOverloadedOperator() == OO_Equal) {
10158      if (!MethodDecl->isUsed(false)) {
10159        if (MethodDecl->isCopyAssignmentOperator())
10160          DefineImplicitCopyAssignment(Loc, MethodDecl);
10161        else
10162          DefineImplicitMoveAssignment(Loc, MethodDecl);
10163      }
10164    } else if (isa<CXXConversionDecl>(MethodDecl) &&
10165               MethodDecl->getParent()->isLambda()) {
10166      CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10167      if (Conversion->isLambdaToBlockPointerConversion())
10168        DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10169      else
10170        DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10171    } else if (MethodDecl->isVirtual())
10172      MarkVTableUsed(Loc, MethodDecl->getParent());
10173  }
10174
10175  // Recursive functions should be marked when used from another function.
10176  // FIXME: Is this really right?
10177  if (CurContext == Func) return;
10178
10179  // Instantiate the exception specification for any function which is
10180  // used: CodeGen will need it.
10181  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10182  if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
10183    InstantiateExceptionSpec(Loc, Func);
10184
10185  // Implicit instantiation of function templates and member functions of
10186  // class templates.
10187  if (Func->isImplicitlyInstantiable()) {
10188    bool AlreadyInstantiated = false;
10189    SourceLocation PointOfInstantiation = Loc;
10190    if (FunctionTemplateSpecializationInfo *SpecInfo
10191                              = Func->getTemplateSpecializationInfo()) {
10192      if (SpecInfo->getPointOfInstantiation().isInvalid())
10193        SpecInfo->setPointOfInstantiation(Loc);
10194      else if (SpecInfo->getTemplateSpecializationKind()
10195                 == TSK_ImplicitInstantiation) {
10196        AlreadyInstantiated = true;
10197        PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10198      }
10199    } else if (MemberSpecializationInfo *MSInfo
10200                                = Func->getMemberSpecializationInfo()) {
10201      if (MSInfo->getPointOfInstantiation().isInvalid())
10202        MSInfo->setPointOfInstantiation(Loc);
10203      else if (MSInfo->getTemplateSpecializationKind()
10204                 == TSK_ImplicitInstantiation) {
10205        AlreadyInstantiated = true;
10206        PointOfInstantiation = MSInfo->getPointOfInstantiation();
10207      }
10208    }
10209
10210    if (!AlreadyInstantiated || Func->isConstexpr()) {
10211      if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10212          cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10213        PendingLocalImplicitInstantiations.push_back(
10214            std::make_pair(Func, PointOfInstantiation));
10215      else if (Func->isConstexpr())
10216        // Do not defer instantiations of constexpr functions, to avoid the
10217        // expression evaluator needing to call back into Sema if it sees a
10218        // call to such a function.
10219        InstantiateFunctionDefinition(PointOfInstantiation, Func);
10220      else {
10221        PendingInstantiations.push_back(std::make_pair(Func,
10222                                                       PointOfInstantiation));
10223        // Notify the consumer that a function was implicitly instantiated.
10224        Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10225      }
10226    }
10227  } else {
10228    // Walk redefinitions, as some of them may be instantiable.
10229    for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10230         e(Func->redecls_end()); i != e; ++i) {
10231      if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10232        MarkFunctionReferenced(Loc, *i);
10233    }
10234  }
10235
10236  // Keep track of used but undefined functions.
10237  if (!Func->isPure() && !Func->hasBody() &&
10238      Func->getLinkage() != ExternalLinkage) {
10239    SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10240    if (old.isInvalid()) old = Loc;
10241  }
10242
10243  Func->setUsed(true);
10244}
10245
10246static void
10247diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10248                                   VarDecl *var, DeclContext *DC) {
10249  DeclContext *VarDC = var->getDeclContext();
10250
10251  //  If the parameter still belongs to the translation unit, then
10252  //  we're actually just using one parameter in the declaration of
10253  //  the next.
10254  if (isa<ParmVarDecl>(var) &&
10255      isa<TranslationUnitDecl>(VarDC))
10256    return;
10257
10258  // For C code, don't diagnose about capture if we're not actually in code
10259  // right now; it's impossible to write a non-constant expression outside of
10260  // function context, so we'll get other (more useful) diagnostics later.
10261  //
10262  // For C++, things get a bit more nasty... it would be nice to suppress this
10263  // diagnostic for certain cases like using a local variable in an array bound
10264  // for a member of a local class, but the correct predicate is not obvious.
10265  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10266    return;
10267
10268  if (isa<CXXMethodDecl>(VarDC) &&
10269      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10270    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10271      << var->getIdentifier();
10272  } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10273    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10274      << var->getIdentifier() << fn->getDeclName();
10275  } else if (isa<BlockDecl>(VarDC)) {
10276    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10277      << var->getIdentifier();
10278  } else {
10279    // FIXME: Is there any other context where a local variable can be
10280    // declared?
10281    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10282      << var->getIdentifier();
10283  }
10284
10285  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10286    << var->getIdentifier();
10287
10288  // FIXME: Add additional diagnostic info about class etc. which prevents
10289  // capture.
10290}
10291
10292/// \brief Capture the given variable in the given lambda expression.
10293static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10294                                  VarDecl *Var, QualType FieldType,
10295                                  QualType DeclRefType,
10296                                  SourceLocation Loc,
10297                                  bool RefersToEnclosingLocal) {
10298  CXXRecordDecl *Lambda = LSI->Lambda;
10299
10300  // Build the non-static data member.
10301  FieldDecl *Field
10302    = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10303                        S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10304                        0, false, ICIS_NoInit);
10305  Field->setImplicit(true);
10306  Field->setAccess(AS_private);
10307  Lambda->addDecl(Field);
10308
10309  // C++11 [expr.prim.lambda]p21:
10310  //   When the lambda-expression is evaluated, the entities that
10311  //   are captured by copy are used to direct-initialize each
10312  //   corresponding non-static data member of the resulting closure
10313  //   object. (For array members, the array elements are
10314  //   direct-initialized in increasing subscript order.) These
10315  //   initializations are performed in the (unspecified) order in
10316  //   which the non-static data members are declared.
10317
10318  // Introduce a new evaluation context for the initialization, so
10319  // that temporaries introduced as part of the capture are retained
10320  // to be re-"exported" from the lambda expression itself.
10321  S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10322
10323  // C++ [expr.prim.labda]p12:
10324  //   An entity captured by a lambda-expression is odr-used (3.2) in
10325  //   the scope containing the lambda-expression.
10326  Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10327                                          DeclRefType, VK_LValue, Loc);
10328  Var->setReferenced(true);
10329  Var->setUsed(true);
10330
10331  // When the field has array type, create index variables for each
10332  // dimension of the array. We use these index variables to subscript
10333  // the source array, and other clients (e.g., CodeGen) will perform
10334  // the necessary iteration with these index variables.
10335  SmallVector<VarDecl *, 4> IndexVariables;
10336  QualType BaseType = FieldType;
10337  QualType SizeType = S.Context.getSizeType();
10338  LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10339  while (const ConstantArrayType *Array
10340                        = S.Context.getAsConstantArrayType(BaseType)) {
10341    // Create the iteration variable for this array index.
10342    IdentifierInfo *IterationVarName = 0;
10343    {
10344      SmallString<8> Str;
10345      llvm::raw_svector_ostream OS(Str);
10346      OS << "__i" << IndexVariables.size();
10347      IterationVarName = &S.Context.Idents.get(OS.str());
10348    }
10349    VarDecl *IterationVar
10350      = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10351                        IterationVarName, SizeType,
10352                        S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10353                        SC_None, SC_None);
10354    IndexVariables.push_back(IterationVar);
10355    LSI->ArrayIndexVars.push_back(IterationVar);
10356
10357    // Create a reference to the iteration variable.
10358    ExprResult IterationVarRef
10359      = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10360    assert(!IterationVarRef.isInvalid() &&
10361           "Reference to invented variable cannot fail!");
10362    IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10363    assert(!IterationVarRef.isInvalid() &&
10364           "Conversion of invented variable cannot fail!");
10365
10366    // Subscript the array with this iteration variable.
10367    ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10368                             Ref, Loc, IterationVarRef.take(), Loc);
10369    if (Subscript.isInvalid()) {
10370      S.CleanupVarDeclMarking();
10371      S.DiscardCleanupsInEvaluationContext();
10372      S.PopExpressionEvaluationContext();
10373      return ExprError();
10374    }
10375
10376    Ref = Subscript.take();
10377    BaseType = Array->getElementType();
10378  }
10379
10380  // Construct the entity that we will be initializing. For an array, this
10381  // will be first element in the array, which may require several levels
10382  // of array-subscript entities.
10383  SmallVector<InitializedEntity, 4> Entities;
10384  Entities.reserve(1 + IndexVariables.size());
10385  Entities.push_back(
10386    InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10387  for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10388    Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10389                                                            0,
10390                                                            Entities.back()));
10391
10392  InitializationKind InitKind
10393    = InitializationKind::CreateDirect(Loc, Loc, Loc);
10394  InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10395  ExprResult Result(true);
10396  if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10397    Result = Init.Perform(S, Entities.back(), InitKind,
10398                          MultiExprArg(S, &Ref, 1));
10399
10400  // If this initialization requires any cleanups (e.g., due to a
10401  // default argument to a copy constructor), note that for the
10402  // lambda.
10403  if (S.ExprNeedsCleanups)
10404    LSI->ExprNeedsCleanups = true;
10405
10406  // Exit the expression evaluation context used for the capture.
10407  S.CleanupVarDeclMarking();
10408  S.DiscardCleanupsInEvaluationContext();
10409  S.PopExpressionEvaluationContext();
10410  return Result;
10411}
10412
10413bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10414                              TryCaptureKind Kind, SourceLocation EllipsisLoc,
10415                              bool BuildAndDiagnose,
10416                              QualType &CaptureType,
10417                              QualType &DeclRefType) {
10418  bool Nested = false;
10419
10420  DeclContext *DC = CurContext;
10421  if (Var->getDeclContext() == DC) return true;
10422  if (!Var->hasLocalStorage()) return true;
10423
10424  bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10425
10426  // Walk up the stack to determine whether we can capture the variable,
10427  // performing the "simple" checks that don't depend on type. We stop when
10428  // we've either hit the declared scope of the variable or find an existing
10429  // capture of that variable.
10430  CaptureType = Var->getType();
10431  DeclRefType = CaptureType.getNonReferenceType();
10432  bool Explicit = (Kind != TryCapture_Implicit);
10433  unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10434  do {
10435    // Only block literals and lambda expressions can capture; other
10436    // scopes don't work.
10437    DeclContext *ParentDC;
10438    if (isa<BlockDecl>(DC))
10439      ParentDC = DC->getParent();
10440    else if (isa<CXXMethodDecl>(DC) &&
10441             cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10442             cast<CXXRecordDecl>(DC->getParent())->isLambda())
10443      ParentDC = DC->getParent()->getParent();
10444    else {
10445      if (BuildAndDiagnose)
10446        diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10447      return true;
10448    }
10449
10450    CapturingScopeInfo *CSI =
10451      cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10452
10453    // Check whether we've already captured it.
10454    if (CSI->CaptureMap.count(Var)) {
10455      // If we found a capture, any subcaptures are nested.
10456      Nested = true;
10457
10458      // Retrieve the capture type for this variable.
10459      CaptureType = CSI->getCapture(Var).getCaptureType();
10460
10461      // Compute the type of an expression that refers to this variable.
10462      DeclRefType = CaptureType.getNonReferenceType();
10463
10464      const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10465      if (Cap.isCopyCapture() &&
10466          !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10467        DeclRefType.addConst();
10468      break;
10469    }
10470
10471    bool IsBlock = isa<BlockScopeInfo>(CSI);
10472    bool IsLambda = !IsBlock;
10473
10474    // Lambdas are not allowed to capture unnamed variables
10475    // (e.g. anonymous unions).
10476    // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10477    // assuming that's the intent.
10478    if (IsLambda && !Var->getDeclName()) {
10479      if (BuildAndDiagnose) {
10480        Diag(Loc, diag::err_lambda_capture_anonymous_var);
10481        Diag(Var->getLocation(), diag::note_declared_at);
10482      }
10483      return true;
10484    }
10485
10486    // Prohibit variably-modified types; they're difficult to deal with.
10487    if (Var->getType()->isVariablyModifiedType()) {
10488      if (BuildAndDiagnose) {
10489        if (IsBlock)
10490          Diag(Loc, diag::err_ref_vm_type);
10491        else
10492          Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10493        Diag(Var->getLocation(), diag::note_previous_decl)
10494          << Var->getDeclName();
10495      }
10496      return true;
10497    }
10498
10499    // Lambdas are not allowed to capture __block variables; they don't
10500    // support the expected semantics.
10501    if (IsLambda && HasBlocksAttr) {
10502      if (BuildAndDiagnose) {
10503        Diag(Loc, diag::err_lambda_capture_block)
10504          << Var->getDeclName();
10505        Diag(Var->getLocation(), diag::note_previous_decl)
10506          << Var->getDeclName();
10507      }
10508      return true;
10509    }
10510
10511    if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10512      // No capture-default
10513      if (BuildAndDiagnose) {
10514        Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10515        Diag(Var->getLocation(), diag::note_previous_decl)
10516          << Var->getDeclName();
10517        Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10518             diag::note_lambda_decl);
10519      }
10520      return true;
10521    }
10522
10523    FunctionScopesIndex--;
10524    DC = ParentDC;
10525    Explicit = false;
10526  } while (!Var->getDeclContext()->Equals(DC));
10527
10528  // Walk back down the scope stack, computing the type of the capture at
10529  // each step, checking type-specific requirements, and adding captures if
10530  // requested.
10531  for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10532       ++I) {
10533    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10534
10535    // Compute the type of the capture and of a reference to the capture within
10536    // this scope.
10537    if (isa<BlockScopeInfo>(CSI)) {
10538      Expr *CopyExpr = 0;
10539      bool ByRef = false;
10540
10541      // Blocks are not allowed to capture arrays.
10542      if (CaptureType->isArrayType()) {
10543        if (BuildAndDiagnose) {
10544          Diag(Loc, diag::err_ref_array_type);
10545          Diag(Var->getLocation(), diag::note_previous_decl)
10546          << Var->getDeclName();
10547        }
10548        return true;
10549      }
10550
10551      // Forbid the block-capture of autoreleasing variables.
10552      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10553        if (BuildAndDiagnose) {
10554          Diag(Loc, diag::err_arc_autoreleasing_capture)
10555            << /*block*/ 0;
10556          Diag(Var->getLocation(), diag::note_previous_decl)
10557            << Var->getDeclName();
10558        }
10559        return true;
10560      }
10561
10562      if (HasBlocksAttr || CaptureType->isReferenceType()) {
10563        // Block capture by reference does not change the capture or
10564        // declaration reference types.
10565        ByRef = true;
10566      } else {
10567        // Block capture by copy introduces 'const'.
10568        CaptureType = CaptureType.getNonReferenceType().withConst();
10569        DeclRefType = CaptureType;
10570
10571        if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10572          if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10573            // The capture logic needs the destructor, so make sure we mark it.
10574            // Usually this is unnecessary because most local variables have
10575            // their destructors marked at declaration time, but parameters are
10576            // an exception because it's technically only the call site that
10577            // actually requires the destructor.
10578            if (isa<ParmVarDecl>(Var))
10579              FinalizeVarWithDestructor(Var, Record);
10580
10581            // According to the blocks spec, the capture of a variable from
10582            // the stack requires a const copy constructor.  This is not true
10583            // of the copy/move done to move a __block variable to the heap.
10584            Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10585                                                      DeclRefType.withConst(),
10586                                                      VK_LValue, Loc);
10587            ExprResult Result
10588              = PerformCopyInitialization(
10589                  InitializedEntity::InitializeBlock(Var->getLocation(),
10590                                                     CaptureType, false),
10591                  Loc, Owned(DeclRef));
10592
10593            // Build a full-expression copy expression if initialization
10594            // succeeded and used a non-trivial constructor.  Recover from
10595            // errors by pretending that the copy isn't necessary.
10596            if (!Result.isInvalid() &&
10597                !cast<CXXConstructExpr>(Result.get())->getConstructor()
10598                   ->isTrivial()) {
10599              Result = MaybeCreateExprWithCleanups(Result);
10600              CopyExpr = Result.take();
10601            }
10602          }
10603        }
10604      }
10605
10606      // Actually capture the variable.
10607      if (BuildAndDiagnose)
10608        CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10609                        SourceLocation(), CaptureType, CopyExpr);
10610      Nested = true;
10611      continue;
10612    }
10613
10614    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10615
10616    // Determine whether we are capturing by reference or by value.
10617    bool ByRef = false;
10618    if (I == N - 1 && Kind != TryCapture_Implicit) {
10619      ByRef = (Kind == TryCapture_ExplicitByRef);
10620    } else {
10621      ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10622    }
10623
10624    // Compute the type of the field that will capture this variable.
10625    if (ByRef) {
10626      // C++11 [expr.prim.lambda]p15:
10627      //   An entity is captured by reference if it is implicitly or
10628      //   explicitly captured but not captured by copy. It is
10629      //   unspecified whether additional unnamed non-static data
10630      //   members are declared in the closure type for entities
10631      //   captured by reference.
10632      //
10633      // FIXME: It is not clear whether we want to build an lvalue reference
10634      // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10635      // to do the former, while EDG does the latter. Core issue 1249 will
10636      // clarify, but for now we follow GCC because it's a more permissive and
10637      // easily defensible position.
10638      CaptureType = Context.getLValueReferenceType(DeclRefType);
10639    } else {
10640      // C++11 [expr.prim.lambda]p14:
10641      //   For each entity captured by copy, an unnamed non-static
10642      //   data member is declared in the closure type. The
10643      //   declaration order of these members is unspecified. The type
10644      //   of such a data member is the type of the corresponding
10645      //   captured entity if the entity is not a reference to an
10646      //   object, or the referenced type otherwise. [Note: If the
10647      //   captured entity is a reference to a function, the
10648      //   corresponding data member is also a reference to a
10649      //   function. - end note ]
10650      if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10651        if (!RefType->getPointeeType()->isFunctionType())
10652          CaptureType = RefType->getPointeeType();
10653      }
10654
10655      // Forbid the lambda copy-capture of autoreleasing variables.
10656      if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10657        if (BuildAndDiagnose) {
10658          Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10659          Diag(Var->getLocation(), diag::note_previous_decl)
10660            << Var->getDeclName();
10661        }
10662        return true;
10663      }
10664    }
10665
10666    // Capture this variable in the lambda.
10667    Expr *CopyExpr = 0;
10668    if (BuildAndDiagnose) {
10669      ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10670                                          DeclRefType, Loc,
10671                                          I == N-1);
10672      if (!Result.isInvalid())
10673        CopyExpr = Result.take();
10674    }
10675
10676    // Compute the type of a reference to this captured variable.
10677    if (ByRef)
10678      DeclRefType = CaptureType.getNonReferenceType();
10679    else {
10680      // C++ [expr.prim.lambda]p5:
10681      //   The closure type for a lambda-expression has a public inline
10682      //   function call operator [...]. This function call operator is
10683      //   declared const (9.3.1) if and only if the lambda-expression’s
10684      //   parameter-declaration-clause is not followed by mutable.
10685      DeclRefType = CaptureType.getNonReferenceType();
10686      if (!LSI->Mutable && !CaptureType->isReferenceType())
10687        DeclRefType.addConst();
10688    }
10689
10690    // Add the capture.
10691    if (BuildAndDiagnose)
10692      CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10693                      EllipsisLoc, CaptureType, CopyExpr);
10694    Nested = true;
10695  }
10696
10697  return false;
10698}
10699
10700bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10701                              TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10702  QualType CaptureType;
10703  QualType DeclRefType;
10704  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10705                            /*BuildAndDiagnose=*/true, CaptureType,
10706                            DeclRefType);
10707}
10708
10709QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10710  QualType CaptureType;
10711  QualType DeclRefType;
10712
10713  // Determine whether we can capture this variable.
10714  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10715                         /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10716    return QualType();
10717
10718  return DeclRefType;
10719}
10720
10721static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10722                               SourceLocation Loc) {
10723  // Keep track of used but undefined variables.
10724  // FIXME: We shouldn't suppress this warning for static data members.
10725  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10726      Var->getLinkage() != ExternalLinkage &&
10727      !(Var->isStaticDataMember() && Var->hasInit())) {
10728    SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10729    if (old.isInvalid()) old = Loc;
10730  }
10731
10732  SemaRef.tryCaptureVariable(Var, Loc);
10733
10734  Var->setUsed(true);
10735}
10736
10737void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10738  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10739  // an object that satisfies the requirements for appearing in a
10740  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10741  // is immediately applied."  This function handles the lvalue-to-rvalue
10742  // conversion part.
10743  MaybeODRUseExprs.erase(E->IgnoreParens());
10744}
10745
10746ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10747  if (!Res.isUsable())
10748    return Res;
10749
10750  // If a constant-expression is a reference to a variable where we delay
10751  // deciding whether it is an odr-use, just assume we will apply the
10752  // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10753  // (a non-type template argument), we have special handling anyway.
10754  UpdateMarkingForLValueToRValue(Res.get());
10755  return Res;
10756}
10757
10758void Sema::CleanupVarDeclMarking() {
10759  for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10760                                        e = MaybeODRUseExprs.end();
10761       i != e; ++i) {
10762    VarDecl *Var;
10763    SourceLocation Loc;
10764    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10765      Var = cast<VarDecl>(DRE->getDecl());
10766      Loc = DRE->getLocation();
10767    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10768      Var = cast<VarDecl>(ME->getMemberDecl());
10769      Loc = ME->getMemberLoc();
10770    } else {
10771      llvm_unreachable("Unexpcted expression");
10772    }
10773
10774    MarkVarDeclODRUsed(*this, Var, Loc);
10775  }
10776
10777  MaybeODRUseExprs.clear();
10778}
10779
10780// Mark a VarDecl referenced, and perform the necessary handling to compute
10781// odr-uses.
10782static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10783                                    VarDecl *Var, Expr *E) {
10784  Var->setReferenced();
10785
10786  if (!IsPotentiallyEvaluatedContext(SemaRef))
10787    return;
10788
10789  // Implicit instantiation of static data members of class templates.
10790  if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10791    MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10792    assert(MSInfo && "Missing member specialization information?");
10793    bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10794    if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10795        (!AlreadyInstantiated ||
10796         Var->isUsableInConstantExpressions(SemaRef.Context))) {
10797      if (!AlreadyInstantiated) {
10798        // This is a modification of an existing AST node. Notify listeners.
10799        if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10800          L->StaticDataMemberInstantiated(Var);
10801        MSInfo->setPointOfInstantiation(Loc);
10802      }
10803      SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10804      if (Var->isUsableInConstantExpressions(SemaRef.Context))
10805        // Do not defer instantiations of variables which could be used in a
10806        // constant expression.
10807        SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10808      else
10809        SemaRef.PendingInstantiations.push_back(
10810            std::make_pair(Var, PointOfInstantiation));
10811    }
10812  }
10813
10814  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10815  // an object that satisfies the requirements for appearing in a
10816  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10817  // is immediately applied."  We check the first part here, and
10818  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10819  // Note that we use the C++11 definition everywhere because nothing in
10820  // C++03 depends on whether we get the C++03 version correct. This does not
10821  // apply to references, since they are not objects.
10822  const VarDecl *DefVD;
10823  if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10824      Var->isUsableInConstantExpressions(SemaRef.Context) &&
10825      Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10826    SemaRef.MaybeODRUseExprs.insert(E);
10827  else
10828    MarkVarDeclODRUsed(SemaRef, Var, Loc);
10829}
10830
10831/// \brief Mark a variable referenced, and check whether it is odr-used
10832/// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10833/// used directly for normal expressions referring to VarDecl.
10834void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10835  DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10836}
10837
10838static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10839                               Decl *D, Expr *E) {
10840  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10841    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10842    return;
10843  }
10844
10845  SemaRef.MarkAnyDeclReferenced(Loc, D);
10846
10847  // If this is a call to a method via a cast, also mark the method in the
10848  // derived class used in case codegen can devirtualize the call.
10849  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10850  if (!ME)
10851    return;
10852  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10853  if (!MD)
10854    return;
10855  const Expr *Base = ME->getBase();
10856  if (Base->getType()->isDependentType())
10857    return;
10858  const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
10859  if (!MostDerivedClassDecl)
10860    return;
10861  CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
10862  if (!DM)
10863    return;
10864  SemaRef.MarkAnyDeclReferenced(Loc, DM);
10865}
10866
10867/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10868void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10869  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10870}
10871
10872/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10873void Sema::MarkMemberReferenced(MemberExpr *E) {
10874  MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10875}
10876
10877/// \brief Perform marking for a reference to an arbitrary declaration.  It
10878/// marks the declaration referenced, and performs odr-use checking for functions
10879/// and variables. This method should not be used when building an normal
10880/// expression which refers to a variable.
10881void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10882  if (VarDecl *VD = dyn_cast<VarDecl>(D))
10883    MarkVariableReferenced(Loc, VD);
10884  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10885    MarkFunctionReferenced(Loc, FD);
10886  else
10887    D->setReferenced();
10888}
10889
10890namespace {
10891  // Mark all of the declarations referenced
10892  // FIXME: Not fully implemented yet! We need to have a better understanding
10893  // of when we're entering
10894  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10895    Sema &S;
10896    SourceLocation Loc;
10897
10898  public:
10899    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10900
10901    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10902
10903    bool TraverseTemplateArgument(const TemplateArgument &Arg);
10904    bool TraverseRecordType(RecordType *T);
10905  };
10906}
10907
10908bool MarkReferencedDecls::TraverseTemplateArgument(
10909  const TemplateArgument &Arg) {
10910  if (Arg.getKind() == TemplateArgument::Declaration) {
10911    if (Decl *D = Arg.getAsDecl())
10912      S.MarkAnyDeclReferenced(Loc, D);
10913  }
10914
10915  return Inherited::TraverseTemplateArgument(Arg);
10916}
10917
10918bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10919  if (ClassTemplateSpecializationDecl *Spec
10920                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10921    const TemplateArgumentList &Args = Spec->getTemplateArgs();
10922    return TraverseTemplateArguments(Args.data(), Args.size());
10923  }
10924
10925  return true;
10926}
10927
10928void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10929  MarkReferencedDecls Marker(*this, Loc);
10930  Marker.TraverseType(Context.getCanonicalType(T));
10931}
10932
10933namespace {
10934  /// \brief Helper class that marks all of the declarations referenced by
10935  /// potentially-evaluated subexpressions as "referenced".
10936  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10937    Sema &S;
10938    bool SkipLocalVariables;
10939
10940  public:
10941    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10942
10943    EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10944      : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
10945
10946    void VisitDeclRefExpr(DeclRefExpr *E) {
10947      // If we were asked not to visit local variables, don't.
10948      if (SkipLocalVariables) {
10949        if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10950          if (VD->hasLocalStorage())
10951            return;
10952      }
10953
10954      S.MarkDeclRefReferenced(E);
10955    }
10956
10957    void VisitMemberExpr(MemberExpr *E) {
10958      S.MarkMemberReferenced(E);
10959      Inherited::VisitMemberExpr(E);
10960    }
10961
10962    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10963      S.MarkFunctionReferenced(E->getLocStart(),
10964            const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10965      Visit(E->getSubExpr());
10966    }
10967
10968    void VisitCXXNewExpr(CXXNewExpr *E) {
10969      if (E->getOperatorNew())
10970        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
10971      if (E->getOperatorDelete())
10972        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
10973      Inherited::VisitCXXNewExpr(E);
10974    }
10975
10976    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10977      if (E->getOperatorDelete())
10978        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
10979      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10980      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10981        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10982        S.MarkFunctionReferenced(E->getLocStart(),
10983                                    S.LookupDestructor(Record));
10984      }
10985
10986      Inherited::VisitCXXDeleteExpr(E);
10987    }
10988
10989    void VisitCXXConstructExpr(CXXConstructExpr *E) {
10990      S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
10991      Inherited::VisitCXXConstructExpr(E);
10992    }
10993
10994    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10995      Visit(E->getExpr());
10996    }
10997
10998    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10999      Inherited::VisitImplicitCastExpr(E);
11000
11001      if (E->getCastKind() == CK_LValueToRValue)
11002        S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11003    }
11004  };
11005}
11006
11007/// \brief Mark any declarations that appear within this expression or any
11008/// potentially-evaluated subexpressions as "referenced".
11009///
11010/// \param SkipLocalVariables If true, don't mark local variables as
11011/// 'referenced'.
11012void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11013                                            bool SkipLocalVariables) {
11014  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11015}
11016
11017/// \brief Emit a diagnostic that describes an effect on the run-time behavior
11018/// of the program being compiled.
11019///
11020/// This routine emits the given diagnostic when the code currently being
11021/// type-checked is "potentially evaluated", meaning that there is a
11022/// possibility that the code will actually be executable. Code in sizeof()
11023/// expressions, code used only during overload resolution, etc., are not
11024/// potentially evaluated. This routine will suppress such diagnostics or,
11025/// in the absolutely nutty case of potentially potentially evaluated
11026/// expressions (C++ typeid), queue the diagnostic to potentially emit it
11027/// later.
11028///
11029/// This routine should be used for all diagnostics that describe the run-time
11030/// behavior of a program, such as passing a non-POD value through an ellipsis.
11031/// Failure to do so will likely result in spurious diagnostics or failures
11032/// during overload resolution or within sizeof/alignof/typeof/typeid.
11033bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11034                               const PartialDiagnostic &PD) {
11035  switch (ExprEvalContexts.back().Context) {
11036  case Unevaluated:
11037    // The argument will never be evaluated, so don't complain.
11038    break;
11039
11040  case ConstantEvaluated:
11041    // Relevant diagnostics should be produced by constant evaluation.
11042    break;
11043
11044  case PotentiallyEvaluated:
11045  case PotentiallyEvaluatedIfUsed:
11046    if (Statement && getCurFunctionOrMethodDecl()) {
11047      FunctionScopes.back()->PossiblyUnreachableDiags.
11048        push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11049    }
11050    else
11051      Diag(Loc, PD);
11052
11053    return true;
11054  }
11055
11056  return false;
11057}
11058
11059bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11060                               CallExpr *CE, FunctionDecl *FD) {
11061  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11062    return false;
11063
11064  // If we're inside a decltype's expression, don't check for a valid return
11065  // type or construct temporaries until we know whether this is the last call.
11066  if (ExprEvalContexts.back().IsDecltype) {
11067    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11068    return false;
11069  }
11070
11071  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11072    FunctionDecl *FD;
11073    CallExpr *CE;
11074
11075  public:
11076    CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11077      : FD(FD), CE(CE) { }
11078
11079    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11080      if (!FD) {
11081        S.Diag(Loc, diag::err_call_incomplete_return)
11082          << T << CE->getSourceRange();
11083        return;
11084      }
11085
11086      S.Diag(Loc, diag::err_call_function_incomplete_return)
11087        << CE->getSourceRange() << FD->getDeclName() << T;
11088      S.Diag(FD->getLocation(),
11089             diag::note_function_with_incomplete_return_type_declared_here)
11090        << FD->getDeclName();
11091    }
11092  } Diagnoser(FD, CE);
11093
11094  if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11095    return true;
11096
11097  return false;
11098}
11099
11100// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11101// will prevent this condition from triggering, which is what we want.
11102void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11103  SourceLocation Loc;
11104
11105  unsigned diagnostic = diag::warn_condition_is_assignment;
11106  bool IsOrAssign = false;
11107
11108  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11109    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11110      return;
11111
11112    IsOrAssign = Op->getOpcode() == BO_OrAssign;
11113
11114    // Greylist some idioms by putting them into a warning subcategory.
11115    if (ObjCMessageExpr *ME
11116          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11117      Selector Sel = ME->getSelector();
11118
11119      // self = [<foo> init...]
11120      if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11121        diagnostic = diag::warn_condition_is_idiomatic_assignment;
11122
11123      // <foo> = [<bar> nextObject]
11124      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11125        diagnostic = diag::warn_condition_is_idiomatic_assignment;
11126    }
11127
11128    Loc = Op->getOperatorLoc();
11129  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11130    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11131      return;
11132
11133    IsOrAssign = Op->getOperator() == OO_PipeEqual;
11134    Loc = Op->getOperatorLoc();
11135  } else {
11136    // Not an assignment.
11137    return;
11138  }
11139
11140  Diag(Loc, diagnostic) << E->getSourceRange();
11141
11142  SourceLocation Open = E->getLocStart();
11143  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11144  Diag(Loc, diag::note_condition_assign_silence)
11145        << FixItHint::CreateInsertion(Open, "(")
11146        << FixItHint::CreateInsertion(Close, ")");
11147
11148  if (IsOrAssign)
11149    Diag(Loc, diag::note_condition_or_assign_to_comparison)
11150      << FixItHint::CreateReplacement(Loc, "!=");
11151  else
11152    Diag(Loc, diag::note_condition_assign_to_comparison)
11153      << FixItHint::CreateReplacement(Loc, "==");
11154}
11155
11156/// \brief Redundant parentheses over an equality comparison can indicate
11157/// that the user intended an assignment used as condition.
11158void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11159  // Don't warn if the parens came from a macro.
11160  SourceLocation parenLoc = ParenE->getLocStart();
11161  if (parenLoc.isInvalid() || parenLoc.isMacroID())
11162    return;
11163  // Don't warn for dependent expressions.
11164  if (ParenE->isTypeDependent())
11165    return;
11166
11167  Expr *E = ParenE->IgnoreParens();
11168
11169  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11170    if (opE->getOpcode() == BO_EQ &&
11171        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11172                                                           == Expr::MLV_Valid) {
11173      SourceLocation Loc = opE->getOperatorLoc();
11174
11175      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11176      SourceRange ParenERange = ParenE->getSourceRange();
11177      Diag(Loc, diag::note_equality_comparison_silence)
11178        << FixItHint::CreateRemoval(ParenERange.getBegin())
11179        << FixItHint::CreateRemoval(ParenERange.getEnd());
11180      Diag(Loc, diag::note_equality_comparison_to_assign)
11181        << FixItHint::CreateReplacement(Loc, "=");
11182    }
11183}
11184
11185ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11186  DiagnoseAssignmentAsCondition(E);
11187  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11188    DiagnoseEqualityWithExtraParens(parenE);
11189
11190  ExprResult result = CheckPlaceholderExpr(E);
11191  if (result.isInvalid()) return ExprError();
11192  E = result.take();
11193
11194  if (!E->isTypeDependent()) {
11195    if (getLangOpts().CPlusPlus)
11196      return CheckCXXBooleanCondition(E); // C++ 6.4p4
11197
11198    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11199    if (ERes.isInvalid())
11200      return ExprError();
11201    E = ERes.take();
11202
11203    QualType T = E->getType();
11204    if (!T->isScalarType()) { // C99 6.8.4.1p1
11205      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11206        << T << E->getSourceRange();
11207      return ExprError();
11208    }
11209  }
11210
11211  return Owned(E);
11212}
11213
11214ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11215                                       Expr *SubExpr) {
11216  if (!SubExpr)
11217    return ExprError();
11218
11219  return CheckBooleanCondition(SubExpr, Loc);
11220}
11221
11222namespace {
11223  /// A visitor for rebuilding a call to an __unknown_any expression
11224  /// to have an appropriate type.
11225  struct RebuildUnknownAnyFunction
11226    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11227
11228    Sema &S;
11229
11230    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11231
11232    ExprResult VisitStmt(Stmt *S) {
11233      llvm_unreachable("unexpected statement!");
11234    }
11235
11236    ExprResult VisitExpr(Expr *E) {
11237      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11238        << E->getSourceRange();
11239      return ExprError();
11240    }
11241
11242    /// Rebuild an expression which simply semantically wraps another
11243    /// expression which it shares the type and value kind of.
11244    template <class T> ExprResult rebuildSugarExpr(T *E) {
11245      ExprResult SubResult = Visit(E->getSubExpr());
11246      if (SubResult.isInvalid()) return ExprError();
11247
11248      Expr *SubExpr = SubResult.take();
11249      E->setSubExpr(SubExpr);
11250      E->setType(SubExpr->getType());
11251      E->setValueKind(SubExpr->getValueKind());
11252      assert(E->getObjectKind() == OK_Ordinary);
11253      return E;
11254    }
11255
11256    ExprResult VisitParenExpr(ParenExpr *E) {
11257      return rebuildSugarExpr(E);
11258    }
11259
11260    ExprResult VisitUnaryExtension(UnaryOperator *E) {
11261      return rebuildSugarExpr(E);
11262    }
11263
11264    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11265      ExprResult SubResult = Visit(E->getSubExpr());
11266      if (SubResult.isInvalid()) return ExprError();
11267
11268      Expr *SubExpr = SubResult.take();
11269      E->setSubExpr(SubExpr);
11270      E->setType(S.Context.getPointerType(SubExpr->getType()));
11271      assert(E->getValueKind() == VK_RValue);
11272      assert(E->getObjectKind() == OK_Ordinary);
11273      return E;
11274    }
11275
11276    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11277      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11278
11279      E->setType(VD->getType());
11280
11281      assert(E->getValueKind() == VK_RValue);
11282      if (S.getLangOpts().CPlusPlus &&
11283          !(isa<CXXMethodDecl>(VD) &&
11284            cast<CXXMethodDecl>(VD)->isInstance()))
11285        E->setValueKind(VK_LValue);
11286
11287      return E;
11288    }
11289
11290    ExprResult VisitMemberExpr(MemberExpr *E) {
11291      return resolveDecl(E, E->getMemberDecl());
11292    }
11293
11294    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11295      return resolveDecl(E, E->getDecl());
11296    }
11297  };
11298}
11299
11300/// Given a function expression of unknown-any type, try to rebuild it
11301/// to have a function type.
11302static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11303  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11304  if (Result.isInvalid()) return ExprError();
11305  return S.DefaultFunctionArrayConversion(Result.take());
11306}
11307
11308namespace {
11309  /// A visitor for rebuilding an expression of type __unknown_anytype
11310  /// into one which resolves the type directly on the referring
11311  /// expression.  Strict preservation of the original source
11312  /// structure is not a goal.
11313  struct RebuildUnknownAnyExpr
11314    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11315
11316    Sema &S;
11317
11318    /// The current destination type.
11319    QualType DestType;
11320
11321    RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11322      : S(S), DestType(CastType) {}
11323
11324    ExprResult VisitStmt(Stmt *S) {
11325      llvm_unreachable("unexpected statement!");
11326    }
11327
11328    ExprResult VisitExpr(Expr *E) {
11329      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11330        << E->getSourceRange();
11331      return ExprError();
11332    }
11333
11334    ExprResult VisitCallExpr(CallExpr *E);
11335    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11336
11337    /// Rebuild an expression which simply semantically wraps another
11338    /// expression which it shares the type and value kind of.
11339    template <class T> ExprResult rebuildSugarExpr(T *E) {
11340      ExprResult SubResult = Visit(E->getSubExpr());
11341      if (SubResult.isInvalid()) return ExprError();
11342      Expr *SubExpr = SubResult.take();
11343      E->setSubExpr(SubExpr);
11344      E->setType(SubExpr->getType());
11345      E->setValueKind(SubExpr->getValueKind());
11346      assert(E->getObjectKind() == OK_Ordinary);
11347      return E;
11348    }
11349
11350    ExprResult VisitParenExpr(ParenExpr *E) {
11351      return rebuildSugarExpr(E);
11352    }
11353
11354    ExprResult VisitUnaryExtension(UnaryOperator *E) {
11355      return rebuildSugarExpr(E);
11356    }
11357
11358    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11359      const PointerType *Ptr = DestType->getAs<PointerType>();
11360      if (!Ptr) {
11361        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11362          << E->getSourceRange();
11363        return ExprError();
11364      }
11365      assert(E->getValueKind() == VK_RValue);
11366      assert(E->getObjectKind() == OK_Ordinary);
11367      E->setType(DestType);
11368
11369      // Build the sub-expression as if it were an object of the pointee type.
11370      DestType = Ptr->getPointeeType();
11371      ExprResult SubResult = Visit(E->getSubExpr());
11372      if (SubResult.isInvalid()) return ExprError();
11373      E->setSubExpr(SubResult.take());
11374      return E;
11375    }
11376
11377    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11378
11379    ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11380
11381    ExprResult VisitMemberExpr(MemberExpr *E) {
11382      return resolveDecl(E, E->getMemberDecl());
11383    }
11384
11385    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11386      return resolveDecl(E, E->getDecl());
11387    }
11388  };
11389}
11390
11391/// Rebuilds a call expression which yielded __unknown_anytype.
11392ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11393  Expr *CalleeExpr = E->getCallee();
11394
11395  enum FnKind {
11396    FK_MemberFunction,
11397    FK_FunctionPointer,
11398    FK_BlockPointer
11399  };
11400
11401  FnKind Kind;
11402  QualType CalleeType = CalleeExpr->getType();
11403  if (CalleeType == S.Context.BoundMemberTy) {
11404    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11405    Kind = FK_MemberFunction;
11406    CalleeType = Expr::findBoundMemberType(CalleeExpr);
11407  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11408    CalleeType = Ptr->getPointeeType();
11409    Kind = FK_FunctionPointer;
11410  } else {
11411    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11412    Kind = FK_BlockPointer;
11413  }
11414  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11415
11416  // Verify that this is a legal result type of a function.
11417  if (DestType->isArrayType() || DestType->isFunctionType()) {
11418    unsigned diagID = diag::err_func_returning_array_function;
11419    if (Kind == FK_BlockPointer)
11420      diagID = diag::err_block_returning_array_function;
11421
11422    S.Diag(E->getExprLoc(), diagID)
11423      << DestType->isFunctionType() << DestType;
11424    return ExprError();
11425  }
11426
11427  // Otherwise, go ahead and set DestType as the call's result.
11428  E->setType(DestType.getNonLValueExprType(S.Context));
11429  E->setValueKind(Expr::getValueKindForType(DestType));
11430  assert(E->getObjectKind() == OK_Ordinary);
11431
11432  // Rebuild the function type, replacing the result type with DestType.
11433  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11434    DestType = S.Context.getFunctionType(DestType,
11435                                         Proto->arg_type_begin(),
11436                                         Proto->getNumArgs(),
11437                                         Proto->getExtProtoInfo());
11438  else
11439    DestType = S.Context.getFunctionNoProtoType(DestType,
11440                                                FnType->getExtInfo());
11441
11442  // Rebuild the appropriate pointer-to-function type.
11443  switch (Kind) {
11444  case FK_MemberFunction:
11445    // Nothing to do.
11446    break;
11447
11448  case FK_FunctionPointer:
11449    DestType = S.Context.getPointerType(DestType);
11450    break;
11451
11452  case FK_BlockPointer:
11453    DestType = S.Context.getBlockPointerType(DestType);
11454    break;
11455  }
11456
11457  // Finally, we can recurse.
11458  ExprResult CalleeResult = Visit(CalleeExpr);
11459  if (!CalleeResult.isUsable()) return ExprError();
11460  E->setCallee(CalleeResult.take());
11461
11462  // Bind a temporary if necessary.
11463  return S.MaybeBindToTemporary(E);
11464}
11465
11466ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11467  // Verify that this is a legal result type of a call.
11468  if (DestType->isArrayType() || DestType->isFunctionType()) {
11469    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11470      << DestType->isFunctionType() << DestType;
11471    return ExprError();
11472  }
11473
11474  // Rewrite the method result type if available.
11475  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11476    assert(Method->getResultType() == S.Context.UnknownAnyTy);
11477    Method->setResultType(DestType);
11478  }
11479
11480  // Change the type of the message.
11481  E->setType(DestType.getNonReferenceType());
11482  E->setValueKind(Expr::getValueKindForType(DestType));
11483
11484  return S.MaybeBindToTemporary(E);
11485}
11486
11487ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11488  // The only case we should ever see here is a function-to-pointer decay.
11489  if (E->getCastKind() == CK_FunctionToPointerDecay) {
11490    assert(E->getValueKind() == VK_RValue);
11491    assert(E->getObjectKind() == OK_Ordinary);
11492
11493    E->setType(DestType);
11494
11495    // Rebuild the sub-expression as the pointee (function) type.
11496    DestType = DestType->castAs<PointerType>()->getPointeeType();
11497
11498    ExprResult Result = Visit(E->getSubExpr());
11499    if (!Result.isUsable()) return ExprError();
11500
11501    E->setSubExpr(Result.take());
11502    return S.Owned(E);
11503  } else if (E->getCastKind() == CK_LValueToRValue) {
11504    assert(E->getValueKind() == VK_RValue);
11505    assert(E->getObjectKind() == OK_Ordinary);
11506
11507    assert(isa<BlockPointerType>(E->getType()));
11508
11509    E->setType(DestType);
11510
11511    // The sub-expression has to be a lvalue reference, so rebuild it as such.
11512    DestType = S.Context.getLValueReferenceType(DestType);
11513
11514    ExprResult Result = Visit(E->getSubExpr());
11515    if (!Result.isUsable()) return ExprError();
11516
11517    E->setSubExpr(Result.take());
11518    return S.Owned(E);
11519  } else {
11520    llvm_unreachable("Unhandled cast type!");
11521  }
11522}
11523
11524ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11525  ExprValueKind ValueKind = VK_LValue;
11526  QualType Type = DestType;
11527
11528  // We know how to make this work for certain kinds of decls:
11529
11530  //  - functions
11531  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11532    if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11533      DestType = Ptr->getPointeeType();
11534      ExprResult Result = resolveDecl(E, VD);
11535      if (Result.isInvalid()) return ExprError();
11536      return S.ImpCastExprToType(Result.take(), Type,
11537                                 CK_FunctionToPointerDecay, VK_RValue);
11538    }
11539
11540    if (!Type->isFunctionType()) {
11541      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11542        << VD << E->getSourceRange();
11543      return ExprError();
11544    }
11545
11546    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11547      if (MD->isInstance()) {
11548        ValueKind = VK_RValue;
11549        Type = S.Context.BoundMemberTy;
11550      }
11551
11552    // Function references aren't l-values in C.
11553    if (!S.getLangOpts().CPlusPlus)
11554      ValueKind = VK_RValue;
11555
11556  //  - variables
11557  } else if (isa<VarDecl>(VD)) {
11558    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11559      Type = RefTy->getPointeeType();
11560    } else if (Type->isFunctionType()) {
11561      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11562        << VD << E->getSourceRange();
11563      return ExprError();
11564    }
11565
11566  //  - nothing else
11567  } else {
11568    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11569      << VD << E->getSourceRange();
11570    return ExprError();
11571  }
11572
11573  VD->setType(DestType);
11574  E->setType(Type);
11575  E->setValueKind(ValueKind);
11576  return S.Owned(E);
11577}
11578
11579/// Check a cast of an unknown-any type.  We intentionally only
11580/// trigger this for C-style casts.
11581ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11582                                     Expr *CastExpr, CastKind &CastKind,
11583                                     ExprValueKind &VK, CXXCastPath &Path) {
11584  // Rewrite the casted expression from scratch.
11585  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11586  if (!result.isUsable()) return ExprError();
11587
11588  CastExpr = result.take();
11589  VK = CastExpr->getValueKind();
11590  CastKind = CK_NoOp;
11591
11592  return CastExpr;
11593}
11594
11595ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11596  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11597}
11598
11599static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11600  Expr *orig = E;
11601  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11602  while (true) {
11603    E = E->IgnoreParenImpCasts();
11604    if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11605      E = call->getCallee();
11606      diagID = diag::err_uncasted_call_of_unknown_any;
11607    } else {
11608      break;
11609    }
11610  }
11611
11612  SourceLocation loc;
11613  NamedDecl *d;
11614  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11615    loc = ref->getLocation();
11616    d = ref->getDecl();
11617  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11618    loc = mem->getMemberLoc();
11619    d = mem->getMemberDecl();
11620  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11621    diagID = diag::err_uncasted_call_of_unknown_any;
11622    loc = msg->getSelectorStartLoc();
11623    d = msg->getMethodDecl();
11624    if (!d) {
11625      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11626        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11627        << orig->getSourceRange();
11628      return ExprError();
11629    }
11630  } else {
11631    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11632      << E->getSourceRange();
11633    return ExprError();
11634  }
11635
11636  S.Diag(loc, diagID) << d << orig->getSourceRange();
11637
11638  // Never recoverable.
11639  return ExprError();
11640}
11641
11642/// Check for operands with placeholder types and complain if found.
11643/// Returns true if there was an error and no recovery was possible.
11644ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11645  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11646  if (!placeholderType) return Owned(E);
11647
11648  switch (placeholderType->getKind()) {
11649
11650  // Overloaded expressions.
11651  case BuiltinType::Overload: {
11652    // Try to resolve a single function template specialization.
11653    // This is obligatory.
11654    ExprResult result = Owned(E);
11655    if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11656      return result;
11657
11658    // If that failed, try to recover with a call.
11659    } else {
11660      tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11661                           /*complain*/ true);
11662      return result;
11663    }
11664  }
11665
11666  // Bound member functions.
11667  case BuiltinType::BoundMember: {
11668    ExprResult result = Owned(E);
11669    tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11670                         /*complain*/ true);
11671    return result;
11672  }
11673
11674  // ARC unbridged casts.
11675  case BuiltinType::ARCUnbridgedCast: {
11676    Expr *realCast = stripARCUnbridgedCast(E);
11677    diagnoseARCUnbridgedCast(realCast);
11678    return Owned(realCast);
11679  }
11680
11681  // Expressions of unknown type.
11682  case BuiltinType::UnknownAny:
11683    return diagnoseUnknownAnyExpr(*this, E);
11684
11685  // Pseudo-objects.
11686  case BuiltinType::PseudoObject:
11687    return checkPseudoObjectRValue(E);
11688
11689  // Everything else should be impossible.
11690#define BUILTIN_TYPE(Id, SingletonId) \
11691  case BuiltinType::Id:
11692#define PLACEHOLDER_TYPE(Id, SingletonId)
11693#include "clang/AST/BuiltinTypes.def"
11694    break;
11695  }
11696
11697  llvm_unreachable("invalid placeholder type!");
11698}
11699
11700bool Sema::CheckCaseExpression(Expr *E) {
11701  if (E->isTypeDependent())
11702    return true;
11703  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11704    return E->getType()->isIntegralOrEnumerationType();
11705  return false;
11706}
11707
11708/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11709ExprResult
11710Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11711  assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11712         "Unknown Objective-C Boolean value!");
11713  return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11714                                        Context.ObjCBuiltinBoolTy, OpLoc));
11715}
11716