clang API Documentation

SemaExpr.cpp
Go to the documentation of this file.
00001 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/Sema/DelayedDiagnostic.h"
00016 #include "clang/Sema/Initialization.h"
00017 #include "clang/Sema/Lookup.h"
00018 #include "clang/Sema/ScopeInfo.h"
00019 #include "clang/Sema/AnalysisBasedWarnings.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/ASTConsumer.h"
00022 #include "clang/AST/ASTMutationListener.h"
00023 #include "clang/AST/CXXInheritance.h"
00024 #include "clang/AST/DeclObjC.h"
00025 #include "clang/AST/DeclTemplate.h"
00026 #include "clang/AST/EvaluatedExprVisitor.h"
00027 #include "clang/AST/Expr.h"
00028 #include "clang/AST/ExprCXX.h"
00029 #include "clang/AST/ExprObjC.h"
00030 #include "clang/AST/RecursiveASTVisitor.h"
00031 #include "clang/AST/TypeLoc.h"
00032 #include "clang/Basic/PartialDiagnostic.h"
00033 #include "clang/Basic/SourceManager.h"
00034 #include "clang/Basic/TargetInfo.h"
00035 #include "clang/Lex/LiteralSupport.h"
00036 #include "clang/Lex/Preprocessor.h"
00037 #include "clang/Sema/DeclSpec.h"
00038 #include "clang/Sema/Designator.h"
00039 #include "clang/Sema/Scope.h"
00040 #include "clang/Sema/ScopeInfo.h"
00041 #include "clang/Sema/ParsedTemplate.h"
00042 #include "clang/Sema/SemaFixItUtils.h"
00043 #include "clang/Sema/Template.h"
00044 #include "TreeTransform.h"
00045 using namespace clang;
00046 using namespace sema;
00047 
00048 /// \brief Determine whether the use of this declaration is valid, without
00049 /// emitting diagnostics.
00050 bool Sema::CanUseDecl(NamedDecl *D) {
00051   // See if this is an auto-typed variable whose initializer we are parsing.
00052   if (ParsingInitForAutoVars.count(D))
00053     return false;
00054 
00055   // See if this is a deleted function.
00056   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00057     if (FD->isDeleted())
00058       return false;
00059   }
00060 
00061   // See if this function is unavailable.
00062   if (D->getAvailability() == AR_Unavailable &&
00063       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
00064     return false;
00065 
00066   return true;
00067 }
00068 
00069 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
00070                               NamedDecl *D, SourceLocation Loc,
00071                               const ObjCInterfaceDecl *UnknownObjCClass) {
00072   // See if this declaration is unavailable or deprecated.
00073   std::string Message;
00074   AvailabilityResult Result = D->getAvailability(&Message);
00075   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
00076     if (Result == AR_Available) {
00077       const DeclContext *DC = ECD->getDeclContext();
00078       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
00079         Result = TheEnumDecl->getAvailability(&Message);
00080     }
00081   
00082   switch (Result) {
00083     case AR_Available:
00084     case AR_NotYetIntroduced:
00085       break;
00086             
00087     case AR_Deprecated:
00088       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
00089       break;
00090             
00091     case AR_Unavailable:
00092       if (S.getCurContextAvailability() != AR_Unavailable) {
00093         if (Message.empty()) {
00094           if (!UnknownObjCClass)
00095             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
00096           else
00097             S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 
00098               << D->getDeclName();
00099         }
00100         else 
00101           S.Diag(Loc, diag::err_unavailable_message) 
00102             << D->getDeclName() << Message;
00103           S.Diag(D->getLocation(), diag::note_unavailable_here) 
00104           << isa<FunctionDecl>(D) << false;
00105       }
00106       break;
00107     }
00108     return Result;
00109 }
00110 
00111 /// \brief Emit a note explaining that this function is deleted or unavailable.
00112 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
00113   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
00114 
00115   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
00116     // If the method was explicitly defaulted, point at that declaration.
00117     if (!Method->isImplicit())
00118       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
00119 
00120     // Try to diagnose why this special member function was implicitly
00121     // deleted. This might fail, if that reason no longer applies.
00122     CXXSpecialMember CSM = getSpecialMember(Method);
00123     if (CSM != CXXInvalid)
00124       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
00125 
00126     return;
00127   }
00128 
00129   Diag(Decl->getLocation(), diag::note_unavailable_here)
00130     << 1 << Decl->isDeleted();
00131 }
00132 
00133 /// \brief Determine whether the use of this declaration is valid, and
00134 /// emit any corresponding diagnostics.
00135 ///
00136 /// This routine diagnoses various problems with referencing
00137 /// declarations that can occur when using a declaration. For example,
00138 /// it might warn if a deprecated or unavailable declaration is being
00139 /// used, or produce an error (and return true) if a C++0x deleted
00140 /// function is being used.
00141 ///
00142 /// \returns true if there was an error (this declaration cannot be
00143 /// referenced), false otherwise.
00144 ///
00145 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
00146                              const ObjCInterfaceDecl *UnknownObjCClass) {
00147   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
00148     // If there were any diagnostics suppressed by template argument deduction,
00149     // emit them now.
00150     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
00151       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
00152     if (Pos != SuppressedDiagnostics.end()) {
00153       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
00154       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
00155         Diag(Suppressed[I].first, Suppressed[I].second);
00156       
00157       // Clear out the list of suppressed diagnostics, so that we don't emit
00158       // them again for this specialization. However, we don't obsolete this
00159       // entry from the table, because we want to avoid ever emitting these
00160       // diagnostics again.
00161       Suppressed.clear();
00162     }
00163   }
00164 
00165   // See if this is an auto-typed variable whose initializer we are parsing.
00166   if (ParsingInitForAutoVars.count(D)) {
00167     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
00168       << D->getDeclName();
00169     return true;
00170   }
00171 
00172   // See if this is a deleted function.
00173   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00174     if (FD->isDeleted()) {
00175       Diag(Loc, diag::err_deleted_function_use);
00176       NoteDeletedFunction(FD);
00177       return true;
00178     }
00179   }
00180   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
00181 
00182   // Warn if this is used but marked unused.
00183   if (D->hasAttr<UnusedAttr>())
00184     Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
00185   return false;
00186 }
00187 
00188 /// \brief Retrieve the message suffix that should be added to a
00189 /// diagnostic complaining about the given function being deleted or
00190 /// unavailable.
00191 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
00192   // FIXME: C++0x implicitly-deleted special member functions could be
00193   // detected here so that we could improve diagnostics to say, e.g.,
00194   // "base class 'A' had a deleted copy constructor".
00195   if (FD->isDeleted())
00196     return std::string();
00197 
00198   std::string Message;
00199   if (FD->getAvailability(&Message))
00200     return ": " + Message;
00201 
00202   return std::string();
00203 }
00204 
00205 /// DiagnoseSentinelCalls - This routine checks whether a call or
00206 /// message-send is to a declaration with the sentinel attribute, and
00207 /// if so, it checks that the requirements of the sentinel are
00208 /// satisfied.
00209 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
00210                                  Expr **args, unsigned numArgs) {
00211   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
00212   if (!attr)
00213     return;
00214 
00215   // The number of formal parameters of the declaration.
00216   unsigned numFormalParams;
00217 
00218   // The kind of declaration.  This is also an index into a %select in
00219   // the diagnostic.
00220   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
00221 
00222   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00223     numFormalParams = MD->param_size();
00224     calleeType = CT_Method;
00225   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00226     numFormalParams = FD->param_size();
00227     calleeType = CT_Function;
00228   } else if (isa<VarDecl>(D)) {
00229     QualType type = cast<ValueDecl>(D)->getType();
00230     const FunctionType *fn = 0;
00231     if (const PointerType *ptr = type->getAs<PointerType>()) {
00232       fn = ptr->getPointeeType()->getAs<FunctionType>();
00233       if (!fn) return;
00234       calleeType = CT_Function;
00235     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
00236       fn = ptr->getPointeeType()->castAs<FunctionType>();
00237       calleeType = CT_Block;
00238     } else {
00239       return;
00240     }
00241 
00242     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
00243       numFormalParams = proto->getNumArgs();
00244     } else {
00245       numFormalParams = 0;
00246     }
00247   } else {
00248     return;
00249   }
00250 
00251   // "nullPos" is the number of formal parameters at the end which
00252   // effectively count as part of the variadic arguments.  This is
00253   // useful if you would prefer to not have *any* formal parameters,
00254   // but the language forces you to have at least one.
00255   unsigned nullPos = attr->getNullPos();
00256   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
00257   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
00258 
00259   // The number of arguments which should follow the sentinel.
00260   unsigned numArgsAfterSentinel = attr->getSentinel();
00261 
00262   // If there aren't enough arguments for all the formal parameters,
00263   // the sentinel, and the args after the sentinel, complain.
00264   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
00265     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00266     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
00267     return;
00268   }
00269 
00270   // Otherwise, find the sentinel expression.
00271   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
00272   if (!sentinelExpr) return;
00273   if (sentinelExpr->isValueDependent()) return;
00274   if (Context.isSentinelNullExpr(sentinelExpr)) return;
00275 
00276   // Pick a reasonable string to insert.  Optimistically use 'nil' or
00277   // 'NULL' if those are actually defined in the context.  Only use
00278   // 'nil' for ObjC methods, where it's much more likely that the
00279   // variadic arguments form a list of object pointers.
00280   SourceLocation MissingNilLoc
00281     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
00282   std::string NullValue;
00283   if (calleeType == CT_Method &&
00284       PP.getIdentifierInfo("nil")->hasMacroDefinition())
00285     NullValue = "nil";
00286   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
00287     NullValue = "NULL";
00288   else
00289     NullValue = "(void*) 0";
00290 
00291   if (MissingNilLoc.isInvalid())
00292     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
00293   else
00294     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
00295       << calleeType
00296       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
00297   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
00298 }
00299 
00300 SourceRange Sema::getExprRange(Expr *E) const {
00301   return E ? E->getSourceRange() : SourceRange();
00302 }
00303 
00304 //===----------------------------------------------------------------------===//
00305 //  Standard Promotions and Conversions
00306 //===----------------------------------------------------------------------===//
00307 
00308 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
00309 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
00310   // Handle any placeholder expressions which made it here.
00311   if (E->getType()->isPlaceholderType()) {
00312     ExprResult result = CheckPlaceholderExpr(E);
00313     if (result.isInvalid()) return ExprError();
00314     E = result.take();
00315   }
00316   
00317   QualType Ty = E->getType();
00318   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
00319 
00320   if (Ty->isFunctionType())
00321     E = ImpCastExprToType(E, Context.getPointerType(Ty),
00322                           CK_FunctionToPointerDecay).take();
00323   else if (Ty->isArrayType()) {
00324     // In C90 mode, arrays only promote to pointers if the array expression is
00325     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
00326     // type 'array of type' is converted to an expression that has type 'pointer
00327     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
00328     // that has type 'array of type' ...".  The relevant change is "an lvalue"
00329     // (C90) to "an expression" (C99).
00330     //
00331     // C++ 4.2p1:
00332     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
00333     // T" can be converted to an rvalue of type "pointer to T".
00334     //
00335     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
00336       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
00337                             CK_ArrayToPointerDecay).take();
00338   }
00339   return Owned(E);
00340 }
00341 
00342 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
00343   // Check to see if we are dereferencing a null pointer.  If so,
00344   // and if not volatile-qualified, this is undefined behavior that the
00345   // optimizer will delete, so warn about it.  People sometimes try to use this
00346   // to get a deterministic trap and are surprised by clang's behavior.  This
00347   // only handles the pattern "*null", which is a very syntactic check.
00348   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
00349     if (UO->getOpcode() == UO_Deref &&
00350         UO->getSubExpr()->IgnoreParenCasts()->
00351           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
00352         !UO->getType().isVolatileQualified()) {
00353     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
00354                           S.PDiag(diag::warn_indirection_through_null)
00355                             << UO->getSubExpr()->getSourceRange());
00356     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
00357                         S.PDiag(diag::note_indirection_through_null));
00358   }
00359 }
00360 
00361 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
00362   // Handle any placeholder expressions which made it here.
00363   if (E->getType()->isPlaceholderType()) {
00364     ExprResult result = CheckPlaceholderExpr(E);
00365     if (result.isInvalid()) return ExprError();
00366     E = result.take();
00367   }
00368   
00369   // C++ [conv.lval]p1:
00370   //   A glvalue of a non-function, non-array type T can be
00371   //   converted to a prvalue.
00372   if (!E->isGLValue()) return Owned(E);
00373 
00374   QualType T = E->getType();
00375   assert(!T.isNull() && "r-value conversion on typeless expression?");
00376 
00377   // We don't want to throw lvalue-to-rvalue casts on top of
00378   // expressions of certain types in C++.
00379   if (getLangOpts().CPlusPlus &&
00380       (E->getType() == Context.OverloadTy ||
00381        T->isDependentType() ||
00382        T->isRecordType()))
00383     return Owned(E);
00384 
00385   // The C standard is actually really unclear on this point, and
00386   // DR106 tells us what the result should be but not why.  It's
00387   // generally best to say that void types just doesn't undergo
00388   // lvalue-to-rvalue at all.  Note that expressions of unqualified
00389   // 'void' type are never l-values, but qualified void can be.
00390   if (T->isVoidType())
00391     return Owned(E);
00392 
00393   CheckForNullPointerDereference(*this, E);
00394 
00395   // C++ [conv.lval]p1:
00396   //   [...] If T is a non-class type, the type of the prvalue is the
00397   //   cv-unqualified version of T. Otherwise, the type of the
00398   //   rvalue is T.
00399   //
00400   // C99 6.3.2.1p2:
00401   //   If the lvalue has qualified type, the value has the unqualified
00402   //   version of the type of the lvalue; otherwise, the value has the
00403   //   type of the lvalue.
00404   if (T.hasQualifiers())
00405     T = T.getUnqualifiedType();
00406 
00407   UpdateMarkingForLValueToRValue(E);
00408 
00409   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
00410                                                   E, 0, VK_RValue));
00411 
00412   // C11 6.3.2.1p2:
00413   //   ... if the lvalue has atomic type, the value has the non-atomic version 
00414   //   of the type of the lvalue ...
00415   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
00416     T = Atomic->getValueType().getUnqualifiedType();
00417     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
00418                                          Res.get(), 0, VK_RValue));
00419   }
00420   
00421   return Res;
00422 }
00423 
00424 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
00425   ExprResult Res = DefaultFunctionArrayConversion(E);
00426   if (Res.isInvalid())
00427     return ExprError();
00428   Res = DefaultLvalueConversion(Res.take());
00429   if (Res.isInvalid())
00430     return ExprError();
00431   return move(Res);
00432 }
00433 
00434 
00435 /// UsualUnaryConversions - Performs various conversions that are common to most
00436 /// operators (C99 6.3). The conversions of array and function types are
00437 /// sometimes suppressed. For example, the array->pointer conversion doesn't
00438 /// apply if the array is an argument to the sizeof or address (&) operators.
00439 /// In these instances, this routine should *not* be called.
00440 ExprResult Sema::UsualUnaryConversions(Expr *E) {
00441   // First, convert to an r-value.
00442   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
00443   if (Res.isInvalid())
00444     return Owned(E);
00445   E = Res.take();
00446 
00447   QualType Ty = E->getType();
00448   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
00449 
00450   // Half FP is a bit different: it's a storage-only type, meaning that any
00451   // "use" of it should be promoted to float.
00452   if (Ty->isHalfType())
00453     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
00454 
00455   // Try to perform integral promotions if the object has a theoretically
00456   // promotable type.
00457   if (Ty->isIntegralOrUnscopedEnumerationType()) {
00458     // C99 6.3.1.1p2:
00459     //
00460     //   The following may be used in an expression wherever an int or
00461     //   unsigned int may be used:
00462     //     - an object or expression with an integer type whose integer
00463     //       conversion rank is less than or equal to the rank of int
00464     //       and unsigned int.
00465     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
00466     //
00467     //   If an int can represent all values of the original type, the
00468     //   value is converted to an int; otherwise, it is converted to an
00469     //   unsigned int. These are called the integer promotions. All
00470     //   other types are unchanged by the integer promotions.
00471 
00472     QualType PTy = Context.isPromotableBitField(E);
00473     if (!PTy.isNull()) {
00474       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
00475       return Owned(E);
00476     }
00477     if (Ty->isPromotableIntegerType()) {
00478       QualType PT = Context.getPromotedIntegerType(Ty);
00479       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
00480       return Owned(E);
00481     }
00482   }
00483   return Owned(E);
00484 }
00485 
00486 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
00487 /// do not have a prototype. Arguments that have type float are promoted to
00488 /// double. All other argument types are converted by UsualUnaryConversions().
00489 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
00490   QualType Ty = E->getType();
00491   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
00492 
00493   ExprResult Res = UsualUnaryConversions(E);
00494   if (Res.isInvalid())
00495     return Owned(E);
00496   E = Res.take();
00497 
00498   // If this is a 'float' (CVR qualified or typedef) promote to double.
00499   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
00500     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
00501 
00502   // C++ performs lvalue-to-rvalue conversion as a default argument
00503   // promotion, even on class types, but note:
00504   //   C++11 [conv.lval]p2:
00505   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
00506   //     operand or a subexpression thereof the value contained in the
00507   //     referenced object is not accessed. Otherwise, if the glvalue
00508   //     has a class type, the conversion copy-initializes a temporary
00509   //     of type T from the glvalue and the result of the conversion
00510   //     is a prvalue for the temporary.
00511   // FIXME: add some way to gate this entire thing for correctness in
00512   // potentially potentially evaluated contexts.
00513   if (getLangOpts().CPlusPlus && E->isGLValue() && 
00514       ExprEvalContexts.back().Context != Unevaluated) {
00515     ExprResult Temp = PerformCopyInitialization(
00516                        InitializedEntity::InitializeTemporary(E->getType()),
00517                                                 E->getExprLoc(),
00518                                                 Owned(E));
00519     if (Temp.isInvalid())
00520       return ExprError();
00521     E = Temp.get();
00522   }
00523 
00524   return Owned(E);
00525 }
00526 
00527 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
00528 /// will warn if the resulting type is not a POD type, and rejects ObjC
00529 /// interfaces passed by value.
00530 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
00531                                                   FunctionDecl *FDecl) {
00532   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
00533     // Strip the unbridged-cast placeholder expression off, if applicable.
00534     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
00535         (CT == VariadicMethod ||
00536          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
00537       E = stripARCUnbridgedCast(E);
00538 
00539     // Otherwise, do normal placeholder checking.
00540     } else {
00541       ExprResult ExprRes = CheckPlaceholderExpr(E);
00542       if (ExprRes.isInvalid())
00543         return ExprError();
00544       E = ExprRes.take();
00545     }
00546   }
00547   
00548   ExprResult ExprRes = DefaultArgumentPromotion(E);
00549   if (ExprRes.isInvalid())
00550     return ExprError();
00551   E = ExprRes.take();
00552 
00553   // Don't allow one to pass an Objective-C interface to a vararg.
00554   if (E->getType()->isObjCObjectType() &&
00555     DiagRuntimeBehavior(E->getLocStart(), 0,
00556                         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
00557                           << E->getType() << CT))
00558     return ExprError();
00559 
00560   // Complain about passing non-POD types through varargs. However, don't
00561   // perform this check for incomplete types, which we can get here when we're
00562   // in an unevaluated context.
00563   if (!E->getType()->isIncompleteType() &&
00564       !E->getType().isCXX98PODType(Context)) {
00565     // C++0x [expr.call]p7:
00566     //   Passing a potentially-evaluated argument of class type (Clause 9) 
00567     //   having a non-trivial copy constructor, a non-trivial move constructor,
00568     //   or a non-trivial destructor, with no corresponding parameter, 
00569     //   is conditionally-supported with implementation-defined semantics.
00570     bool TrivialEnough = false;
00571     if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType())  {
00572       if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
00573         if (Record->hasTrivialCopyConstructor() &&
00574             Record->hasTrivialMoveConstructor() &&
00575             Record->hasTrivialDestructor()) {
00576           DiagRuntimeBehavior(E->getLocStart(), 0,
00577             PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
00578               << E->getType() << CT);
00579           TrivialEnough = true;
00580         }
00581       }
00582     }
00583 
00584     if (!TrivialEnough &&
00585         getLangOpts().ObjCAutoRefCount &&
00586         E->getType()->isObjCLifetimeType())
00587       TrivialEnough = true;
00588       
00589     if (TrivialEnough) {
00590       // Nothing to diagnose. This is okay.
00591     } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
00592                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
00593                             << getLangOpts().CPlusPlus0x << E->getType() 
00594                             << CT)) {
00595       // Turn this into a trap.
00596       CXXScopeSpec SS;
00597       SourceLocation TemplateKWLoc;
00598       UnqualifiedId Name;
00599       Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
00600                          E->getLocStart());
00601       ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
00602                                             true, false);
00603       if (TrapFn.isInvalid())
00604         return ExprError();
00605 
00606       ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
00607                                       MultiExprArg(), E->getLocEnd());
00608       if (Call.isInvalid())
00609         return ExprError();
00610       
00611       ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
00612                                     Call.get(), E);
00613       if (Comma.isInvalid())
00614         return ExprError();      
00615       E = Comma.get();
00616     }
00617   }
00618   // c++ rules are enforced elsewhere.
00619   if (!getLangOpts().CPlusPlus &&
00620       RequireCompleteType(E->getExprLoc(), E->getType(),
00621                           diag::err_call_incomplete_argument))
00622     return ExprError();
00623   
00624   return Owned(E);
00625 }
00626 
00627 /// \brief Converts an integer to complex float type.  Helper function of
00628 /// UsualArithmeticConversions()
00629 ///
00630 /// \return false if the integer expression is an integer type and is
00631 /// successfully converted to the complex type.
00632 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
00633                                                   ExprResult &ComplexExpr,
00634                                                   QualType IntTy,
00635                                                   QualType ComplexTy,
00636                                                   bool SkipCast) {
00637   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
00638   if (SkipCast) return false;
00639   if (IntTy->isIntegerType()) {
00640     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
00641     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
00642     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
00643                                   CK_FloatingRealToComplex);
00644   } else {
00645     assert(IntTy->isComplexIntegerType());
00646     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
00647                                   CK_IntegralComplexToFloatingComplex);
00648   }
00649   return false;
00650 }
00651 
00652 /// \brief Takes two complex float types and converts them to the same type.
00653 /// Helper function of UsualArithmeticConversions()
00654 static QualType
00655 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
00656                                             ExprResult &RHS, QualType LHSType,
00657                                             QualType RHSType,
00658                                             bool IsCompAssign) {
00659   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
00660 
00661   if (order < 0) {
00662     // _Complex float -> _Complex double
00663     if (!IsCompAssign)
00664       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
00665     return RHSType;
00666   }
00667   if (order > 0)
00668     // _Complex float -> _Complex double
00669     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
00670   return LHSType;
00671 }
00672 
00673 /// \brief Converts otherExpr to complex float and promotes complexExpr if
00674 /// necessary.  Helper function of UsualArithmeticConversions()
00675 static QualType handleOtherComplexFloatConversion(Sema &S,
00676                                                   ExprResult &ComplexExpr,
00677                                                   ExprResult &OtherExpr,
00678                                                   QualType ComplexTy,
00679                                                   QualType OtherTy,
00680                                                   bool ConvertComplexExpr,
00681                                                   bool ConvertOtherExpr) {
00682   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
00683 
00684   // If just the complexExpr is complex, the otherExpr needs to be converted,
00685   // and the complexExpr might need to be promoted.
00686   if (order > 0) { // complexExpr is wider
00687     // float -> _Complex double
00688     if (ConvertOtherExpr) {
00689       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
00690       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
00691       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
00692                                       CK_FloatingRealToComplex);
00693     }
00694     return ComplexTy;
00695   }
00696 
00697   // otherTy is at least as wide.  Find its corresponding complex type.
00698   QualType result = (order == 0 ? ComplexTy :
00699                                   S.Context.getComplexType(OtherTy));
00700 
00701   // double -> _Complex double
00702   if (ConvertOtherExpr)
00703     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
00704                                     CK_FloatingRealToComplex);
00705 
00706   // _Complex float -> _Complex double
00707   if (ConvertComplexExpr && order < 0)
00708     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
00709                                       CK_FloatingComplexCast);
00710 
00711   return result;
00712 }
00713 
00714 /// \brief Handle arithmetic conversion with complex types.  Helper function of
00715 /// UsualArithmeticConversions()
00716 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
00717                                              ExprResult &RHS, QualType LHSType,
00718                                              QualType RHSType,
00719                                              bool IsCompAssign) {
00720   // if we have an integer operand, the result is the complex type.
00721   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
00722                                              /*skipCast*/false))
00723     return LHSType;
00724   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
00725                                              /*skipCast*/IsCompAssign))
00726     return RHSType;
00727 
00728   // This handles complex/complex, complex/float, or float/complex.
00729   // When both operands are complex, the shorter operand is converted to the
00730   // type of the longer, and that is the type of the result. This corresponds
00731   // to what is done when combining two real floating-point operands.
00732   // The fun begins when size promotion occur across type domains.
00733   // From H&S 6.3.4: When one operand is complex and the other is a real
00734   // floating-point type, the less precise type is converted, within it's
00735   // real or complex domain, to the precision of the other type. For example,
00736   // when combining a "long double" with a "double _Complex", the
00737   // "double _Complex" is promoted to "long double _Complex".
00738 
00739   bool LHSComplexFloat = LHSType->isComplexType();
00740   bool RHSComplexFloat = RHSType->isComplexType();
00741 
00742   // If both are complex, just cast to the more precise type.
00743   if (LHSComplexFloat && RHSComplexFloat)
00744     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
00745                                                        LHSType, RHSType,
00746                                                        IsCompAssign);
00747 
00748   // If only one operand is complex, promote it if necessary and convert the
00749   // other operand to complex.
00750   if (LHSComplexFloat)
00751     return handleOtherComplexFloatConversion(
00752         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
00753         /*convertOtherExpr*/ true);
00754 
00755   assert(RHSComplexFloat);
00756   return handleOtherComplexFloatConversion(
00757       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
00758       /*convertOtherExpr*/ !IsCompAssign);
00759 }
00760 
00761 /// \brief Hande arithmetic conversion from integer to float.  Helper function
00762 /// of UsualArithmeticConversions()
00763 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
00764                                            ExprResult &IntExpr,
00765                                            QualType FloatTy, QualType IntTy,
00766                                            bool ConvertFloat, bool ConvertInt) {
00767   if (IntTy->isIntegerType()) {
00768     if (ConvertInt)
00769       // Convert intExpr to the lhs floating point type.
00770       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
00771                                     CK_IntegralToFloating);
00772     return FloatTy;
00773   }
00774      
00775   // Convert both sides to the appropriate complex float.
00776   assert(IntTy->isComplexIntegerType());
00777   QualType result = S.Context.getComplexType(FloatTy);
00778 
00779   // _Complex int -> _Complex float
00780   if (ConvertInt)
00781     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
00782                                   CK_IntegralComplexToFloatingComplex);
00783 
00784   // float -> _Complex float
00785   if (ConvertFloat)
00786     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
00787                                     CK_FloatingRealToComplex);
00788 
00789   return result;
00790 }
00791 
00792 /// \brief Handle arithmethic conversion with floating point types.  Helper
00793 /// function of UsualArithmeticConversions()
00794 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
00795                                       ExprResult &RHS, QualType LHSType,
00796                                       QualType RHSType, bool IsCompAssign) {
00797   bool LHSFloat = LHSType->isRealFloatingType();
00798   bool RHSFloat = RHSType->isRealFloatingType();
00799 
00800   // If we have two real floating types, convert the smaller operand
00801   // to the bigger result.
00802   if (LHSFloat && RHSFloat) {
00803     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
00804     if (order > 0) {
00805       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
00806       return LHSType;
00807     }
00808 
00809     assert(order < 0 && "illegal float comparison");
00810     if (!IsCompAssign)
00811       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
00812     return RHSType;
00813   }
00814 
00815   if (LHSFloat)
00816     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
00817                                       /*convertFloat=*/!IsCompAssign,
00818                                       /*convertInt=*/ true);
00819   assert(RHSFloat);
00820   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
00821                                     /*convertInt=*/ true,
00822                                     /*convertFloat=*/!IsCompAssign);
00823 }
00824 
00825 /// \brief Handle conversions with GCC complex int extension.  Helper function
00826 /// of UsualArithmeticConversions()
00827 // FIXME: if the operands are (int, _Complex long), we currently
00828 // don't promote the complex.  Also, signedness?
00829 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
00830                                            ExprResult &RHS, QualType LHSType,
00831                                            QualType RHSType,
00832                                            bool IsCompAssign) {
00833   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
00834   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
00835 
00836   if (LHSComplexInt && RHSComplexInt) {
00837     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
00838                                               RHSComplexInt->getElementType());
00839     assert(order && "inequal types with equal element ordering");
00840     if (order > 0) {
00841       // _Complex int -> _Complex long
00842       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
00843       return LHSType;
00844     }
00845 
00846     if (!IsCompAssign)
00847       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
00848     return RHSType;
00849   }
00850 
00851   if (LHSComplexInt) {
00852     // int -> _Complex int
00853     // FIXME: This needs to take integer ranks into account
00854     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
00855                               CK_IntegralCast);
00856     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
00857     return LHSType;
00858   }
00859 
00860   assert(RHSComplexInt);
00861   // int -> _Complex int
00862   // FIXME: This needs to take integer ranks into account
00863   if (!IsCompAssign) {
00864     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
00865                               CK_IntegralCast);
00866     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
00867   }
00868   return RHSType;
00869 }
00870 
00871 /// \brief Handle integer arithmetic conversions.  Helper function of
00872 /// UsualArithmeticConversions()
00873 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
00874                                         ExprResult &RHS, QualType LHSType,
00875                                         QualType RHSType, bool IsCompAssign) {
00876   // The rules for this case are in C99 6.3.1.8
00877   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
00878   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
00879   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
00880   if (LHSSigned == RHSSigned) {
00881     // Same signedness; use the higher-ranked type
00882     if (order >= 0) {
00883       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
00884       return LHSType;
00885     } else if (!IsCompAssign)
00886       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
00887     return RHSType;
00888   } else if (order != (LHSSigned ? 1 : -1)) {
00889     // The unsigned type has greater than or equal rank to the
00890     // signed type, so use the unsigned type
00891     if (RHSSigned) {
00892       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
00893       return LHSType;
00894     } else if (!IsCompAssign)
00895       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
00896     return RHSType;
00897   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
00898     // The two types are different widths; if we are here, that
00899     // means the signed type is larger than the unsigned type, so
00900     // use the signed type.
00901     if (LHSSigned) {
00902       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
00903       return LHSType;
00904     } else if (!IsCompAssign)
00905       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
00906     return RHSType;
00907   } else {
00908     // The signed type is higher-ranked than the unsigned type,
00909     // but isn't actually any bigger (like unsigned int and long
00910     // on most 32-bit systems).  Use the unsigned type corresponding
00911     // to the signed type.
00912     QualType result =
00913       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
00914     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
00915     if (!IsCompAssign)
00916       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
00917     return result;
00918   }
00919 }
00920 
00921 /// UsualArithmeticConversions - Performs various conversions that are common to
00922 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
00923 /// routine returns the first non-arithmetic type found. The client is
00924 /// responsible for emitting appropriate error diagnostics.
00925 /// FIXME: verify the conversion rules for "complex int" are consistent with
00926 /// GCC.
00927 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
00928                                           bool IsCompAssign) {
00929   if (!IsCompAssign) {
00930     LHS = UsualUnaryConversions(LHS.take());
00931     if (LHS.isInvalid())
00932       return QualType();
00933   }
00934 
00935   RHS = UsualUnaryConversions(RHS.take());
00936   if (RHS.isInvalid())
00937     return QualType();
00938 
00939   // For conversion purposes, we ignore any qualifiers.
00940   // For example, "const float" and "float" are equivalent.
00941   QualType LHSType =
00942     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
00943   QualType RHSType =
00944     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
00945 
00946   // If both types are identical, no conversion is needed.
00947   if (LHSType == RHSType)
00948     return LHSType;
00949 
00950   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
00951   // The caller can deal with this (e.g. pointer + int).
00952   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
00953     return LHSType;
00954 
00955   // Apply unary and bitfield promotions to the LHS's type.
00956   QualType LHSUnpromotedType = LHSType;
00957   if (LHSType->isPromotableIntegerType())
00958     LHSType = Context.getPromotedIntegerType(LHSType);
00959   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
00960   if (!LHSBitfieldPromoteTy.isNull())
00961     LHSType = LHSBitfieldPromoteTy;
00962   if (LHSType != LHSUnpromotedType && !IsCompAssign)
00963     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
00964 
00965   // If both types are identical, no conversion is needed.
00966   if (LHSType == RHSType)
00967     return LHSType;
00968 
00969   // At this point, we have two different arithmetic types.
00970 
00971   // Handle complex types first (C99 6.3.1.8p1).
00972   if (LHSType->isComplexType() || RHSType->isComplexType())
00973     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
00974                                         IsCompAssign);
00975 
00976   // Now handle "real" floating types (i.e. float, double, long double).
00977   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
00978     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
00979                                  IsCompAssign);
00980 
00981   // Handle GCC complex int extension.
00982   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
00983     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
00984                                       IsCompAssign);
00985 
00986   // Finally, we have two differing integer types.
00987   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
00988                                  IsCompAssign);
00989 }
00990 
00991 //===----------------------------------------------------------------------===//
00992 //  Semantic Analysis for various Expression Types
00993 //===----------------------------------------------------------------------===//
00994 
00995 
00996 ExprResult
00997 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
00998                                 SourceLocation DefaultLoc,
00999                                 SourceLocation RParenLoc,
01000                                 Expr *ControllingExpr,
01001                                 MultiTypeArg ArgTypes,
01002                                 MultiExprArg ArgExprs) {
01003   unsigned NumAssocs = ArgTypes.size();
01004   assert(NumAssocs == ArgExprs.size());
01005 
01006   ParsedType *ParsedTypes = ArgTypes.release();
01007   Expr **Exprs = ArgExprs.release();
01008 
01009   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
01010   for (unsigned i = 0; i < NumAssocs; ++i) {
01011     if (ParsedTypes[i])
01012       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
01013     else
01014       Types[i] = 0;
01015   }
01016 
01017   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
01018                                              ControllingExpr, Types, Exprs,
01019                                              NumAssocs);
01020   delete [] Types;
01021   return ER;
01022 }
01023 
01024 ExprResult
01025 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
01026                                  SourceLocation DefaultLoc,
01027                                  SourceLocation RParenLoc,
01028                                  Expr *ControllingExpr,
01029                                  TypeSourceInfo **Types,
01030                                  Expr **Exprs,
01031                                  unsigned NumAssocs) {
01032   bool TypeErrorFound = false,
01033        IsResultDependent = ControllingExpr->isTypeDependent(),
01034        ContainsUnexpandedParameterPack
01035          = ControllingExpr->containsUnexpandedParameterPack();
01036 
01037   for (unsigned i = 0; i < NumAssocs; ++i) {
01038     if (Exprs[i]->containsUnexpandedParameterPack())
01039       ContainsUnexpandedParameterPack = true;
01040 
01041     if (Types[i]) {
01042       if (Types[i]->getType()->containsUnexpandedParameterPack())
01043         ContainsUnexpandedParameterPack = true;
01044 
01045       if (Types[i]->getType()->isDependentType()) {
01046         IsResultDependent = true;
01047       } else {
01048         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
01049         // complete object type other than a variably modified type."
01050         unsigned D = 0;
01051         if (Types[i]->getType()->isIncompleteType())
01052           D = diag::err_assoc_type_incomplete;
01053         else if (!Types[i]->getType()->isObjectType())
01054           D = diag::err_assoc_type_nonobject;
01055         else if (Types[i]->getType()->isVariablyModifiedType())
01056           D = diag::err_assoc_type_variably_modified;
01057 
01058         if (D != 0) {
01059           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
01060             << Types[i]->getTypeLoc().getSourceRange()
01061             << Types[i]->getType();
01062           TypeErrorFound = true;
01063         }
01064 
01065         // C11 6.5.1.1p2 "No two generic associations in the same generic
01066         // selection shall specify compatible types."
01067         for (unsigned j = i+1; j < NumAssocs; ++j)
01068           if (Types[j] && !Types[j]->getType()->isDependentType() &&
01069               Context.typesAreCompatible(Types[i]->getType(),
01070                                          Types[j]->getType())) {
01071             Diag(Types[j]->getTypeLoc().getBeginLoc(),
01072                  diag::err_assoc_compatible_types)
01073               << Types[j]->getTypeLoc().getSourceRange()
01074               << Types[j]->getType()
01075               << Types[i]->getType();
01076             Diag(Types[i]->getTypeLoc().getBeginLoc(),
01077                  diag::note_compat_assoc)
01078               << Types[i]->getTypeLoc().getSourceRange()
01079               << Types[i]->getType();
01080             TypeErrorFound = true;
01081           }
01082       }
01083     }
01084   }
01085   if (TypeErrorFound)
01086     return ExprError();
01087 
01088   // If we determined that the generic selection is result-dependent, don't
01089   // try to compute the result expression.
01090   if (IsResultDependent)
01091     return Owned(new (Context) GenericSelectionExpr(
01092                    Context, KeyLoc, ControllingExpr,
01093                    Types, Exprs, NumAssocs, DefaultLoc,
01094                    RParenLoc, ContainsUnexpandedParameterPack));
01095 
01096   SmallVector<unsigned, 1> CompatIndices;
01097   unsigned DefaultIndex = -1U;
01098   for (unsigned i = 0; i < NumAssocs; ++i) {
01099     if (!Types[i])
01100       DefaultIndex = i;
01101     else if (Context.typesAreCompatible(ControllingExpr->getType(),
01102                                         Types[i]->getType()))
01103       CompatIndices.push_back(i);
01104   }
01105 
01106   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
01107   // type compatible with at most one of the types named in its generic
01108   // association list."
01109   if (CompatIndices.size() > 1) {
01110     // We strip parens here because the controlling expression is typically
01111     // parenthesized in macro definitions.
01112     ControllingExpr = ControllingExpr->IgnoreParens();
01113     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
01114       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
01115       << (unsigned) CompatIndices.size();
01116     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
01117          E = CompatIndices.end(); I != E; ++I) {
01118       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
01119            diag::note_compat_assoc)
01120         << Types[*I]->getTypeLoc().getSourceRange()
01121         << Types[*I]->getType();
01122     }
01123     return ExprError();
01124   }
01125 
01126   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
01127   // its controlling expression shall have type compatible with exactly one of
01128   // the types named in its generic association list."
01129   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
01130     // We strip parens here because the controlling expression is typically
01131     // parenthesized in macro definitions.
01132     ControllingExpr = ControllingExpr->IgnoreParens();
01133     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
01134       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
01135     return ExprError();
01136   }
01137 
01138   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
01139   // type name that is compatible with the type of the controlling expression,
01140   // then the result expression of the generic selection is the expression
01141   // in that generic association. Otherwise, the result expression of the
01142   // generic selection is the expression in the default generic association."
01143   unsigned ResultIndex =
01144     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
01145 
01146   return Owned(new (Context) GenericSelectionExpr(
01147                  Context, KeyLoc, ControllingExpr,
01148                  Types, Exprs, NumAssocs, DefaultLoc,
01149                  RParenLoc, ContainsUnexpandedParameterPack,
01150                  ResultIndex));
01151 }
01152 
01153 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
01154 /// location of the token and the offset of the ud-suffix within it.
01155 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
01156                                      unsigned Offset) {
01157   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
01158                                         S.getLangOpts());
01159 }
01160 
01161 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
01162 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
01163 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
01164                                                  IdentifierInfo *UDSuffix,
01165                                                  SourceLocation UDSuffixLoc,
01166                                                  ArrayRef<Expr*> Args,
01167                                                  SourceLocation LitEndLoc) {
01168   assert(Args.size() <= 2 && "too many arguments for literal operator");
01169 
01170   QualType ArgTy[2];
01171   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
01172     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
01173     if (ArgTy[ArgIdx]->isArrayType())
01174       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
01175   }
01176 
01177   DeclarationName OpName =
01178     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
01179   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
01180   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
01181 
01182   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
01183   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
01184                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
01185     return ExprError();
01186 
01187   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
01188 }
01189 
01190 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
01191 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
01192 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
01193 /// multiple tokens.  However, the common case is that StringToks points to one
01194 /// string.
01195 ///
01196 ExprResult
01197 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
01198                          Scope *UDLScope) {
01199   assert(NumStringToks && "Must have at least one string!");
01200 
01201   StringLiteralParser Literal(StringToks, NumStringToks, PP);
01202   if (Literal.hadError)
01203     return ExprError();
01204 
01205   SmallVector<SourceLocation, 4> StringTokLocs;
01206   for (unsigned i = 0; i != NumStringToks; ++i)
01207     StringTokLocs.push_back(StringToks[i].getLocation());
01208 
01209   QualType StrTy = Context.CharTy;
01210   if (Literal.isWide())
01211     StrTy = Context.getWCharType();
01212   else if (Literal.isUTF16())
01213     StrTy = Context.Char16Ty;
01214   else if (Literal.isUTF32())
01215     StrTy = Context.Char32Ty;
01216   else if (Literal.isPascal())
01217     StrTy = Context.UnsignedCharTy;
01218 
01219   StringLiteral::StringKind Kind = StringLiteral::Ascii;
01220   if (Literal.isWide())
01221     Kind = StringLiteral::Wide;
01222   else if (Literal.isUTF8())
01223     Kind = StringLiteral::UTF8;
01224   else if (Literal.isUTF16())
01225     Kind = StringLiteral::UTF16;
01226   else if (Literal.isUTF32())
01227     Kind = StringLiteral::UTF32;
01228 
01229   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
01230   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
01231     StrTy.addConst();
01232 
01233   // Get an array type for the string, according to C99 6.4.5.  This includes
01234   // the nul terminator character as well as the string length for pascal
01235   // strings.
01236   StrTy = Context.getConstantArrayType(StrTy,
01237                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
01238                                        ArrayType::Normal, 0);
01239 
01240   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
01241   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
01242                                              Kind, Literal.Pascal, StrTy,
01243                                              &StringTokLocs[0],
01244                                              StringTokLocs.size());
01245   if (Literal.getUDSuffix().empty())
01246     return Owned(Lit);
01247 
01248   // We're building a user-defined literal.
01249   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
01250   SourceLocation UDSuffixLoc =
01251     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
01252                    Literal.getUDSuffixOffset());
01253 
01254   // Make sure we're allowed user-defined literals here.
01255   if (!UDLScope)
01256     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
01257 
01258   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
01259   //   operator "" X (str, len)
01260   QualType SizeType = Context.getSizeType();
01261   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
01262   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
01263                                                   StringTokLocs[0]);
01264   Expr *Args[] = { Lit, LenArg };
01265   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
01266                                         Args, StringTokLocs.back());
01267 }
01268 
01269 ExprResult
01270 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
01271                        SourceLocation Loc,
01272                        const CXXScopeSpec *SS) {
01273   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
01274   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
01275 }
01276 
01277 /// BuildDeclRefExpr - Build an expression that references a
01278 /// declaration that does not require a closure capture.
01279 ExprResult
01280 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
01281                        const DeclarationNameInfo &NameInfo,
01282                        const CXXScopeSpec *SS) {
01283   if (getLangOpts().CUDA)
01284     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
01285       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
01286         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
01287                            CalleeTarget = IdentifyCUDATarget(Callee);
01288         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
01289           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
01290             << CalleeTarget << D->getIdentifier() << CallerTarget;
01291           Diag(D->getLocation(), diag::note_previous_decl)
01292             << D->getIdentifier();
01293           return ExprError();
01294         }
01295       }
01296 
01297   bool refersToEnclosingScope =
01298     (CurContext != D->getDeclContext() &&
01299      D->getDeclContext()->isFunctionOrMethod());
01300 
01301   DeclRefExpr *E = DeclRefExpr::Create(Context,
01302                                        SS ? SS->getWithLocInContext(Context)
01303                                               : NestedNameSpecifierLoc(),
01304                                        SourceLocation(),
01305                                        D, refersToEnclosingScope,
01306                                        NameInfo, Ty, VK);
01307 
01308   MarkDeclRefReferenced(E);
01309 
01310   // Just in case we're building an illegal pointer-to-member.
01311   FieldDecl *FD = dyn_cast<FieldDecl>(D);
01312   if (FD && FD->isBitField())
01313     E->setObjectKind(OK_BitField);
01314 
01315   return Owned(E);
01316 }
01317 
01318 /// Decomposes the given name into a DeclarationNameInfo, its location, and
01319 /// possibly a list of template arguments.
01320 ///
01321 /// If this produces template arguments, it is permitted to call
01322 /// DecomposeTemplateName.
01323 ///
01324 /// This actually loses a lot of source location information for
01325 /// non-standard name kinds; we should consider preserving that in
01326 /// some way.
01327 void
01328 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
01329                              TemplateArgumentListInfo &Buffer,
01330                              DeclarationNameInfo &NameInfo,
01331                              const TemplateArgumentListInfo *&TemplateArgs) {
01332   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
01333     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
01334     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
01335 
01336     ASTTemplateArgsPtr TemplateArgsPtr(*this,
01337                                        Id.TemplateId->getTemplateArgs(),
01338                                        Id.TemplateId->NumArgs);
01339     translateTemplateArguments(TemplateArgsPtr, Buffer);
01340     TemplateArgsPtr.release();
01341 
01342     TemplateName TName = Id.TemplateId->Template.get();
01343     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
01344     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
01345     TemplateArgs = &Buffer;
01346   } else {
01347     NameInfo = GetNameFromUnqualifiedId(Id);
01348     TemplateArgs = 0;
01349   }
01350 }
01351 
01352 /// Diagnose an empty lookup.
01353 ///
01354 /// \return false if new lookup candidates were found
01355 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
01356                                CorrectionCandidateCallback &CCC,
01357                                TemplateArgumentListInfo *ExplicitTemplateArgs,
01358                                llvm::ArrayRef<Expr *> Args) {
01359   DeclarationName Name = R.getLookupName();
01360 
01361   unsigned diagnostic = diag::err_undeclared_var_use;
01362   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
01363   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
01364       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
01365       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
01366     diagnostic = diag::err_undeclared_use;
01367     diagnostic_suggest = diag::err_undeclared_use_suggest;
01368   }
01369 
01370   // If the original lookup was an unqualified lookup, fake an
01371   // unqualified lookup.  This is useful when (for example) the
01372   // original lookup would not have found something because it was a
01373   // dependent name.
01374   DeclContext *DC = SS.isEmpty() ? CurContext : 0;
01375   while (DC) {
01376     if (isa<CXXRecordDecl>(DC)) {
01377       LookupQualifiedName(R, DC);
01378 
01379       if (!R.empty()) {
01380         // Don't give errors about ambiguities in this lookup.
01381         R.suppressDiagnostics();
01382 
01383         // During a default argument instantiation the CurContext points
01384         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
01385         // function parameter list, hence add an explicit check.
01386         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
01387                               ActiveTemplateInstantiations.back().Kind ==
01388             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
01389         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
01390         bool isInstance = CurMethod &&
01391                           CurMethod->isInstance() &&
01392                           DC == CurMethod->getParent() && !isDefaultArgument;
01393                           
01394 
01395         // Give a code modification hint to insert 'this->'.
01396         // TODO: fixit for inserting 'Base<T>::' in the other cases.
01397         // Actually quite difficult!
01398         if (isInstance) {
01399           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
01400               CallsUndergoingInstantiation.back()->getCallee());
01401           CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
01402               CurMethod->getInstantiatedFromMemberFunction());
01403           if (DepMethod) {
01404             if (getLangOpts().MicrosoftMode)
01405               diagnostic = diag::warn_found_via_dependent_bases_lookup;
01406             Diag(R.getNameLoc(), diagnostic) << Name
01407               << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
01408             QualType DepThisType = DepMethod->getThisType(Context);
01409             CheckCXXThisCapture(R.getNameLoc());
01410             CXXThisExpr *DepThis = new (Context) CXXThisExpr(
01411                                        R.getNameLoc(), DepThisType, false);
01412             TemplateArgumentListInfo TList;
01413             if (ULE->hasExplicitTemplateArgs())
01414               ULE->copyTemplateArgumentsInto(TList);
01415             
01416             CXXScopeSpec SS;
01417             SS.Adopt(ULE->getQualifierLoc());
01418             CXXDependentScopeMemberExpr *DepExpr =
01419                 CXXDependentScopeMemberExpr::Create(
01420                     Context, DepThis, DepThisType, true, SourceLocation(),
01421                     SS.getWithLocInContext(Context),
01422                     ULE->getTemplateKeywordLoc(), 0,
01423                     R.getLookupNameInfo(),
01424                     ULE->hasExplicitTemplateArgs() ? &TList : 0);
01425             CallsUndergoingInstantiation.back()->setCallee(DepExpr);
01426           } else {
01427             // FIXME: we should be able to handle this case too. It is correct
01428             // to add this-> here. This is a workaround for PR7947.
01429             Diag(R.getNameLoc(), diagnostic) << Name;
01430           }
01431         } else {
01432           if (getLangOpts().MicrosoftMode)
01433             diagnostic = diag::warn_found_via_dependent_bases_lookup;
01434           Diag(R.getNameLoc(), diagnostic) << Name;
01435         }
01436 
01437         // Do we really want to note all of these?
01438         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
01439           Diag((*I)->getLocation(), diag::note_dependent_var_use);
01440 
01441         // Return true if we are inside a default argument instantiation
01442         // and the found name refers to an instance member function, otherwise
01443         // the function calling DiagnoseEmptyLookup will try to create an
01444         // implicit member call and this is wrong for default argument.
01445         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
01446           Diag(R.getNameLoc(), diag::err_member_call_without_object);
01447           return true;
01448         }
01449 
01450         // Tell the callee to try to recover.
01451         return false;
01452       }
01453 
01454       R.clear();
01455     }
01456 
01457     // In Microsoft mode, if we are performing lookup from within a friend
01458     // function definition declared at class scope then we must set
01459     // DC to the lexical parent to be able to search into the parent
01460     // class.
01461     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
01462         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
01463         DC->getLexicalParent()->isRecord())
01464       DC = DC->getLexicalParent();
01465     else
01466       DC = DC->getParent();
01467   }
01468 
01469   // We didn't find anything, so try to correct for a typo.
01470   TypoCorrection Corrected;
01471   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
01472                                     S, &SS, CCC))) {
01473     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
01474     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
01475     R.setLookupName(Corrected.getCorrection());
01476 
01477     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
01478       if (Corrected.isOverloaded()) {
01479         OverloadCandidateSet OCS(R.getNameLoc());
01480         OverloadCandidateSet::iterator Best;
01481         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
01482                                         CDEnd = Corrected.end();
01483              CD != CDEnd; ++CD) {
01484           if (FunctionTemplateDecl *FTD =
01485                    dyn_cast<FunctionTemplateDecl>(*CD))
01486             AddTemplateOverloadCandidate(
01487                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
01488                 Args, OCS);
01489           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
01490             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
01491               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
01492                                    Args, OCS);
01493         }
01494         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
01495           case OR_Success:
01496             ND = Best->Function;
01497             break;
01498           default:
01499             break;
01500         }
01501       }
01502       R.addDecl(ND);
01503       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
01504         if (SS.isEmpty())
01505           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
01506             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
01507         else
01508           Diag(R.getNameLoc(), diag::err_no_member_suggest)
01509             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
01510             << SS.getRange()
01511             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
01512         if (ND)
01513           Diag(ND->getLocation(), diag::note_previous_decl)
01514             << CorrectedQuotedStr;
01515 
01516         // Tell the callee to try to recover.
01517         return false;
01518       }
01519 
01520       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
01521         // FIXME: If we ended up with a typo for a type name or
01522         // Objective-C class name, we're in trouble because the parser
01523         // is in the wrong place to recover. Suggest the typo
01524         // correction, but don't make it a fix-it since we're not going
01525         // to recover well anyway.
01526         if (SS.isEmpty())
01527           Diag(R.getNameLoc(), diagnostic_suggest)
01528             << Name << CorrectedQuotedStr;
01529         else
01530           Diag(R.getNameLoc(), diag::err_no_member_suggest)
01531             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
01532             << SS.getRange();
01533 
01534         // Don't try to recover; it won't work.
01535         return true;
01536       }
01537     } else {
01538       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
01539       // because we aren't able to recover.
01540       if (SS.isEmpty())
01541         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
01542       else
01543         Diag(R.getNameLoc(), diag::err_no_member_suggest)
01544         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
01545         << SS.getRange();
01546       return true;
01547     }
01548   }
01549   R.clear();
01550 
01551   // Emit a special diagnostic for failed member lookups.
01552   // FIXME: computing the declaration context might fail here (?)
01553   if (!SS.isEmpty()) {
01554     Diag(R.getNameLoc(), diag::err_no_member)
01555       << Name << computeDeclContext(SS, false)
01556       << SS.getRange();
01557     return true;
01558   }
01559 
01560   // Give up, we can't recover.
01561   Diag(R.getNameLoc(), diagnostic) << Name;
01562   return true;
01563 }
01564 
01565 ExprResult Sema::ActOnIdExpression(Scope *S,
01566                                    CXXScopeSpec &SS,
01567                                    SourceLocation TemplateKWLoc,
01568                                    UnqualifiedId &Id,
01569                                    bool HasTrailingLParen,
01570                                    bool IsAddressOfOperand,
01571                                    CorrectionCandidateCallback *CCC) {
01572   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
01573          "cannot be direct & operand and have a trailing lparen");
01574 
01575   if (SS.isInvalid())
01576     return ExprError();
01577 
01578   TemplateArgumentListInfo TemplateArgsBuffer;
01579 
01580   // Decompose the UnqualifiedId into the following data.
01581   DeclarationNameInfo NameInfo;
01582   const TemplateArgumentListInfo *TemplateArgs;
01583   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
01584 
01585   DeclarationName Name = NameInfo.getName();
01586   IdentifierInfo *II = Name.getAsIdentifierInfo();
01587   SourceLocation NameLoc = NameInfo.getLoc();
01588 
01589   // C++ [temp.dep.expr]p3:
01590   //   An id-expression is type-dependent if it contains:
01591   //     -- an identifier that was declared with a dependent type,
01592   //        (note: handled after lookup)
01593   //     -- a template-id that is dependent,
01594   //        (note: handled in BuildTemplateIdExpr)
01595   //     -- a conversion-function-id that specifies a dependent type,
01596   //     -- a nested-name-specifier that contains a class-name that
01597   //        names a dependent type.
01598   // Determine whether this is a member of an unknown specialization;
01599   // we need to handle these differently.
01600   bool DependentID = false;
01601   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
01602       Name.getCXXNameType()->isDependentType()) {
01603     DependentID = true;
01604   } else if (SS.isSet()) {
01605     if (DeclContext *DC = computeDeclContext(SS, false)) {
01606       if (RequireCompleteDeclContext(SS, DC))
01607         return ExprError();
01608     } else {
01609       DependentID = true;
01610     }
01611   }
01612 
01613   if (DependentID)
01614     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
01615                                       IsAddressOfOperand, TemplateArgs);
01616 
01617   // Perform the required lookup.
01618   LookupResult R(*this, NameInfo, 
01619                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
01620                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
01621   if (TemplateArgs) {
01622     // Lookup the template name again to correctly establish the context in
01623     // which it was found. This is really unfortunate as we already did the
01624     // lookup to determine that it was a template name in the first place. If
01625     // this becomes a performance hit, we can work harder to preserve those
01626     // results until we get here but it's likely not worth it.
01627     bool MemberOfUnknownSpecialization;
01628     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
01629                        MemberOfUnknownSpecialization);
01630     
01631     if (MemberOfUnknownSpecialization ||
01632         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
01633       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
01634                                         IsAddressOfOperand, TemplateArgs);
01635   } else {
01636     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
01637     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
01638 
01639     // If the result might be in a dependent base class, this is a dependent 
01640     // id-expression.
01641     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
01642       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
01643                                         IsAddressOfOperand, TemplateArgs);
01644 
01645     // If this reference is in an Objective-C method, then we need to do
01646     // some special Objective-C lookup, too.
01647     if (IvarLookupFollowUp) {
01648       ExprResult E(LookupInObjCMethod(R, S, II, true));
01649       if (E.isInvalid())
01650         return ExprError();
01651 
01652       if (Expr *Ex = E.takeAs<Expr>())
01653         return Owned(Ex);
01654     }
01655   }
01656 
01657   if (R.isAmbiguous())
01658     return ExprError();
01659 
01660   // Determine whether this name might be a candidate for
01661   // argument-dependent lookup.
01662   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
01663 
01664   if (R.empty() && !ADL) {
01665     // Otherwise, this could be an implicitly declared function reference (legal
01666     // in C90, extension in C99, forbidden in C++).
01667     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
01668       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
01669       if (D) R.addDecl(D);
01670     }
01671 
01672     // If this name wasn't predeclared and if this is not a function
01673     // call, diagnose the problem.
01674     if (R.empty()) {
01675 
01676       // In Microsoft mode, if we are inside a template class member function
01677       // and we can't resolve an identifier then assume the identifier is type
01678       // dependent. The goal is to postpone name lookup to instantiation time 
01679       // to be able to search into type dependent base classes.
01680       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
01681           isa<CXXMethodDecl>(CurContext))
01682         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
01683                                           IsAddressOfOperand, TemplateArgs);
01684 
01685       CorrectionCandidateCallback DefaultValidator;
01686       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
01687         return ExprError();
01688 
01689       assert(!R.empty() &&
01690              "DiagnoseEmptyLookup returned false but added no results");
01691 
01692       // If we found an Objective-C instance variable, let
01693       // LookupInObjCMethod build the appropriate expression to
01694       // reference the ivar.
01695       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
01696         R.clear();
01697         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
01698         // In a hopelessly buggy code, Objective-C instance variable
01699         // lookup fails and no expression will be built to reference it.
01700         if (!E.isInvalid() && !E.get())
01701           return ExprError();
01702         return move(E);
01703       }
01704     }
01705   }
01706 
01707   // This is guaranteed from this point on.
01708   assert(!R.empty() || ADL);
01709 
01710   // Check whether this might be a C++ implicit instance member access.
01711   // C++ [class.mfct.non-static]p3:
01712   //   When an id-expression that is not part of a class member access
01713   //   syntax and not used to form a pointer to member is used in the
01714   //   body of a non-static member function of class X, if name lookup
01715   //   resolves the name in the id-expression to a non-static non-type
01716   //   member of some class C, the id-expression is transformed into a
01717   //   class member access expression using (*this) as the
01718   //   postfix-expression to the left of the . operator.
01719   //
01720   // But we don't actually need to do this for '&' operands if R
01721   // resolved to a function or overloaded function set, because the
01722   // expression is ill-formed if it actually works out to be a
01723   // non-static member function:
01724   //
01725   // C++ [expr.ref]p4:
01726   //   Otherwise, if E1.E2 refers to a non-static member function. . .
01727   //   [t]he expression can be used only as the left-hand operand of a
01728   //   member function call.
01729   //
01730   // There are other safeguards against such uses, but it's important
01731   // to get this right here so that we don't end up making a
01732   // spuriously dependent expression if we're inside a dependent
01733   // instance method.
01734   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
01735     bool MightBeImplicitMember;
01736     if (!IsAddressOfOperand)
01737       MightBeImplicitMember = true;
01738     else if (!SS.isEmpty())
01739       MightBeImplicitMember = false;
01740     else if (R.isOverloadedResult())
01741       MightBeImplicitMember = false;
01742     else if (R.isUnresolvableResult())
01743       MightBeImplicitMember = true;
01744     else
01745       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
01746                               isa<IndirectFieldDecl>(R.getFoundDecl());
01747 
01748     if (MightBeImplicitMember)
01749       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
01750                                              R, TemplateArgs);
01751   }
01752 
01753   if (TemplateArgs || TemplateKWLoc.isValid())
01754     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
01755 
01756   return BuildDeclarationNameExpr(SS, R, ADL);
01757 }
01758 
01759 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
01760 /// declaration name, generally during template instantiation.
01761 /// There's a large number of things which don't need to be done along
01762 /// this path.
01763 ExprResult
01764 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
01765                                         const DeclarationNameInfo &NameInfo) {
01766   DeclContext *DC;
01767   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
01768     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
01769                                      NameInfo, /*TemplateArgs=*/0);
01770 
01771   if (RequireCompleteDeclContext(SS, DC))
01772     return ExprError();
01773 
01774   LookupResult R(*this, NameInfo, LookupOrdinaryName);
01775   LookupQualifiedName(R, DC);
01776 
01777   if (R.isAmbiguous())
01778     return ExprError();
01779 
01780   if (R.empty()) {
01781     Diag(NameInfo.getLoc(), diag::err_no_member)
01782       << NameInfo.getName() << DC << SS.getRange();
01783     return ExprError();
01784   }
01785 
01786   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
01787 }
01788 
01789 /// LookupInObjCMethod - The parser has read a name in, and Sema has
01790 /// detected that we're currently inside an ObjC method.  Perform some
01791 /// additional lookup.
01792 ///
01793 /// Ideally, most of this would be done by lookup, but there's
01794 /// actually quite a lot of extra work involved.
01795 ///
01796 /// Returns a null sentinel to indicate trivial success.
01797 ExprResult
01798 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
01799                          IdentifierInfo *II, bool AllowBuiltinCreation) {
01800   SourceLocation Loc = Lookup.getNameLoc();
01801   ObjCMethodDecl *CurMethod = getCurMethodDecl();
01802 
01803   // There are two cases to handle here.  1) scoped lookup could have failed,
01804   // in which case we should look for an ivar.  2) scoped lookup could have
01805   // found a decl, but that decl is outside the current instance method (i.e.
01806   // a global variable).  In these two cases, we do a lookup for an ivar with
01807   // this name, if the lookup sucedes, we replace it our current decl.
01808 
01809   // If we're in a class method, we don't normally want to look for
01810   // ivars.  But if we don't find anything else, and there's an
01811   // ivar, that's an error.
01812   bool IsClassMethod = CurMethod->isClassMethod();
01813 
01814   bool LookForIvars;
01815   if (Lookup.empty())
01816     LookForIvars = true;
01817   else if (IsClassMethod)
01818     LookForIvars = false;
01819   else
01820     LookForIvars = (Lookup.isSingleResult() &&
01821                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
01822   ObjCInterfaceDecl *IFace = 0;
01823   if (LookForIvars) {
01824     IFace = CurMethod->getClassInterface();
01825     ObjCInterfaceDecl *ClassDeclared;
01826     ObjCIvarDecl *IV = 0;
01827     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
01828       // Diagnose using an ivar in a class method.
01829       if (IsClassMethod)
01830         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
01831                          << IV->getDeclName());
01832 
01833       // If we're referencing an invalid decl, just return this as a silent
01834       // error node.  The error diagnostic was already emitted on the decl.
01835       if (IV->isInvalidDecl())
01836         return ExprError();
01837 
01838       // Check if referencing a field with __attribute__((deprecated)).
01839       if (DiagnoseUseOfDecl(IV, Loc))
01840         return ExprError();
01841 
01842       // Diagnose the use of an ivar outside of the declaring class.
01843       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
01844           !declaresSameEntity(ClassDeclared, IFace) &&
01845           !getLangOpts().DebuggerSupport)
01846         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
01847 
01848       // FIXME: This should use a new expr for a direct reference, don't
01849       // turn this into Self->ivar, just return a BareIVarExpr or something.
01850       IdentifierInfo &II = Context.Idents.get("self");
01851       UnqualifiedId SelfName;
01852       SelfName.setIdentifier(&II, SourceLocation());
01853       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
01854       CXXScopeSpec SelfScopeSpec;
01855       SourceLocation TemplateKWLoc;
01856       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
01857                                               SelfName, false, false);
01858       if (SelfExpr.isInvalid())
01859         return ExprError();
01860 
01861       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
01862       if (SelfExpr.isInvalid())
01863         return ExprError();
01864 
01865       MarkAnyDeclReferenced(Loc, IV);
01866       return Owned(new (Context)
01867                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
01868                                    SelfExpr.take(), true, true));
01869     }
01870   } else if (CurMethod->isInstanceMethod()) {
01871     // We should warn if a local variable hides an ivar.
01872     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
01873       ObjCInterfaceDecl *ClassDeclared;
01874       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
01875         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
01876             declaresSameEntity(IFace, ClassDeclared))
01877           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
01878       }
01879     }
01880   } else if (Lookup.isSingleResult() &&
01881              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
01882     // If accessing a stand-alone ivar in a class method, this is an error.
01883     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
01884       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
01885                        << IV->getDeclName());
01886   }
01887 
01888   if (Lookup.empty() && II && AllowBuiltinCreation) {
01889     // FIXME. Consolidate this with similar code in LookupName.
01890     if (unsigned BuiltinID = II->getBuiltinID()) {
01891       if (!(getLangOpts().CPlusPlus &&
01892             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
01893         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
01894                                            S, Lookup.isForRedeclaration(),
01895                                            Lookup.getNameLoc());
01896         if (D) Lookup.addDecl(D);
01897       }
01898     }
01899   }
01900   // Sentinel value saying that we didn't do anything special.
01901   return Owned((Expr*) 0);
01902 }
01903 
01904 /// \brief Cast a base object to a member's actual type.
01905 ///
01906 /// Logically this happens in three phases:
01907 ///
01908 /// * First we cast from the base type to the naming class.
01909 ///   The naming class is the class into which we were looking
01910 ///   when we found the member;  it's the qualifier type if a
01911 ///   qualifier was provided, and otherwise it's the base type.
01912 ///
01913 /// * Next we cast from the naming class to the declaring class.
01914 ///   If the member we found was brought into a class's scope by
01915 ///   a using declaration, this is that class;  otherwise it's
01916 ///   the class declaring the member.
01917 ///
01918 /// * Finally we cast from the declaring class to the "true"
01919 ///   declaring class of the member.  This conversion does not
01920 ///   obey access control.
01921 ExprResult
01922 Sema::PerformObjectMemberConversion(Expr *From,
01923                                     NestedNameSpecifier *Qualifier,
01924                                     NamedDecl *FoundDecl,
01925                                     NamedDecl *Member) {
01926   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
01927   if (!RD)
01928     return Owned(From);
01929 
01930   QualType DestRecordType;
01931   QualType DestType;
01932   QualType FromRecordType;
01933   QualType FromType = From->getType();
01934   bool PointerConversions = false;
01935   if (isa<FieldDecl>(Member)) {
01936     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
01937 
01938     if (FromType->getAs<PointerType>()) {
01939       DestType = Context.getPointerType(DestRecordType);
01940       FromRecordType = FromType->getPointeeType();
01941       PointerConversions = true;
01942     } else {
01943       DestType = DestRecordType;
01944       FromRecordType = FromType;
01945     }
01946   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
01947     if (Method->isStatic())
01948       return Owned(From);
01949 
01950     DestType = Method->getThisType(Context);
01951     DestRecordType = DestType->getPointeeType();
01952 
01953     if (FromType->getAs<PointerType>()) {
01954       FromRecordType = FromType->getPointeeType();
01955       PointerConversions = true;
01956     } else {
01957       FromRecordType = FromType;
01958       DestType = DestRecordType;
01959     }
01960   } else {
01961     // No conversion necessary.
01962     return Owned(From);
01963   }
01964 
01965   if (DestType->isDependentType() || FromType->isDependentType())
01966     return Owned(From);
01967 
01968   // If the unqualified types are the same, no conversion is necessary.
01969   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
01970     return Owned(From);
01971 
01972   SourceRange FromRange = From->getSourceRange();
01973   SourceLocation FromLoc = FromRange.getBegin();
01974 
01975   ExprValueKind VK = From->getValueKind();
01976 
01977   // C++ [class.member.lookup]p8:
01978   //   [...] Ambiguities can often be resolved by qualifying a name with its
01979   //   class name.
01980   //
01981   // If the member was a qualified name and the qualified referred to a
01982   // specific base subobject type, we'll cast to that intermediate type
01983   // first and then to the object in which the member is declared. That allows
01984   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
01985   //
01986   //   class Base { public: int x; };
01987   //   class Derived1 : public Base { };
01988   //   class Derived2 : public Base { };
01989   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
01990   //
01991   //   void VeryDerived::f() {
01992   //     x = 17; // error: ambiguous base subobjects
01993   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
01994   //   }
01995   if (Qualifier) {
01996     QualType QType = QualType(Qualifier->getAsType(), 0);
01997     assert(!QType.isNull() && "lookup done with dependent qualifier?");
01998     assert(QType->isRecordType() && "lookup done with non-record type");
01999 
02000     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
02001 
02002     // In C++98, the qualifier type doesn't actually have to be a base
02003     // type of the object type, in which case we just ignore it.
02004     // Otherwise build the appropriate casts.
02005     if (IsDerivedFrom(FromRecordType, QRecordType)) {
02006       CXXCastPath BasePath;
02007       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
02008                                        FromLoc, FromRange, &BasePath))
02009         return ExprError();
02010 
02011       if (PointerConversions)
02012         QType = Context.getPointerType(QType);
02013       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
02014                                VK, &BasePath).take();
02015 
02016       FromType = QType;
02017       FromRecordType = QRecordType;
02018 
02019       // If the qualifier type was the same as the destination type,
02020       // we're done.
02021       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
02022         return Owned(From);
02023     }
02024   }
02025 
02026   bool IgnoreAccess = false;
02027 
02028   // If we actually found the member through a using declaration, cast
02029   // down to the using declaration's type.
02030   //
02031   // Pointer equality is fine here because only one declaration of a
02032   // class ever has member declarations.
02033   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
02034     assert(isa<UsingShadowDecl>(FoundDecl));
02035     QualType URecordType = Context.getTypeDeclType(
02036                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
02037 
02038     // We only need to do this if the naming-class to declaring-class
02039     // conversion is non-trivial.
02040     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
02041       assert(IsDerivedFrom(FromRecordType, URecordType));
02042       CXXCastPath BasePath;
02043       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
02044                                        FromLoc, FromRange, &BasePath))
02045         return ExprError();
02046 
02047       QualType UType = URecordType;
02048       if (PointerConversions)
02049         UType = Context.getPointerType(UType);
02050       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
02051                                VK, &BasePath).take();
02052       FromType = UType;
02053       FromRecordType = URecordType;
02054     }
02055 
02056     // We don't do access control for the conversion from the
02057     // declaring class to the true declaring class.
02058     IgnoreAccess = true;
02059   }
02060 
02061   CXXCastPath BasePath;
02062   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
02063                                    FromLoc, FromRange, &BasePath,
02064                                    IgnoreAccess))
02065     return ExprError();
02066 
02067   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
02068                            VK, &BasePath);
02069 }
02070 
02071 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
02072                                       const LookupResult &R,
02073                                       bool HasTrailingLParen) {
02074   // Only when used directly as the postfix-expression of a call.
02075   if (!HasTrailingLParen)
02076     return false;
02077 
02078   // Never if a scope specifier was provided.
02079   if (SS.isSet())
02080     return false;
02081 
02082   // Only in C++ or ObjC++.
02083   if (!getLangOpts().CPlusPlus)
02084     return false;
02085 
02086   // Turn off ADL when we find certain kinds of declarations during
02087   // normal lookup:
02088   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
02089     NamedDecl *D = *I;
02090 
02091     // C++0x [basic.lookup.argdep]p3:
02092     //     -- a declaration of a class member
02093     // Since using decls preserve this property, we check this on the
02094     // original decl.
02095     if (D->isCXXClassMember())
02096       return false;
02097 
02098     // C++0x [basic.lookup.argdep]p3:
02099     //     -- a block-scope function declaration that is not a
02100     //        using-declaration
02101     // NOTE: we also trigger this for function templates (in fact, we
02102     // don't check the decl type at all, since all other decl types
02103     // turn off ADL anyway).
02104     if (isa<UsingShadowDecl>(D))
02105       D = cast<UsingShadowDecl>(D)->getTargetDecl();
02106     else if (D->getDeclContext()->isFunctionOrMethod())
02107       return false;
02108 
02109     // C++0x [basic.lookup.argdep]p3:
02110     //     -- a declaration that is neither a function or a function
02111     //        template
02112     // And also for builtin functions.
02113     if (isa<FunctionDecl>(D)) {
02114       FunctionDecl *FDecl = cast<FunctionDecl>(D);
02115 
02116       // But also builtin functions.
02117       if (FDecl->getBuiltinID() && FDecl->isImplicit())
02118         return false;
02119     } else if (!isa<FunctionTemplateDecl>(D))
02120       return false;
02121   }
02122 
02123   return true;
02124 }
02125 
02126 
02127 /// Diagnoses obvious problems with the use of the given declaration
02128 /// as an expression.  This is only actually called for lookups that
02129 /// were not overloaded, and it doesn't promise that the declaration
02130 /// will in fact be used.
02131 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
02132   if (isa<TypedefNameDecl>(D)) {
02133     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
02134     return true;
02135   }
02136 
02137   if (isa<ObjCInterfaceDecl>(D)) {
02138     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
02139     return true;
02140   }
02141 
02142   if (isa<NamespaceDecl>(D)) {
02143     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
02144     return true;
02145   }
02146 
02147   return false;
02148 }
02149 
02150 ExprResult
02151 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
02152                                LookupResult &R,
02153                                bool NeedsADL) {
02154   // If this is a single, fully-resolved result and we don't need ADL,
02155   // just build an ordinary singleton decl ref.
02156   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
02157     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
02158                                     R.getFoundDecl());
02159 
02160   // We only need to check the declaration if there's exactly one
02161   // result, because in the overloaded case the results can only be
02162   // functions and function templates.
02163   if (R.isSingleResult() &&
02164       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
02165     return ExprError();
02166 
02167   // Otherwise, just build an unresolved lookup expression.  Suppress
02168   // any lookup-related diagnostics; we'll hash these out later, when
02169   // we've picked a target.
02170   R.suppressDiagnostics();
02171 
02172   UnresolvedLookupExpr *ULE
02173     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
02174                                    SS.getWithLocInContext(Context),
02175                                    R.getLookupNameInfo(),
02176                                    NeedsADL, R.isOverloadedResult(),
02177                                    R.begin(), R.end());
02178 
02179   return Owned(ULE);
02180 }
02181 
02182 /// \brief Complete semantic analysis for a reference to the given declaration.
02183 ExprResult
02184 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
02185                                const DeclarationNameInfo &NameInfo,
02186                                NamedDecl *D) {
02187   assert(D && "Cannot refer to a NULL declaration");
02188   assert(!isa<FunctionTemplateDecl>(D) &&
02189          "Cannot refer unambiguously to a function template");
02190 
02191   SourceLocation Loc = NameInfo.getLoc();
02192   if (CheckDeclInExpr(*this, Loc, D))
02193     return ExprError();
02194 
02195   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
02196     // Specifically diagnose references to class templates that are missing
02197     // a template argument list.
02198     Diag(Loc, diag::err_template_decl_ref)
02199       << Template << SS.getRange();
02200     Diag(Template->getLocation(), diag::note_template_decl_here);
02201     return ExprError();
02202   }
02203 
02204   // Make sure that we're referring to a value.
02205   ValueDecl *VD = dyn_cast<ValueDecl>(D);
02206   if (!VD) {
02207     Diag(Loc, diag::err_ref_non_value)
02208       << D << SS.getRange();
02209     Diag(D->getLocation(), diag::note_declared_at);
02210     return ExprError();
02211   }
02212 
02213   // Check whether this declaration can be used. Note that we suppress
02214   // this check when we're going to perform argument-dependent lookup
02215   // on this function name, because this might not be the function
02216   // that overload resolution actually selects.
02217   if (DiagnoseUseOfDecl(VD, Loc))
02218     return ExprError();
02219 
02220   // Only create DeclRefExpr's for valid Decl's.
02221   if (VD->isInvalidDecl())
02222     return ExprError();
02223 
02224   // Handle members of anonymous structs and unions.  If we got here,
02225   // and the reference is to a class member indirect field, then this
02226   // must be the subject of a pointer-to-member expression.
02227   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
02228     if (!indirectField->isCXXClassMember())
02229       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
02230                                                       indirectField);
02231 
02232   {
02233     QualType type = VD->getType();
02234     ExprValueKind valueKind = VK_RValue;
02235 
02236     switch (D->getKind()) {
02237     // Ignore all the non-ValueDecl kinds.
02238 #define ABSTRACT_DECL(kind)
02239 #define VALUE(type, base)
02240 #define DECL(type, base) \
02241     case Decl::type:
02242 #include "clang/AST/DeclNodes.inc"
02243       llvm_unreachable("invalid value decl kind");
02244 
02245     // These shouldn't make it here.
02246     case Decl::ObjCAtDefsField:
02247     case Decl::ObjCIvar:
02248       llvm_unreachable("forming non-member reference to ivar?");
02249 
02250     // Enum constants are always r-values and never references.
02251     // Unresolved using declarations are dependent.
02252     case Decl::EnumConstant:
02253     case Decl::UnresolvedUsingValue:
02254       valueKind = VK_RValue;
02255       break;
02256 
02257     // Fields and indirect fields that got here must be for
02258     // pointer-to-member expressions; we just call them l-values for
02259     // internal consistency, because this subexpression doesn't really
02260     // exist in the high-level semantics.
02261     case Decl::Field:
02262     case Decl::IndirectField:
02263       assert(getLangOpts().CPlusPlus &&
02264              "building reference to field in C?");
02265 
02266       // These can't have reference type in well-formed programs, but
02267       // for internal consistency we do this anyway.
02268       type = type.getNonReferenceType();
02269       valueKind = VK_LValue;
02270       break;
02271 
02272     // Non-type template parameters are either l-values or r-values
02273     // depending on the type.
02274     case Decl::NonTypeTemplateParm: {
02275       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
02276         type = reftype->getPointeeType();
02277         valueKind = VK_LValue; // even if the parameter is an r-value reference
02278         break;
02279       }
02280 
02281       // For non-references, we need to strip qualifiers just in case
02282       // the template parameter was declared as 'const int' or whatever.
02283       valueKind = VK_RValue;
02284       type = type.getUnqualifiedType();
02285       break;
02286     }
02287 
02288     case Decl::Var:
02289       // In C, "extern void blah;" is valid and is an r-value.
02290       if (!getLangOpts().CPlusPlus &&
02291           !type.hasQualifiers() &&
02292           type->isVoidType()) {
02293         valueKind = VK_RValue;
02294         break;
02295       }
02296       // fallthrough
02297 
02298     case Decl::ImplicitParam:
02299     case Decl::ParmVar: {
02300       // These are always l-values.
02301       valueKind = VK_LValue;
02302       type = type.getNonReferenceType();
02303 
02304       // FIXME: Does the addition of const really only apply in
02305       // potentially-evaluated contexts? Since the variable isn't actually
02306       // captured in an unevaluated context, it seems that the answer is no.
02307       if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
02308         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
02309         if (!CapturedType.isNull())
02310           type = CapturedType;
02311       }
02312       
02313       break;
02314     }
02315         
02316     case Decl::Function: {
02317       const FunctionType *fty = type->castAs<FunctionType>();
02318 
02319       // If we're referring to a function with an __unknown_anytype
02320       // result type, make the entire expression __unknown_anytype.
02321       if (fty->getResultType() == Context.UnknownAnyTy) {
02322         type = Context.UnknownAnyTy;
02323         valueKind = VK_RValue;
02324         break;
02325       }
02326 
02327       // Functions are l-values in C++.
02328       if (getLangOpts().CPlusPlus) {
02329         valueKind = VK_LValue;
02330         break;
02331       }
02332       
02333       // C99 DR 316 says that, if a function type comes from a
02334       // function definition (without a prototype), that type is only
02335       // used for checking compatibility. Therefore, when referencing
02336       // the function, we pretend that we don't have the full function
02337       // type.
02338       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
02339           isa<FunctionProtoType>(fty))
02340         type = Context.getFunctionNoProtoType(fty->getResultType(),
02341                                               fty->getExtInfo());
02342 
02343       // Functions are r-values in C.
02344       valueKind = VK_RValue;
02345       break;
02346     }
02347 
02348     case Decl::CXXMethod:
02349       // If we're referring to a method with an __unknown_anytype
02350       // result type, make the entire expression __unknown_anytype.
02351       // This should only be possible with a type written directly.
02352       if (const FunctionProtoType *proto
02353             = dyn_cast<FunctionProtoType>(VD->getType()))
02354         if (proto->getResultType() == Context.UnknownAnyTy) {
02355           type = Context.UnknownAnyTy;
02356           valueKind = VK_RValue;
02357           break;
02358         }
02359 
02360       // C++ methods are l-values if static, r-values if non-static.
02361       if (cast<CXXMethodDecl>(VD)->isStatic()) {
02362         valueKind = VK_LValue;
02363         break;
02364       }
02365       // fallthrough
02366 
02367     case Decl::CXXConversion:
02368     case Decl::CXXDestructor:
02369     case Decl::CXXConstructor:
02370       valueKind = VK_RValue;
02371       break;
02372     }
02373 
02374     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
02375   }
02376 }
02377 
02378 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
02379   PredefinedExpr::IdentType IT;
02380 
02381   switch (Kind) {
02382   default: llvm_unreachable("Unknown simple primary expr!");
02383   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
02384   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
02385   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
02386   }
02387 
02388   // Pre-defined identifiers are of type char[x], where x is the length of the
02389   // string.
02390 
02391   Decl *currentDecl = getCurFunctionOrMethodDecl();
02392   if (!currentDecl && getCurBlock())
02393     currentDecl = getCurBlock()->TheDecl;
02394   if (!currentDecl) {
02395     Diag(Loc, diag::ext_predef_outside_function);
02396     currentDecl = Context.getTranslationUnitDecl();
02397   }
02398 
02399   QualType ResTy;
02400   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
02401     ResTy = Context.DependentTy;
02402   } else {
02403     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
02404 
02405     llvm::APInt LengthI(32, Length + 1);
02406     ResTy = Context.CharTy.withConst();
02407     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
02408   }
02409   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
02410 }
02411 
02412 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
02413   SmallString<16> CharBuffer;
02414   bool Invalid = false;
02415   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
02416   if (Invalid)
02417     return ExprError();
02418 
02419   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
02420                             PP, Tok.getKind());
02421   if (Literal.hadError())
02422     return ExprError();
02423 
02424   QualType Ty;
02425   if (Literal.isWide())
02426     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
02427   else if (Literal.isUTF16())
02428     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
02429   else if (Literal.isUTF32())
02430     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
02431   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
02432     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
02433   else
02434     Ty = Context.CharTy;  // 'x' -> char in C++
02435 
02436   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
02437   if (Literal.isWide())
02438     Kind = CharacterLiteral::Wide;
02439   else if (Literal.isUTF16())
02440     Kind = CharacterLiteral::UTF16;
02441   else if (Literal.isUTF32())
02442     Kind = CharacterLiteral::UTF32;
02443 
02444   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
02445                                              Tok.getLocation());
02446 
02447   if (Literal.getUDSuffix().empty())
02448     return Owned(Lit);
02449 
02450   // We're building a user-defined literal.
02451   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
02452   SourceLocation UDSuffixLoc =
02453     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
02454 
02455   // Make sure we're allowed user-defined literals here.
02456   if (!UDLScope)
02457     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
02458 
02459   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
02460   //   operator "" X (ch)
02461   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
02462                                         llvm::makeArrayRef(&Lit, 1),
02463                                         Tok.getLocation());
02464 }
02465 
02466 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
02467   unsigned IntSize = Context.getTargetInfo().getIntWidth();
02468   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
02469                                       Context.IntTy, Loc));
02470 }
02471 
02472 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
02473                                   QualType Ty, SourceLocation Loc) {
02474   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
02475 
02476   using llvm::APFloat;
02477   APFloat Val(Format);
02478 
02479   APFloat::opStatus result = Literal.GetFloatValue(Val);
02480 
02481   // Overflow is always an error, but underflow is only an error if
02482   // we underflowed to zero (APFloat reports denormals as underflow).
02483   if ((result & APFloat::opOverflow) ||
02484       ((result & APFloat::opUnderflow) && Val.isZero())) {
02485     unsigned diagnostic;
02486     SmallString<20> buffer;
02487     if (result & APFloat::opOverflow) {
02488       diagnostic = diag::warn_float_overflow;
02489       APFloat::getLargest(Format).toString(buffer);
02490     } else {
02491       diagnostic = diag::warn_float_underflow;
02492       APFloat::getSmallest(Format).toString(buffer);
02493     }
02494 
02495     S.Diag(Loc, diagnostic)
02496       << Ty
02497       << StringRef(buffer.data(), buffer.size());
02498   }
02499 
02500   bool isExact = (result == APFloat::opOK);
02501   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
02502 }
02503 
02504 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
02505   // Fast path for a single digit (which is quite common).  A single digit
02506   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
02507   if (Tok.getLength() == 1) {
02508     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
02509     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
02510   }
02511 
02512   SmallString<512> IntegerBuffer;
02513   // Add padding so that NumericLiteralParser can overread by one character.
02514   IntegerBuffer.resize(Tok.getLength()+1);
02515   const char *ThisTokBegin = &IntegerBuffer[0];
02516 
02517   // Get the spelling of the token, which eliminates trigraphs, etc.
02518   bool Invalid = false;
02519   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
02520   if (Invalid)
02521     return ExprError();
02522 
02523   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
02524                                Tok.getLocation(), PP);
02525   if (Literal.hadError)
02526     return ExprError();
02527 
02528   if (Literal.hasUDSuffix()) {
02529     // We're building a user-defined literal.
02530     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
02531     SourceLocation UDSuffixLoc =
02532       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
02533 
02534     // Make sure we're allowed user-defined literals here.
02535     if (!UDLScope)
02536       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
02537 
02538     QualType CookedTy;
02539     if (Literal.isFloatingLiteral()) {
02540       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
02541       // long double, the literal is treated as a call of the form
02542       //   operator "" X (f L)
02543       CookedTy = Context.LongDoubleTy;
02544     } else {
02545       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
02546       // unsigned long long, the literal is treated as a call of the form
02547       //   operator "" X (n ULL)
02548       CookedTy = Context.UnsignedLongLongTy;
02549     }
02550 
02551     DeclarationName OpName =
02552       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
02553     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
02554     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
02555 
02556     // Perform literal operator lookup to determine if we're building a raw
02557     // literal or a cooked one.
02558     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
02559     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
02560                                   /*AllowRawAndTemplate*/true)) {
02561     case LOLR_Error:
02562       return ExprError();
02563 
02564     case LOLR_Cooked: {
02565       Expr *Lit;
02566       if (Literal.isFloatingLiteral()) {
02567         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
02568       } else {
02569         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
02570         if (Literal.GetIntegerValue(ResultVal))
02571           Diag(Tok.getLocation(), diag::warn_integer_too_large);
02572         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
02573                                      Tok.getLocation());
02574       }
02575       return BuildLiteralOperatorCall(R, OpNameInfo,
02576                                       llvm::makeArrayRef(&Lit, 1),
02577                                       Tok.getLocation());
02578     }
02579 
02580     case LOLR_Raw: {
02581       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
02582       // literal is treated as a call of the form
02583       //   operator "" X ("n")
02584       SourceLocation TokLoc = Tok.getLocation();
02585       unsigned Length = Literal.getUDSuffixOffset();
02586       QualType StrTy = Context.getConstantArrayType(
02587           Context.CharTy, llvm::APInt(32, Length + 1),
02588           ArrayType::Normal, 0);
02589       Expr *Lit = StringLiteral::Create(
02590           Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
02591           /*Pascal*/false, StrTy, &TokLoc, 1);
02592       return BuildLiteralOperatorCall(R, OpNameInfo,
02593                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
02594     }
02595 
02596     case LOLR_Template:
02597       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
02598       // template), L is treated as a call fo the form
02599       //   operator "" X <'c1', 'c2', ... 'ck'>()
02600       // where n is the source character sequence c1 c2 ... ck.
02601       TemplateArgumentListInfo ExplicitArgs;
02602       unsigned CharBits = Context.getIntWidth(Context.CharTy);
02603       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
02604       llvm::APSInt Value(CharBits, CharIsUnsigned);
02605       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
02606         Value = ThisTokBegin[I];
02607         TemplateArgument Arg(Value, Context.CharTy);
02608         TemplateArgumentLocInfo ArgInfo;
02609         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
02610       }
02611       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
02612                                       Tok.getLocation(), &ExplicitArgs);
02613     }
02614 
02615     llvm_unreachable("unexpected literal operator lookup result");
02616   }
02617 
02618   Expr *Res;
02619 
02620   if (Literal.isFloatingLiteral()) {
02621     QualType Ty;
02622     if (Literal.isFloat)
02623       Ty = Context.FloatTy;
02624     else if (!Literal.isLong)
02625       Ty = Context.DoubleTy;
02626     else
02627       Ty = Context.LongDoubleTy;
02628 
02629     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
02630 
02631     if (Ty == Context.DoubleTy) {
02632       if (getLangOpts().SinglePrecisionConstants) {
02633         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
02634       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
02635         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
02636         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
02637       }
02638     }
02639   } else if (!Literal.isIntegerLiteral()) {
02640     return ExprError();
02641   } else {
02642     QualType Ty;
02643 
02644     // long long is a C99 feature.
02645     if (!getLangOpts().C99 && Literal.isLongLong)
02646       Diag(Tok.getLocation(),
02647            getLangOpts().CPlusPlus0x ?
02648              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
02649 
02650     // Get the value in the widest-possible width.
02651     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
02652     // The microsoft literal suffix extensions support 128-bit literals, which
02653     // may be wider than [u]intmax_t.
02654     if (Literal.isMicrosoftInteger && MaxWidth < 128)
02655       MaxWidth = 128;
02656     llvm::APInt ResultVal(MaxWidth, 0);
02657 
02658     if (Literal.GetIntegerValue(ResultVal)) {
02659       // If this value didn't fit into uintmax_t, warn and force to ull.
02660       Diag(Tok.getLocation(), diag::warn_integer_too_large);
02661       Ty = Context.UnsignedLongLongTy;
02662       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
02663              "long long is not intmax_t?");
02664     } else {
02665       // If this value fits into a ULL, try to figure out what else it fits into
02666       // according to the rules of C99 6.4.4.1p5.
02667 
02668       // Octal, Hexadecimal, and integers with a U suffix are allowed to
02669       // be an unsigned int.
02670       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
02671 
02672       // Check from smallest to largest, picking the smallest type we can.
02673       unsigned Width = 0;
02674       if (!Literal.isLong && !Literal.isLongLong) {
02675         // Are int/unsigned possibilities?
02676         unsigned IntSize = Context.getTargetInfo().getIntWidth();
02677 
02678         // Does it fit in a unsigned int?
02679         if (ResultVal.isIntN(IntSize)) {
02680           // Does it fit in a signed int?
02681           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
02682             Ty = Context.IntTy;
02683           else if (AllowUnsigned)
02684             Ty = Context.UnsignedIntTy;
02685           Width = IntSize;
02686         }
02687       }
02688 
02689       // Are long/unsigned long possibilities?
02690       if (Ty.isNull() && !Literal.isLongLong) {
02691         unsigned LongSize = Context.getTargetInfo().getLongWidth();
02692 
02693         // Does it fit in a unsigned long?
02694         if (ResultVal.isIntN(LongSize)) {
02695           // Does it fit in a signed long?
02696           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
02697             Ty = Context.LongTy;
02698           else if (AllowUnsigned)
02699             Ty = Context.UnsignedLongTy;
02700           Width = LongSize;
02701         }
02702       }
02703 
02704       // Check long long if needed.
02705       if (Ty.isNull()) {
02706         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
02707 
02708         // Does it fit in a unsigned long long?
02709         if (ResultVal.isIntN(LongLongSize)) {
02710           // Does it fit in a signed long long?
02711           // To be compatible with MSVC, hex integer literals ending with the
02712           // LL or i64 suffix are always signed in Microsoft mode.
02713           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
02714               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
02715             Ty = Context.LongLongTy;
02716           else if (AllowUnsigned)
02717             Ty = Context.UnsignedLongLongTy;
02718           Width = LongLongSize;
02719         }
02720       }
02721         
02722       // If it doesn't fit in unsigned long long, and we're using Microsoft
02723       // extensions, then its a 128-bit integer literal.
02724       if (Ty.isNull() && Literal.isMicrosoftInteger) {
02725         if (Literal.isUnsigned)
02726           Ty = Context.UnsignedInt128Ty;
02727         else
02728           Ty = Context.Int128Ty;
02729         Width = 128;
02730       }
02731 
02732       // If we still couldn't decide a type, we probably have something that
02733       // does not fit in a signed long long, but has no U suffix.
02734       if (Ty.isNull()) {
02735         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
02736         Ty = Context.UnsignedLongLongTy;
02737         Width = Context.getTargetInfo().getLongLongWidth();
02738       }
02739 
02740       if (ResultVal.getBitWidth() != Width)
02741         ResultVal = ResultVal.trunc(Width);
02742     }
02743     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
02744   }
02745 
02746   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
02747   if (Literal.isImaginary)
02748     Res = new (Context) ImaginaryLiteral(Res,
02749                                         Context.getComplexType(Res->getType()));
02750 
02751   return Owned(Res);
02752 }
02753 
02754 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
02755   assert((E != 0) && "ActOnParenExpr() missing expr");
02756   return Owned(new (Context) ParenExpr(L, R, E));
02757 }
02758 
02759 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
02760                                          SourceLocation Loc,
02761                                          SourceRange ArgRange) {
02762   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
02763   // scalar or vector data type argument..."
02764   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
02765   // type (C99 6.2.5p18) or void.
02766   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
02767     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
02768       << T << ArgRange;
02769     return true;
02770   }
02771 
02772   assert((T->isVoidType() || !T->isIncompleteType()) &&
02773          "Scalar types should always be complete");
02774   return false;
02775 }
02776 
02777 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
02778                                            SourceLocation Loc,
02779                                            SourceRange ArgRange,
02780                                            UnaryExprOrTypeTrait TraitKind) {
02781   // C99 6.5.3.4p1:
02782   if (T->isFunctionType()) {
02783     // alignof(function) is allowed as an extension.
02784     if (TraitKind == UETT_SizeOf)
02785       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
02786     return false;
02787   }
02788 
02789   // Allow sizeof(void)/alignof(void) as an extension.
02790   if (T->isVoidType()) {
02791     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
02792     return false;
02793   }
02794 
02795   return true;
02796 }
02797 
02798 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
02799                                              SourceLocation Loc,
02800                                              SourceRange ArgRange,
02801                                              UnaryExprOrTypeTrait TraitKind) {
02802   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
02803   if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
02804     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
02805       << T << (TraitKind == UETT_SizeOf)
02806       << ArgRange;
02807     return true;
02808   }
02809 
02810   return false;
02811 }
02812 
02813 /// \brief Check the constrains on expression operands to unary type expression
02814 /// and type traits.
02815 ///
02816 /// Completes any types necessary and validates the constraints on the operand
02817 /// expression. The logic mostly mirrors the type-based overload, but may modify
02818 /// the expression as it completes the type for that expression through template
02819 /// instantiation, etc.
02820 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
02821                                             UnaryExprOrTypeTrait ExprKind) {
02822   QualType ExprTy = E->getType();
02823 
02824   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
02825   //   the result is the size of the referenced type."
02826   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
02827   //   result shall be the alignment of the referenced type."
02828   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
02829     ExprTy = Ref->getPointeeType();
02830 
02831   if (ExprKind == UETT_VecStep)
02832     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
02833                                         E->getSourceRange());
02834 
02835   // Whitelist some types as extensions
02836   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
02837                                       E->getSourceRange(), ExprKind))
02838     return false;
02839 
02840   if (RequireCompleteExprType(E,
02841                               diag::err_sizeof_alignof_incomplete_type,
02842                               ExprKind, E->getSourceRange()))
02843     return true;
02844 
02845   // Completeing the expression's type may have changed it.
02846   ExprTy = E->getType();
02847   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
02848     ExprTy = Ref->getPointeeType();
02849 
02850   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
02851                                        E->getSourceRange(), ExprKind))
02852     return true;
02853 
02854   if (ExprKind == UETT_SizeOf) {
02855     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
02856       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
02857         QualType OType = PVD->getOriginalType();
02858         QualType Type = PVD->getType();
02859         if (Type->isPointerType() && OType->isArrayType()) {
02860           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
02861             << Type << OType;
02862           Diag(PVD->getLocation(), diag::note_declared_at);
02863         }
02864       }
02865     }
02866   }
02867 
02868   return false;
02869 }
02870 
02871 /// \brief Check the constraints on operands to unary expression and type
02872 /// traits.
02873 ///
02874 /// This will complete any types necessary, and validate the various constraints
02875 /// on those operands.
02876 ///
02877 /// The UsualUnaryConversions() function is *not* called by this routine.
02878 /// C99 6.3.2.1p[2-4] all state:
02879 ///   Except when it is the operand of the sizeof operator ...
02880 ///
02881 /// C++ [expr.sizeof]p4
02882 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
02883 ///   standard conversions are not applied to the operand of sizeof.
02884 ///
02885 /// This policy is followed for all of the unary trait expressions.
02886 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
02887                                             SourceLocation OpLoc,
02888                                             SourceRange ExprRange,
02889                                             UnaryExprOrTypeTrait ExprKind) {
02890   if (ExprType->isDependentType())
02891     return false;
02892 
02893   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
02894   //   the result is the size of the referenced type."
02895   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
02896   //   result shall be the alignment of the referenced type."
02897   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
02898     ExprType = Ref->getPointeeType();
02899 
02900   if (ExprKind == UETT_VecStep)
02901     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
02902 
02903   // Whitelist some types as extensions
02904   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
02905                                       ExprKind))
02906     return false;
02907 
02908   if (RequireCompleteType(OpLoc, ExprType,
02909                           diag::err_sizeof_alignof_incomplete_type,
02910                           ExprKind, ExprRange))
02911     return true;
02912 
02913   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
02914                                        ExprKind))
02915     return true;
02916 
02917   return false;
02918 }
02919 
02920 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
02921   E = E->IgnoreParens();
02922 
02923   // alignof decl is always ok.
02924   if (isa<DeclRefExpr>(E))
02925     return false;
02926 
02927   // Cannot know anything else if the expression is dependent.
02928   if (E->isTypeDependent())
02929     return false;
02930 
02931   if (E->getBitField()) {
02932     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
02933        << 1 << E->getSourceRange();
02934     return true;
02935   }
02936 
02937   // Alignment of a field access is always okay, so long as it isn't a
02938   // bit-field.
02939   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
02940     if (isa<FieldDecl>(ME->getMemberDecl()))
02941       return false;
02942 
02943   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
02944 }
02945 
02946 bool Sema::CheckVecStepExpr(Expr *E) {
02947   E = E->IgnoreParens();
02948 
02949   // Cannot know anything else if the expression is dependent.
02950   if (E->isTypeDependent())
02951     return false;
02952 
02953   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
02954 }
02955 
02956 /// \brief Build a sizeof or alignof expression given a type operand.
02957 ExprResult
02958 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
02959                                      SourceLocation OpLoc,
02960                                      UnaryExprOrTypeTrait ExprKind,
02961                                      SourceRange R) {
02962   if (!TInfo)
02963     return ExprError();
02964 
02965   QualType T = TInfo->getType();
02966 
02967   if (!T->isDependentType() &&
02968       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
02969     return ExprError();
02970 
02971   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
02972   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
02973                                                       Context.getSizeType(),
02974                                                       OpLoc, R.getEnd()));
02975 }
02976 
02977 /// \brief Build a sizeof or alignof expression given an expression
02978 /// operand.
02979 ExprResult
02980 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
02981                                      UnaryExprOrTypeTrait ExprKind) {
02982   ExprResult PE = CheckPlaceholderExpr(E);
02983   if (PE.isInvalid()) 
02984     return ExprError();
02985 
02986   E = PE.get();
02987   
02988   // Verify that the operand is valid.
02989   bool isInvalid = false;
02990   if (E->isTypeDependent()) {
02991     // Delay type-checking for type-dependent expressions.
02992   } else if (ExprKind == UETT_AlignOf) {
02993     isInvalid = CheckAlignOfExpr(*this, E);
02994   } else if (ExprKind == UETT_VecStep) {
02995     isInvalid = CheckVecStepExpr(E);
02996   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
02997     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
02998     isInvalid = true;
02999   } else {
03000     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
03001   }
03002 
03003   if (isInvalid)
03004     return ExprError();
03005 
03006   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
03007     PE = TranformToPotentiallyEvaluated(E);
03008     if (PE.isInvalid()) return ExprError();
03009     E = PE.take();
03010   }
03011 
03012   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
03013   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
03014       ExprKind, E, Context.getSizeType(), OpLoc,
03015       E->getSourceRange().getEnd()));
03016 }
03017 
03018 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
03019 /// expr and the same for @c alignof and @c __alignof
03020 /// Note that the ArgRange is invalid if isType is false.
03021 ExprResult
03022 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
03023                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
03024                                     void *TyOrEx, const SourceRange &ArgRange) {
03025   // If error parsing type, ignore.
03026   if (TyOrEx == 0) return ExprError();
03027 
03028   if (IsType) {
03029     TypeSourceInfo *TInfo;
03030     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
03031     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
03032   }
03033 
03034   Expr *ArgEx = (Expr *)TyOrEx;
03035   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
03036   return move(Result);
03037 }
03038 
03039 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
03040                                      bool IsReal) {
03041   if (V.get()->isTypeDependent())
03042     return S.Context.DependentTy;
03043 
03044   // _Real and _Imag are only l-values for normal l-values.
03045   if (V.get()->getObjectKind() != OK_Ordinary) {
03046     V = S.DefaultLvalueConversion(V.take());
03047     if (V.isInvalid())
03048       return QualType();
03049   }
03050 
03051   // These operators return the element type of a complex type.
03052   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
03053     return CT->getElementType();
03054 
03055   // Otherwise they pass through real integer and floating point types here.
03056   if (V.get()->getType()->isArithmeticType())
03057     return V.get()->getType();
03058 
03059   // Test for placeholders.
03060   ExprResult PR = S.CheckPlaceholderExpr(V.get());
03061   if (PR.isInvalid()) return QualType();
03062   if (PR.get() != V.get()) {
03063     V = move(PR);
03064     return CheckRealImagOperand(S, V, Loc, IsReal);
03065   }
03066 
03067   // Reject anything else.
03068   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
03069     << (IsReal ? "__real" : "__imag");
03070   return QualType();
03071 }
03072 
03073 
03074 
03075 ExprResult
03076 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
03077                           tok::TokenKind Kind, Expr *Input) {
03078   UnaryOperatorKind Opc;
03079   switch (Kind) {
03080   default: llvm_unreachable("Unknown unary op!");
03081   case tok::plusplus:   Opc = UO_PostInc; break;
03082   case tok::minusminus: Opc = UO_PostDec; break;
03083   }
03084 
03085   // Since this might is a postfix expression, get rid of ParenListExprs.
03086   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
03087   if (Result.isInvalid()) return ExprError();
03088   Input = Result.take();
03089 
03090   return BuildUnaryOp(S, OpLoc, Opc, Input);
03091 }
03092 
03093 ExprResult
03094 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
03095                               Expr *Idx, SourceLocation RLoc) {
03096   // Since this might be a postfix expression, get rid of ParenListExprs.
03097   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
03098   if (Result.isInvalid()) return ExprError();
03099   Base = Result.take();
03100 
03101   Expr *LHSExp = Base, *RHSExp = Idx;
03102 
03103   if (getLangOpts().CPlusPlus &&
03104       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
03105     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
03106                                                   Context.DependentTy,
03107                                                   VK_LValue, OK_Ordinary,
03108                                                   RLoc));
03109   }
03110 
03111   if (getLangOpts().CPlusPlus &&
03112       (LHSExp->getType()->isRecordType() ||
03113        LHSExp->getType()->isEnumeralType() ||
03114        RHSExp->getType()->isRecordType() ||
03115        RHSExp->getType()->isEnumeralType()) &&
03116       !LHSExp->getType()->isObjCObjectPointerType()) {
03117     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
03118   }
03119 
03120   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
03121 }
03122 
03123 
03124 ExprResult
03125 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
03126                                       Expr *Idx, SourceLocation RLoc) {
03127   Expr *LHSExp = Base;
03128   Expr *RHSExp = Idx;
03129 
03130   // Perform default conversions.
03131   if (!LHSExp->getType()->getAs<VectorType>()) {
03132     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
03133     if (Result.isInvalid())
03134       return ExprError();
03135     LHSExp = Result.take();
03136   }
03137   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
03138   if (Result.isInvalid())
03139     return ExprError();
03140   RHSExp = Result.take();
03141 
03142   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
03143   ExprValueKind VK = VK_LValue;
03144   ExprObjectKind OK = OK_Ordinary;
03145 
03146   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
03147   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
03148   // in the subscript position. As a result, we need to derive the array base
03149   // and index from the expression types.
03150   Expr *BaseExpr, *IndexExpr;
03151   QualType ResultType;
03152   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
03153     BaseExpr = LHSExp;
03154     IndexExpr = RHSExp;
03155     ResultType = Context.DependentTy;
03156   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
03157     BaseExpr = LHSExp;
03158     IndexExpr = RHSExp;
03159     ResultType = PTy->getPointeeType();
03160   } else if (const ObjCObjectPointerType *PTy =
03161              LHSTy->getAs<ObjCObjectPointerType>()) {
03162     BaseExpr = LHSExp;
03163     IndexExpr = RHSExp;
03164     Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
03165     if (!Result.isInvalid())
03166       return Owned(Result.take());
03167     ResultType = PTy->getPointeeType();
03168   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
03169      // Handle the uncommon case of "123[Ptr]".
03170     BaseExpr = RHSExp;
03171     IndexExpr = LHSExp;
03172     ResultType = PTy->getPointeeType();
03173   } else if (const ObjCObjectPointerType *PTy =
03174                RHSTy->getAs<ObjCObjectPointerType>()) {
03175      // Handle the uncommon case of "123[Ptr]".
03176     BaseExpr = RHSExp;
03177     IndexExpr = LHSExp;
03178     ResultType = PTy->getPointeeType();
03179   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
03180     BaseExpr = LHSExp;    // vectors: V[123]
03181     IndexExpr = RHSExp;
03182     VK = LHSExp->getValueKind();
03183     if (VK != VK_RValue)
03184       OK = OK_VectorComponent;
03185 
03186     // FIXME: need to deal with const...
03187     ResultType = VTy->getElementType();
03188   } else if (LHSTy->isArrayType()) {
03189     // If we see an array that wasn't promoted by
03190     // DefaultFunctionArrayLvalueConversion, it must be an array that
03191     // wasn't promoted because of the C90 rule that doesn't
03192     // allow promoting non-lvalue arrays.  Warn, then
03193     // force the promotion here.
03194     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
03195         LHSExp->getSourceRange();
03196     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
03197                                CK_ArrayToPointerDecay).take();
03198     LHSTy = LHSExp->getType();
03199 
03200     BaseExpr = LHSExp;
03201     IndexExpr = RHSExp;
03202     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
03203   } else if (RHSTy->isArrayType()) {
03204     // Same as previous, except for 123[f().a] case
03205     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
03206         RHSExp->getSourceRange();
03207     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
03208                                CK_ArrayToPointerDecay).take();
03209     RHSTy = RHSExp->getType();
03210 
03211     BaseExpr = RHSExp;
03212     IndexExpr = LHSExp;
03213     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
03214   } else {
03215     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
03216        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
03217   }
03218   // C99 6.5.2.1p1
03219   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
03220     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
03221                      << IndexExpr->getSourceRange());
03222 
03223   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
03224        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
03225          && !IndexExpr->isTypeDependent())
03226     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
03227 
03228   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
03229   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
03230   // type. Note that Functions are not objects, and that (in C99 parlance)
03231   // incomplete types are not object types.
03232   if (ResultType->isFunctionType()) {
03233     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
03234       << ResultType << BaseExpr->getSourceRange();
03235     return ExprError();
03236   }
03237 
03238   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
03239     // GNU extension: subscripting on pointer to void
03240     Diag(LLoc, diag::ext_gnu_subscript_void_type)
03241       << BaseExpr->getSourceRange();
03242 
03243     // C forbids expressions of unqualified void type from being l-values.
03244     // See IsCForbiddenLValueType.
03245     if (!ResultType.hasQualifiers()) VK = VK_RValue;
03246   } else if (!ResultType->isDependentType() &&
03247       RequireCompleteType(LLoc, ResultType,
03248                           diag::err_subscript_incomplete_type, BaseExpr))
03249     return ExprError();
03250 
03251   // Diagnose bad cases where we step over interface counts.
03252   if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
03253     Diag(LLoc, diag::err_subscript_nonfragile_interface)
03254       << ResultType << BaseExpr->getSourceRange();
03255     return ExprError();
03256   }
03257 
03258   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
03259          !ResultType.isCForbiddenLValueType());
03260 
03261   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
03262                                                 ResultType, VK, OK, RLoc));
03263 }
03264 
03265 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
03266                                         FunctionDecl *FD,
03267                                         ParmVarDecl *Param) {
03268   if (Param->hasUnparsedDefaultArg()) {
03269     Diag(CallLoc,
03270          diag::err_use_of_default_argument_to_function_declared_later) <<
03271       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
03272     Diag(UnparsedDefaultArgLocs[Param],
03273          diag::note_default_argument_declared_here);
03274     return ExprError();
03275   }
03276   
03277   if (Param->hasUninstantiatedDefaultArg()) {
03278     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
03279 
03280     // Instantiate the expression.
03281     MultiLevelTemplateArgumentList ArgList
03282       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
03283 
03284     std::pair<const TemplateArgument *, unsigned> Innermost
03285       = ArgList.getInnermost();
03286     InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
03287                                Innermost.second);
03288 
03289     ExprResult Result;
03290     {
03291       // C++ [dcl.fct.default]p5:
03292       //   The names in the [default argument] expression are bound, and
03293       //   the semantic constraints are checked, at the point where the
03294       //   default argument expression appears.
03295       ContextRAII SavedContext(*this, FD);
03296       LocalInstantiationScope Local(*this);
03297       Result = SubstExpr(UninstExpr, ArgList);
03298     }
03299     if (Result.isInvalid())
03300       return ExprError();
03301 
03302     // Check the expression as an initializer for the parameter.
03303     InitializedEntity Entity
03304       = InitializedEntity::InitializeParameter(Context, Param);
03305     InitializationKind Kind
03306       = InitializationKind::CreateCopy(Param->getLocation(),
03307              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
03308     Expr *ResultE = Result.takeAs<Expr>();
03309 
03310     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
03311     Result = InitSeq.Perform(*this, Entity, Kind,
03312                              MultiExprArg(*this, &ResultE, 1));
03313     if (Result.isInvalid())
03314       return ExprError();
03315 
03316     Expr *Arg = Result.takeAs<Expr>();
03317     CheckImplicitConversions(Arg, Param->getOuterLocStart());
03318     // Build the default argument expression.
03319     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
03320   }
03321 
03322   // If the default expression creates temporaries, we need to
03323   // push them to the current stack of expression temporaries so they'll
03324   // be properly destroyed.
03325   // FIXME: We should really be rebuilding the default argument with new
03326   // bound temporaries; see the comment in PR5810.
03327   // We don't need to do that with block decls, though, because
03328   // blocks in default argument expression can never capture anything.
03329   if (isa<ExprWithCleanups>(Param->getInit())) {
03330     // Set the "needs cleanups" bit regardless of whether there are
03331     // any explicit objects.
03332     ExprNeedsCleanups = true;
03333 
03334     // Append all the objects to the cleanup list.  Right now, this
03335     // should always be a no-op, because blocks in default argument
03336     // expressions should never be able to capture anything.
03337     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
03338            "default argument expression has capturing blocks?");
03339   }
03340 
03341   // We already type-checked the argument, so we know it works. 
03342   // Just mark all of the declarations in this potentially-evaluated expression
03343   // as being "referenced".
03344   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
03345                                    /*SkipLocalVariables=*/true);
03346   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
03347 }
03348 
03349 /// ConvertArgumentsForCall - Converts the arguments specified in
03350 /// Args/NumArgs to the parameter types of the function FDecl with
03351 /// function prototype Proto. Call is the call expression itself, and
03352 /// Fn is the function expression. For a C++ member function, this
03353 /// routine does not attempt to convert the object argument. Returns
03354 /// true if the call is ill-formed.
03355 bool
03356 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
03357                               FunctionDecl *FDecl,
03358                               const FunctionProtoType *Proto,
03359                               Expr **Args, unsigned NumArgs,
03360                               SourceLocation RParenLoc,
03361                               bool IsExecConfig) {
03362   // Bail out early if calling a builtin with custom typechecking.
03363   // We don't need to do this in the 
03364   if (FDecl)
03365     if (unsigned ID = FDecl->getBuiltinID())
03366       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
03367         return false;
03368 
03369   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
03370   // assignment, to the types of the corresponding parameter, ...
03371   unsigned NumArgsInProto = Proto->getNumArgs();
03372   bool Invalid = false;
03373   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
03374   unsigned FnKind = Fn->getType()->isBlockPointerType()
03375                        ? 1 /* block */
03376                        : (IsExecConfig ? 3 /* kernel function (exec config) */
03377                                        : 0 /* function */);
03378 
03379   // If too few arguments are available (and we don't have default
03380   // arguments for the remaining parameters), don't make the call.
03381   if (NumArgs < NumArgsInProto) {
03382     if (NumArgs < MinArgs) {
03383       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
03384         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
03385                           ? diag::err_typecheck_call_too_few_args_one
03386                           : diag::err_typecheck_call_too_few_args_at_least_one)
03387           << FnKind
03388           << FDecl->getParamDecl(0) << Fn->getSourceRange();
03389       else
03390         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
03391                           ? diag::err_typecheck_call_too_few_args
03392                           : diag::err_typecheck_call_too_few_args_at_least)
03393           << FnKind
03394           << MinArgs << NumArgs << Fn->getSourceRange();
03395 
03396       // Emit the location of the prototype.
03397       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
03398         Diag(FDecl->getLocStart(), diag::note_callee_decl)
03399           << FDecl;
03400 
03401       return true;
03402     }
03403     Call->setNumArgs(Context, NumArgsInProto);
03404   }
03405 
03406   // If too many are passed and not variadic, error on the extras and drop
03407   // them.
03408   if (NumArgs > NumArgsInProto) {
03409     if (!Proto->isVariadic()) {
03410       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
03411         Diag(Args[NumArgsInProto]->getLocStart(),
03412              MinArgs == NumArgsInProto
03413                ? diag::err_typecheck_call_too_many_args_one
03414                : diag::err_typecheck_call_too_many_args_at_most_one)
03415           << FnKind
03416           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
03417           << SourceRange(Args[NumArgsInProto]->getLocStart(),
03418                          Args[NumArgs-1]->getLocEnd());
03419       else
03420         Diag(Args[NumArgsInProto]->getLocStart(),
03421              MinArgs == NumArgsInProto
03422                ? diag::err_typecheck_call_too_many_args
03423                : diag::err_typecheck_call_too_many_args_at_most)
03424           << FnKind
03425           << NumArgsInProto << NumArgs << Fn->getSourceRange()
03426           << SourceRange(Args[NumArgsInProto]->getLocStart(),
03427                          Args[NumArgs-1]->getLocEnd());
03428 
03429       // Emit the location of the prototype.
03430       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
03431         Diag(FDecl->getLocStart(), diag::note_callee_decl)
03432           << FDecl;
03433       
03434       // This deletes the extra arguments.
03435       Call->setNumArgs(Context, NumArgsInProto);
03436       return true;
03437     }
03438   }
03439   SmallVector<Expr *, 8> AllArgs;
03440   VariadicCallType CallType =
03441     Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
03442   if (Fn->getType()->isBlockPointerType())
03443     CallType = VariadicBlock; // Block
03444   else if (isa<MemberExpr>(Fn))
03445     CallType = VariadicMethod;
03446   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
03447                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
03448   if (Invalid)
03449     return true;
03450   unsigned TotalNumArgs = AllArgs.size();
03451   for (unsigned i = 0; i < TotalNumArgs; ++i)
03452     Call->setArg(i, AllArgs[i]);
03453 
03454   return false;
03455 }
03456 
03457 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
03458                                   FunctionDecl *FDecl,
03459                                   const FunctionProtoType *Proto,
03460                                   unsigned FirstProtoArg,
03461                                   Expr **Args, unsigned NumArgs,
03462                                   SmallVector<Expr *, 8> &AllArgs,
03463                                   VariadicCallType CallType,
03464                                   bool AllowExplicit) {
03465   unsigned NumArgsInProto = Proto->getNumArgs();
03466   unsigned NumArgsToCheck = NumArgs;
03467   bool Invalid = false;
03468   if (NumArgs != NumArgsInProto)
03469     // Use default arguments for missing arguments
03470     NumArgsToCheck = NumArgsInProto;
03471   unsigned ArgIx = 0;
03472   // Continue to check argument types (even if we have too few/many args).
03473   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
03474     QualType ProtoArgType = Proto->getArgType(i);
03475 
03476     Expr *Arg;
03477     ParmVarDecl *Param;
03478     if (ArgIx < NumArgs) {
03479       Arg = Args[ArgIx++];
03480 
03481       if (RequireCompleteType(Arg->getLocStart(),
03482                               ProtoArgType,
03483                               diag::err_call_incomplete_argument, Arg))
03484         return true;
03485 
03486       // Pass the argument
03487       Param = 0;
03488       if (FDecl && i < FDecl->getNumParams())
03489         Param = FDecl->getParamDecl(i);
03490 
03491       // Strip the unbridged-cast placeholder expression off, if applicable.
03492       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
03493           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
03494           (!Param || !Param->hasAttr<CFConsumedAttr>()))
03495         Arg = stripARCUnbridgedCast(Arg);
03496 
03497       InitializedEntity Entity =
03498         Param? InitializedEntity::InitializeParameter(Context, Param)
03499              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
03500                                                       Proto->isArgConsumed(i));
03501       ExprResult ArgE = PerformCopyInitialization(Entity,
03502                                                   SourceLocation(),
03503                                                   Owned(Arg),
03504                                                   /*TopLevelOfInitList=*/false,
03505                                                   AllowExplicit);
03506       if (ArgE.isInvalid())
03507         return true;
03508 
03509       Arg = ArgE.takeAs<Expr>();
03510     } else {
03511       Param = FDecl->getParamDecl(i);
03512 
03513       ExprResult ArgExpr =
03514         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
03515       if (ArgExpr.isInvalid())
03516         return true;
03517 
03518       Arg = ArgExpr.takeAs<Expr>();
03519     }
03520 
03521     // Check for array bounds violations for each argument to the call. This
03522     // check only triggers warnings when the argument isn't a more complex Expr
03523     // with its own checking, such as a BinaryOperator.
03524     CheckArrayAccess(Arg);
03525 
03526     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
03527     CheckStaticArrayArgument(CallLoc, Param, Arg);
03528 
03529     AllArgs.push_back(Arg);
03530   }
03531 
03532   // If this is a variadic call, handle args passed through "...".
03533   if (CallType != VariadicDoesNotApply) {
03534 
03535     // Assume that extern "C" functions with variadic arguments that
03536     // return __unknown_anytype aren't *really* variadic.
03537     if (Proto->getResultType() == Context.UnknownAnyTy &&
03538         FDecl && FDecl->isExternC()) {
03539       for (unsigned i = ArgIx; i != NumArgs; ++i) {
03540         ExprResult arg;
03541         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
03542           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
03543         else
03544           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
03545         Invalid |= arg.isInvalid();
03546         AllArgs.push_back(arg.take());
03547       }
03548 
03549     // Otherwise do argument promotion, (C99 6.5.2.2p7).
03550     } else {
03551       for (unsigned i = ArgIx; i != NumArgs; ++i) {
03552         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
03553                                                           FDecl);
03554         Invalid |= Arg.isInvalid();
03555         AllArgs.push_back(Arg.take());
03556       }
03557     }
03558 
03559     // Check for array bounds violations.
03560     for (unsigned i = ArgIx; i != NumArgs; ++i)
03561       CheckArrayAccess(Args[i]);
03562   }
03563   return Invalid;
03564 }
03565 
03566 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
03567   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
03568   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
03569     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
03570       << ATL->getLocalSourceRange();
03571 }
03572 
03573 /// CheckStaticArrayArgument - If the given argument corresponds to a static
03574 /// array parameter, check that it is non-null, and that if it is formed by
03575 /// array-to-pointer decay, the underlying array is sufficiently large.
03576 ///
03577 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
03578 /// array type derivation, then for each call to the function, the value of the
03579 /// corresponding actual argument shall provide access to the first element of
03580 /// an array with at least as many elements as specified by the size expression.
03581 void
03582 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
03583                                ParmVarDecl *Param,
03584                                const Expr *ArgExpr) {
03585   // Static array parameters are not supported in C++.
03586   if (!Param || getLangOpts().CPlusPlus)
03587     return;
03588 
03589   QualType OrigTy = Param->getOriginalType();
03590 
03591   const ArrayType *AT = Context.getAsArrayType(OrigTy);
03592   if (!AT || AT->getSizeModifier() != ArrayType::Static)
03593     return;
03594 
03595   if (ArgExpr->isNullPointerConstant(Context,
03596                                      Expr::NPC_NeverValueDependent)) {
03597     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
03598     DiagnoseCalleeStaticArrayParam(*this, Param);
03599     return;
03600   }
03601 
03602   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
03603   if (!CAT)
03604     return;
03605 
03606   const ConstantArrayType *ArgCAT =
03607     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
03608   if (!ArgCAT)
03609     return;
03610 
03611   if (ArgCAT->getSize().ult(CAT->getSize())) {
03612     Diag(CallLoc, diag::warn_static_array_too_small)
03613       << ArgExpr->getSourceRange()
03614       << (unsigned) ArgCAT->getSize().getZExtValue()
03615       << (unsigned) CAT->getSize().getZExtValue();
03616     DiagnoseCalleeStaticArrayParam(*this, Param);
03617   }
03618 }
03619 
03620 /// Given a function expression of unknown-any type, try to rebuild it
03621 /// to have a function type.
03622 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
03623 
03624 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
03625 /// This provides the location of the left/right parens and a list of comma
03626 /// locations.
03627 ExprResult
03628 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
03629                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
03630                     Expr *ExecConfig, bool IsExecConfig) {
03631   unsigned NumArgs = ArgExprs.size();
03632 
03633   // Since this might be a postfix expression, get rid of ParenListExprs.
03634   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
03635   if (Result.isInvalid()) return ExprError();
03636   Fn = Result.take();
03637 
03638   Expr **Args = ArgExprs.release();
03639 
03640   if (getLangOpts().CPlusPlus) {
03641     // If this is a pseudo-destructor expression, build the call immediately.
03642     if (isa<CXXPseudoDestructorExpr>(Fn)) {
03643       if (NumArgs > 0) {
03644         // Pseudo-destructor calls should not have any arguments.
03645         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
03646           << FixItHint::CreateRemoval(
03647                                     SourceRange(Args[0]->getLocStart(),
03648                                                 Args[NumArgs-1]->getLocEnd()));
03649       }
03650 
03651       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
03652                                           VK_RValue, RParenLoc));
03653     }
03654 
03655     // Determine whether this is a dependent call inside a C++ template,
03656     // in which case we won't do any semantic analysis now.
03657     // FIXME: Will need to cache the results of name lookup (including ADL) in
03658     // Fn.
03659     bool Dependent = false;
03660     if (Fn->isTypeDependent())
03661       Dependent = true;
03662     else if (Expr::hasAnyTypeDependentArguments(
03663         llvm::makeArrayRef(Args, NumArgs)))
03664       Dependent = true;
03665 
03666     if (Dependent) {
03667       if (ExecConfig) {
03668         return Owned(new (Context) CUDAKernelCallExpr(
03669             Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
03670             Context.DependentTy, VK_RValue, RParenLoc));
03671       } else {
03672         return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
03673                                             Context.DependentTy, VK_RValue,
03674                                             RParenLoc));
03675       }
03676     }
03677 
03678     // Determine whether this is a call to an object (C++ [over.call.object]).
03679     if (Fn->getType()->isRecordType())
03680       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
03681                                                 RParenLoc));
03682 
03683     if (Fn->getType() == Context.UnknownAnyTy) {
03684       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
03685       if (result.isInvalid()) return ExprError();
03686       Fn = result.take();
03687     }
03688 
03689     if (Fn->getType() == Context.BoundMemberTy) {
03690       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03691                                        RParenLoc);
03692     }
03693   }
03694 
03695   // Check for overloaded calls.  This can happen even in C due to extensions.
03696   if (Fn->getType() == Context.OverloadTy) {
03697     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
03698 
03699     // We aren't supposed to apply this logic for if there's an '&' involved.
03700     if (!find.HasFormOfMemberPointer) {
03701       OverloadExpr *ovl = find.Expression;
03702       if (isa<UnresolvedLookupExpr>(ovl)) {
03703         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
03704         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
03705                                        RParenLoc, ExecConfig);
03706       } else {
03707         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03708                                          RParenLoc);
03709       }
03710     }
03711   }
03712 
03713   // If we're directly calling a function, get the appropriate declaration.
03714   if (Fn->getType() == Context.UnknownAnyTy) {
03715     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
03716     if (result.isInvalid()) return ExprError();
03717     Fn = result.take();
03718   }
03719 
03720   Expr *NakedFn = Fn->IgnoreParens();
03721 
03722   NamedDecl *NDecl = 0;
03723   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
03724     if (UnOp->getOpcode() == UO_AddrOf)
03725       NakedFn = UnOp->getSubExpr()->IgnoreParens();
03726   
03727   if (isa<DeclRefExpr>(NakedFn))
03728     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
03729   else if (isa<MemberExpr>(NakedFn))
03730     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
03731 
03732   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
03733                                ExecConfig, IsExecConfig);
03734 }
03735 
03736 ExprResult
03737 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
03738                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
03739   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
03740   if (!ConfigDecl)
03741     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
03742                           << "cudaConfigureCall");
03743   QualType ConfigQTy = ConfigDecl->getType();
03744 
03745   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
03746       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
03747   MarkFunctionReferenced(LLLLoc, ConfigDecl);
03748 
03749   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
03750                        /*IsExecConfig=*/true);
03751 }
03752 
03753 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
03754 ///
03755 /// __builtin_astype( value, dst type )
03756 ///
03757 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
03758                                  SourceLocation BuiltinLoc,
03759                                  SourceLocation RParenLoc) {
03760   ExprValueKind VK = VK_RValue;
03761   ExprObjectKind OK = OK_Ordinary;
03762   QualType DstTy = GetTypeFromParser(ParsedDestTy);
03763   QualType SrcTy = E->getType();
03764   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
03765     return ExprError(Diag(BuiltinLoc,
03766                           diag::err_invalid_astype_of_different_size)
03767                      << DstTy
03768                      << SrcTy
03769                      << E->getSourceRange());
03770   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
03771                RParenLoc));
03772 }
03773 
03774 /// BuildResolvedCallExpr - Build a call to a resolved expression,
03775 /// i.e. an expression not of \p OverloadTy.  The expression should
03776 /// unary-convert to an expression of function-pointer or
03777 /// block-pointer type.
03778 ///
03779 /// \param NDecl the declaration being called, if available
03780 ExprResult
03781 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
03782                             SourceLocation LParenLoc,
03783                             Expr **Args, unsigned NumArgs,
03784                             SourceLocation RParenLoc,
03785                             Expr *Config, bool IsExecConfig) {
03786   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
03787 
03788   // Promote the function operand.
03789   ExprResult Result = UsualUnaryConversions(Fn);
03790   if (Result.isInvalid())
03791     return ExprError();
03792   Fn = Result.take();
03793 
03794   // Make the call expr early, before semantic checks.  This guarantees cleanup
03795   // of arguments and function on error.
03796   CallExpr *TheCall;
03797   if (Config) {
03798     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
03799                                                cast<CallExpr>(Config),
03800                                                Args, NumArgs,
03801                                                Context.BoolTy,
03802                                                VK_RValue,
03803                                                RParenLoc);
03804   } else {
03805     TheCall = new (Context) CallExpr(Context, Fn,
03806                                      Args, NumArgs,
03807                                      Context.BoolTy,
03808                                      VK_RValue,
03809                                      RParenLoc);
03810   }
03811 
03812   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
03813 
03814   // Bail out early if calling a builtin with custom typechecking.
03815   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
03816     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
03817 
03818  retry:
03819   const FunctionType *FuncT;
03820   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
03821     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
03822     // have type pointer to function".
03823     FuncT = PT->getPointeeType()->getAs<FunctionType>();
03824     if (FuncT == 0)
03825       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03826                          << Fn->getType() << Fn->getSourceRange());
03827   } else if (const BlockPointerType *BPT =
03828                Fn->getType()->getAs<BlockPointerType>()) {
03829     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
03830   } else {
03831     // Handle calls to expressions of unknown-any type.
03832     if (Fn->getType() == Context.UnknownAnyTy) {
03833       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
03834       if (rewrite.isInvalid()) return ExprError();
03835       Fn = rewrite.take();
03836       TheCall->setCallee(Fn);
03837       goto retry;
03838     }
03839 
03840     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03841       << Fn->getType() << Fn->getSourceRange());
03842   }
03843 
03844   if (getLangOpts().CUDA) {
03845     if (Config) {
03846       // CUDA: Kernel calls must be to global functions
03847       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
03848         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
03849             << FDecl->getName() << Fn->getSourceRange());
03850 
03851       // CUDA: Kernel function must have 'void' return type
03852       if (!FuncT->getResultType()->isVoidType())
03853         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
03854             << Fn->getType() << Fn->getSourceRange());
03855     } else {
03856       // CUDA: Calls to global functions must be configured
03857       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
03858         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
03859             << FDecl->getName() << Fn->getSourceRange());
03860     }
03861   }
03862 
03863   // Check for a valid return type
03864   if (CheckCallReturnType(FuncT->getResultType(),
03865                           Fn->getLocStart(), TheCall,
03866                           FDecl))
03867     return ExprError();
03868 
03869   // We know the result type of the call, set it.
03870   TheCall->setType(FuncT->getCallResultType(Context));
03871   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
03872 
03873   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
03874     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
03875                                 RParenLoc, IsExecConfig))
03876       return ExprError();
03877   } else {
03878     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
03879 
03880     if (FDecl) {
03881       // Check if we have too few/too many template arguments, based
03882       // on our knowledge of the function definition.
03883       const FunctionDecl *Def = 0;
03884       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
03885         const FunctionProtoType *Proto 
03886           = Def->getType()->getAs<FunctionProtoType>();
03887         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
03888           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
03889             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
03890       }
03891       
03892       // If the function we're calling isn't a function prototype, but we have
03893       // a function prototype from a prior declaratiom, use that prototype.
03894       if (!FDecl->hasPrototype())
03895         Proto = FDecl->getType()->getAs<FunctionProtoType>();
03896     }
03897 
03898     // Promote the arguments (C99 6.5.2.2p6).
03899     for (unsigned i = 0; i != NumArgs; i++) {
03900       Expr *Arg = Args[i];
03901 
03902       if (Proto && i < Proto->getNumArgs()) {
03903         InitializedEntity Entity
03904           = InitializedEntity::InitializeParameter(Context, 
03905                                                    Proto->getArgType(i),
03906                                                    Proto->isArgConsumed(i));
03907         ExprResult ArgE = PerformCopyInitialization(Entity,
03908                                                     SourceLocation(),
03909                                                     Owned(Arg));
03910         if (ArgE.isInvalid())
03911           return true;
03912         
03913         Arg = ArgE.takeAs<Expr>();
03914 
03915       } else {
03916         ExprResult ArgE = DefaultArgumentPromotion(Arg);
03917 
03918         if (ArgE.isInvalid())
03919           return true;
03920 
03921         Arg = ArgE.takeAs<Expr>();
03922       }
03923       
03924       if (RequireCompleteType(Arg->getLocStart(),
03925                               Arg->getType(),
03926                               diag::err_call_incomplete_argument, Arg))
03927         return ExprError();
03928 
03929       TheCall->setArg(i, Arg);
03930     }
03931   }
03932 
03933   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
03934     if (!Method->isStatic())
03935       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
03936         << Fn->getSourceRange());
03937 
03938   // Check for sentinels
03939   if (NDecl)
03940     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
03941 
03942   // Do special checking on direct calls to functions.
03943   if (FDecl) {
03944     if (CheckFunctionCall(FDecl, TheCall))
03945       return ExprError();
03946 
03947     if (BuiltinID)
03948       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
03949   } else if (NDecl) {
03950     if (CheckBlockCall(NDecl, TheCall))
03951       return ExprError();
03952   }
03953 
03954   return MaybeBindToTemporary(TheCall);
03955 }
03956 
03957 ExprResult
03958 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
03959                            SourceLocation RParenLoc, Expr *InitExpr) {
03960   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
03961   // FIXME: put back this assert when initializers are worked out.
03962   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
03963 
03964   TypeSourceInfo *TInfo;
03965   QualType literalType = GetTypeFromParser(Ty, &TInfo);
03966   if (!TInfo)
03967     TInfo = Context.getTrivialTypeSourceInfo(literalType);
03968 
03969   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
03970 }
03971 
03972 ExprResult
03973 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
03974                                SourceLocation RParenLoc, Expr *LiteralExpr) {
03975   QualType literalType = TInfo->getType();
03976 
03977   if (literalType->isArrayType()) {
03978     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
03979           diag::err_illegal_decl_array_incomplete_type,
03980           SourceRange(LParenLoc,
03981                       LiteralExpr->getSourceRange().getEnd())))
03982       return ExprError();
03983     if (literalType->isVariableArrayType())
03984       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
03985         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
03986   } else if (!literalType->isDependentType() &&
03987              RequireCompleteType(LParenLoc, literalType,
03988                diag::err_typecheck_decl_incomplete_type,
03989                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
03990     return ExprError();
03991 
03992   InitializedEntity Entity
03993     = InitializedEntity::InitializeTemporary(literalType);
03994   InitializationKind Kind
03995     = InitializationKind::CreateCStyleCast(LParenLoc, 
03996                                            SourceRange(LParenLoc, RParenLoc),
03997                                            /*InitList=*/true);
03998   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
03999   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
04000                                        MultiExprArg(*this, &LiteralExpr, 1),
04001                                             &literalType);
04002   if (Result.isInvalid())
04003     return ExprError();
04004   LiteralExpr = Result.get();
04005 
04006   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
04007   if (isFileScope) { // 6.5.2.5p3
04008     if (CheckForConstantInitializer(LiteralExpr, literalType))
04009       return ExprError();
04010   }
04011 
04012   // In C, compound literals are l-values for some reason.
04013   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
04014 
04015   return MaybeBindToTemporary(
04016            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
04017                                              VK, LiteralExpr, isFileScope));
04018 }
04019 
04020 ExprResult
04021 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
04022                     SourceLocation RBraceLoc) {
04023   unsigned NumInit = InitArgList.size();
04024   Expr **InitList = InitArgList.release();
04025 
04026   // Immediately handle non-overload placeholders.  Overloads can be
04027   // resolved contextually, but everything else here can't.
04028   for (unsigned I = 0; I != NumInit; ++I) {
04029     if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
04030       ExprResult result = CheckPlaceholderExpr(InitList[I]);
04031 
04032       // Ignore failures; dropping the entire initializer list because
04033       // of one failure would be terrible for indexing/etc.
04034       if (result.isInvalid()) continue;
04035 
04036       InitList[I] = result.take();
04037     }
04038   }
04039 
04040   // Semantic analysis for initializers is done by ActOnDeclarator() and
04041   // CheckInitializer() - it requires knowledge of the object being intialized.
04042 
04043   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
04044                                                NumInit, RBraceLoc);
04045   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
04046   return Owned(E);
04047 }
04048 
04049 /// Do an explicit extend of the given block pointer if we're in ARC.
04050 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
04051   assert(E.get()->getType()->isBlockPointerType());
04052   assert(E.get()->isRValue());
04053 
04054   // Only do this in an r-value context.
04055   if (!S.getLangOpts().ObjCAutoRefCount) return;
04056 
04057   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
04058                                CK_ARCExtendBlockObject, E.get(),
04059                                /*base path*/ 0, VK_RValue);
04060   S.ExprNeedsCleanups = true;
04061 }
04062 
04063 /// Prepare a conversion of the given expression to an ObjC object
04064 /// pointer type.
04065 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
04066   QualType type = E.get()->getType();
04067   if (type->isObjCObjectPointerType()) {
04068     return CK_BitCast;
04069   } else if (type->isBlockPointerType()) {
04070     maybeExtendBlockObject(*this, E);
04071     return CK_BlockPointerToObjCPointerCast;
04072   } else {
04073     assert(type->isPointerType());
04074     return CK_CPointerToObjCPointerCast;
04075   }
04076 }
04077 
04078 /// Prepares for a scalar cast, performing all the necessary stages
04079 /// except the final cast and returning the kind required.
04080 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
04081   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
04082   // Also, callers should have filtered out the invalid cases with
04083   // pointers.  Everything else should be possible.
04084 
04085   QualType SrcTy = Src.get()->getType();
04086   if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
04087     SrcTy = SrcAtomicTy->getValueType();
04088   if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
04089     DestTy = DestAtomicTy->getValueType();
04090 
04091   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
04092     return CK_NoOp;
04093 
04094   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
04095   case Type::STK_MemberPointer:
04096     llvm_unreachable("member pointer type in C");
04097 
04098   case Type::STK_CPointer:
04099   case Type::STK_BlockPointer:
04100   case Type::STK_ObjCObjectPointer:
04101     switch (DestTy->getScalarTypeKind()) {
04102     case Type::STK_CPointer:
04103       return CK_BitCast;
04104     case Type::STK_BlockPointer:
04105       return (SrcKind == Type::STK_BlockPointer
04106                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
04107     case Type::STK_ObjCObjectPointer:
04108       if (SrcKind == Type::STK_ObjCObjectPointer)
04109         return CK_BitCast;
04110       if (SrcKind == Type::STK_CPointer)
04111         return CK_CPointerToObjCPointerCast;
04112       maybeExtendBlockObject(*this, Src);
04113       return CK_BlockPointerToObjCPointerCast;
04114     case Type::STK_Bool:
04115       return CK_PointerToBoolean;
04116     case Type::STK_Integral:
04117       return CK_PointerToIntegral;
04118     case Type::STK_Floating:
04119     case Type::STK_FloatingComplex:
04120     case Type::STK_IntegralComplex:
04121     case Type::STK_MemberPointer:
04122       llvm_unreachable("illegal cast from pointer");
04123     }
04124     llvm_unreachable("Should have returned before this");
04125 
04126   case Type::STK_Bool: // casting from bool is like casting from an integer
04127   case Type::STK_Integral:
04128     switch (DestTy->getScalarTypeKind()) {
04129     case Type::STK_CPointer:
04130     case Type::STK_ObjCObjectPointer:
04131     case Type::STK_BlockPointer:
04132       if (Src.get()->isNullPointerConstant(Context,
04133                                            Expr::NPC_ValueDependentIsNull))
04134         return CK_NullToPointer;
04135       return CK_IntegralToPointer;
04136     case Type::STK_Bool:
04137       return CK_IntegralToBoolean;
04138     case Type::STK_Integral:
04139       return CK_IntegralCast;
04140     case Type::STK_Floating:
04141       return CK_IntegralToFloating;
04142     case Type::STK_IntegralComplex:
04143       Src = ImpCastExprToType(Src.take(),
04144                               DestTy->castAs<ComplexType>()->getElementType(),
04145                               CK_IntegralCast);
04146       return CK_IntegralRealToComplex;
04147     case Type::STK_FloatingComplex:
04148       Src = ImpCastExprToType(Src.take(),
04149                               DestTy->castAs<ComplexType>()->getElementType(),
04150                               CK_IntegralToFloating);
04151       return CK_FloatingRealToComplex;
04152     case Type::STK_MemberPointer:
04153       llvm_unreachable("member pointer type in C");
04154     }
04155     llvm_unreachable("Should have returned before this");
04156 
04157   case Type::STK_Floating:
04158     switch (DestTy->getScalarTypeKind()) {
04159     case Type::STK_Floating:
04160       return CK_FloatingCast;
04161     case Type::STK_Bool:
04162       return CK_FloatingToBoolean;
04163     case Type::STK_Integral:
04164       return CK_FloatingToIntegral;
04165     case Type::STK_FloatingComplex:
04166       Src = ImpCastExprToType(Src.take(),
04167                               DestTy->castAs<ComplexType>()->getElementType(),
04168                               CK_FloatingCast);
04169       return CK_FloatingRealToComplex;
04170     case Type::STK_IntegralComplex:
04171       Src = ImpCastExprToType(Src.take(),
04172                               DestTy->castAs<ComplexType>()->getElementType(),
04173                               CK_FloatingToIntegral);
04174       return CK_IntegralRealToComplex;
04175     case Type::STK_CPointer:
04176     case Type::STK_ObjCObjectPointer:
04177     case Type::STK_BlockPointer:
04178       llvm_unreachable("valid float->pointer cast?");
04179     case Type::STK_MemberPointer:
04180       llvm_unreachable("member pointer type in C");
04181     }
04182     llvm_unreachable("Should have returned before this");
04183 
04184   case Type::STK_FloatingComplex:
04185     switch (DestTy->getScalarTypeKind()) {
04186     case Type::STK_FloatingComplex:
04187       return CK_FloatingComplexCast;
04188     case Type::STK_IntegralComplex:
04189       return CK_FloatingComplexToIntegralComplex;
04190     case Type::STK_Floating: {
04191       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
04192       if (Context.hasSameType(ET, DestTy))
04193         return CK_FloatingComplexToReal;
04194       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
04195       return CK_FloatingCast;
04196     }
04197     case Type::STK_Bool:
04198       return CK_FloatingComplexToBoolean;
04199     case Type::STK_Integral:
04200       Src = ImpCastExprToType(Src.take(),
04201                               SrcTy->castAs<ComplexType>()->getElementType(),
04202                               CK_FloatingComplexToReal);
04203       return CK_FloatingToIntegral;
04204     case Type::STK_CPointer:
04205     case Type::STK_ObjCObjectPointer:
04206     case Type::STK_BlockPointer:
04207       llvm_unreachable("valid complex float->pointer cast?");
04208     case Type::STK_MemberPointer:
04209       llvm_unreachable("member pointer type in C");
04210     }
04211     llvm_unreachable("Should have returned before this");
04212 
04213   case Type::STK_IntegralComplex:
04214     switch (DestTy->getScalarTypeKind()) {
04215     case Type::STK_FloatingComplex:
04216       return CK_IntegralComplexToFloatingComplex;
04217     case Type::STK_IntegralComplex:
04218       return CK_IntegralComplexCast;
04219     case Type::STK_Integral: {
04220       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
04221       if (Context.hasSameType(ET, DestTy))
04222         return CK_IntegralComplexToReal;
04223       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
04224       return CK_IntegralCast;
04225     }
04226     case Type::STK_Bool:
04227       return CK_IntegralComplexToBoolean;
04228     case Type::STK_Floating:
04229       Src = ImpCastExprToType(Src.take(),
04230                               SrcTy->castAs<ComplexType>()->getElementType(),
04231                               CK_IntegralComplexToReal);
04232       return CK_IntegralToFloating;
04233     case Type::STK_CPointer:
04234     case Type::STK_ObjCObjectPointer:
04235     case Type::STK_BlockPointer:
04236       llvm_unreachable("valid complex int->pointer cast?");
04237     case Type::STK_MemberPointer:
04238       llvm_unreachable("member pointer type in C");
04239     }
04240     llvm_unreachable("Should have returned before this");
04241   }
04242 
04243   llvm_unreachable("Unhandled scalar cast");
04244 }
04245 
04246 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
04247                            CastKind &Kind) {
04248   assert(VectorTy->isVectorType() && "Not a vector type!");
04249 
04250   if (Ty->isVectorType() || Ty->isIntegerType()) {
04251     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
04252       return Diag(R.getBegin(),
04253                   Ty->isVectorType() ?
04254                   diag::err_invalid_conversion_between_vectors :
04255                   diag::err_invalid_conversion_between_vector_and_integer)
04256         << VectorTy << Ty << R;
04257   } else
04258     return Diag(R.getBegin(),
04259                 diag::err_invalid_conversion_between_vector_and_scalar)
04260       << VectorTy << Ty << R;
04261 
04262   Kind = CK_BitCast;
04263   return false;
04264 }
04265 
04266 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
04267                                     Expr *CastExpr, CastKind &Kind) {
04268   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
04269 
04270   QualType SrcTy = CastExpr->getType();
04271 
04272   // If SrcTy is a VectorType, the total size must match to explicitly cast to
04273   // an ExtVectorType.
04274   // In OpenCL, casts between vectors of different types are not allowed.
04275   // (See OpenCL 6.2).
04276   if (SrcTy->isVectorType()) {
04277     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
04278         || (getLangOpts().OpenCL &&
04279             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
04280       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
04281         << DestTy << SrcTy << R;
04282       return ExprError();
04283     }
04284     Kind = CK_BitCast;
04285     return Owned(CastExpr);
04286   }
04287 
04288   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
04289   // conversion will take place first from scalar to elt type, and then
04290   // splat from elt type to vector.
04291   if (SrcTy->isPointerType())
04292     return Diag(R.getBegin(),
04293                 diag::err_invalid_conversion_between_vector_and_scalar)
04294       << DestTy << SrcTy << R;
04295 
04296   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
04297   ExprResult CastExprRes = Owned(CastExpr);
04298   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
04299   if (CastExprRes.isInvalid())
04300     return ExprError();
04301   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
04302 
04303   Kind = CK_VectorSplat;
04304   return Owned(CastExpr);
04305 }
04306 
04307 ExprResult
04308 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
04309                     Declarator &D, ParsedType &Ty,
04310                     SourceLocation RParenLoc, Expr *CastExpr) {
04311   assert(!D.isInvalidType() && (CastExpr != 0) &&
04312          "ActOnCastExpr(): missing type or expr");
04313 
04314   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
04315   if (D.isInvalidType())
04316     return ExprError();
04317 
04318   if (getLangOpts().CPlusPlus) {
04319     // Check that there are no default arguments (C++ only).
04320     CheckExtraCXXDefaultArguments(D);
04321   }
04322 
04323   checkUnusedDeclAttributes(D);
04324 
04325   QualType castType = castTInfo->getType();
04326   Ty = CreateParsedType(castType, castTInfo);
04327 
04328   bool isVectorLiteral = false;
04329 
04330   // Check for an altivec or OpenCL literal,
04331   // i.e. all the elements are integer constants.
04332   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
04333   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
04334   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
04335        && castType->isVectorType() && (PE || PLE)) {
04336     if (PLE && PLE->getNumExprs() == 0) {
04337       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
04338       return ExprError();
04339     }
04340     if (PE || PLE->getNumExprs() == 1) {
04341       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
04342       if (!E->getType()->isVectorType())
04343         isVectorLiteral = true;
04344     }
04345     else
04346       isVectorLiteral = true;
04347   }
04348 
04349   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
04350   // then handle it as such.
04351   if (isVectorLiteral)
04352     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
04353 
04354   // If the Expr being casted is a ParenListExpr, handle it specially.
04355   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
04356   // sequence of BinOp comma operators.
04357   if (isa<ParenListExpr>(CastExpr)) {
04358     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
04359     if (Result.isInvalid()) return ExprError();
04360     CastExpr = Result.take();
04361   }
04362 
04363   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
04364 }
04365 
04366 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
04367                                     SourceLocation RParenLoc, Expr *E,
04368                                     TypeSourceInfo *TInfo) {
04369   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
04370          "Expected paren or paren list expression");
04371 
04372   Expr **exprs;
04373   unsigned numExprs;
04374   Expr *subExpr;
04375   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
04376     exprs = PE->getExprs();
04377     numExprs = PE->getNumExprs();
04378   } else {
04379     subExpr = cast<ParenExpr>(E)->getSubExpr();
04380     exprs = &subExpr;
04381     numExprs = 1;
04382   }
04383 
04384   QualType Ty = TInfo->getType();
04385   assert(Ty->isVectorType() && "Expected vector type");
04386 
04387   SmallVector<Expr *, 8> initExprs;
04388   const VectorType *VTy = Ty->getAs<VectorType>();
04389   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
04390   
04391   // '(...)' form of vector initialization in AltiVec: the number of
04392   // initializers must be one or must match the size of the vector.
04393   // If a single value is specified in the initializer then it will be
04394   // replicated to all the components of the vector
04395   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
04396     // The number of initializers must be one or must match the size of the
04397     // vector. If a single value is specified in the initializer then it will
04398     // be replicated to all the components of the vector
04399     if (numExprs == 1) {
04400       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
04401       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
04402       if (Literal.isInvalid())
04403         return ExprError();
04404       Literal = ImpCastExprToType(Literal.take(), ElemTy,
04405                                   PrepareScalarCast(Literal, ElemTy));
04406       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
04407     }
04408     else if (numExprs < numElems) {
04409       Diag(E->getExprLoc(),
04410            diag::err_incorrect_number_of_vector_initializers);
04411       return ExprError();
04412     }
04413     else
04414       initExprs.append(exprs, exprs + numExprs);
04415   }
04416   else {
04417     // For OpenCL, when the number of initializers is a single value,
04418     // it will be replicated to all components of the vector.
04419     if (getLangOpts().OpenCL &&
04420         VTy->getVectorKind() == VectorType::GenericVector &&
04421         numExprs == 1) {
04422         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
04423         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
04424         if (Literal.isInvalid())
04425           return ExprError();
04426         Literal = ImpCastExprToType(Literal.take(), ElemTy,
04427                                     PrepareScalarCast(Literal, ElemTy));
04428         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
04429     }
04430     
04431     initExprs.append(exprs, exprs + numExprs);
04432   }
04433   // FIXME: This means that pretty-printing the final AST will produce curly
04434   // braces instead of the original commas.
04435   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
04436                                                    &initExprs[0],
04437                                                    initExprs.size(), RParenLoc);
04438   initE->setType(Ty);
04439   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
04440 }
04441 
04442 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
04443 /// the ParenListExpr into a sequence of comma binary operators.
04444 ExprResult
04445 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
04446   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
04447   if (!E)
04448     return Owned(OrigExpr);
04449 
04450   ExprResult Result(E->getExpr(0));
04451 
04452   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
04453     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
04454                         E->getExpr(i));
04455 
04456   if (Result.isInvalid()) return ExprError();
04457 
04458   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
04459 }
04460 
04461 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
04462                                     SourceLocation R,
04463                                     MultiExprArg Val) {
04464   unsigned nexprs = Val.size();
04465   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
04466   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
04467   Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
04468   return Owned(expr);
04469 }
04470 
04471 /// \brief Emit a specialized diagnostic when one expression is a null pointer
04472 /// constant and the other is not a pointer.  Returns true if a diagnostic is
04473 /// emitted.
04474 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
04475                                       SourceLocation QuestionLoc) {
04476   Expr *NullExpr = LHSExpr;
04477   Expr *NonPointerExpr = RHSExpr;
04478   Expr::NullPointerConstantKind NullKind =
04479       NullExpr->isNullPointerConstant(Context,
04480                                       Expr::NPC_ValueDependentIsNotNull);
04481 
04482   if (NullKind == Expr::NPCK_NotNull) {
04483     NullExpr = RHSExpr;
04484     NonPointerExpr = LHSExpr;
04485     NullKind =
04486         NullExpr->isNullPointerConstant(Context,
04487                                         Expr::NPC_ValueDependentIsNotNull);
04488   }
04489 
04490   if (NullKind == Expr::NPCK_NotNull)
04491     return false;
04492 
04493   if (NullKind == Expr::NPCK_ZeroInteger) {
04494     // In this case, check to make sure that we got here from a "NULL"
04495     // string in the source code.
04496     NullExpr = NullExpr->IgnoreParenImpCasts();
04497     SourceLocation loc = NullExpr->getExprLoc();
04498     if (!findMacroSpelling(loc, "NULL"))
04499       return false;
04500   }
04501 
04502   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
04503   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
04504       << NonPointerExpr->getType() << DiagType
04505       << NonPointerExpr->getSourceRange();
04506   return true;
04507 }
04508 
04509 /// \brief Return false if the condition expression is valid, true otherwise.
04510 static bool checkCondition(Sema &S, Expr *Cond) {
04511   QualType CondTy = Cond->getType();
04512 
04513   // C99 6.5.15p2
04514   if (CondTy->isScalarType()) return false;
04515 
04516   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
04517   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
04518     return false;
04519 
04520   // Emit the proper error message.
04521   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
04522                               diag::err_typecheck_cond_expect_scalar :
04523                               diag::err_typecheck_cond_expect_scalar_or_vector)
04524     << CondTy;
04525   return true;
04526 }
04527 
04528 /// \brief Return false if the two expressions can be converted to a vector,
04529 /// true otherwise
04530 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
04531                                                     ExprResult &RHS,
04532                                                     QualType CondTy) {
04533   // Both operands should be of scalar type.
04534   if (!LHS.get()->getType()->isScalarType()) {
04535     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
04536       << CondTy;
04537     return true;
04538   }
04539   if (!RHS.get()->getType()->isScalarType()) {
04540     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
04541       << CondTy;
04542     return true;
04543   }
04544 
04545   // Implicity convert these scalars to the type of the condition.
04546   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
04547   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
04548   return false;
04549 }
04550 
04551 /// \brief Handle when one or both operands are void type.
04552 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
04553                                          ExprResult &RHS) {
04554     Expr *LHSExpr = LHS.get();
04555     Expr *RHSExpr = RHS.get();
04556 
04557     if (!LHSExpr->getType()->isVoidType())
04558       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
04559         << RHSExpr->getSourceRange();
04560     if (!RHSExpr->getType()->isVoidType())
04561       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
04562         << LHSExpr->getSourceRange();
04563     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
04564     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
04565     return S.Context.VoidTy;
04566 }
04567 
04568 /// \brief Return false if the NullExpr can be promoted to PointerTy,
04569 /// true otherwise.
04570 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
04571                                         QualType PointerTy) {
04572   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
04573       !NullExpr.get()->isNullPointerConstant(S.Context,
04574                                             Expr::NPC_ValueDependentIsNull))
04575     return true;
04576 
04577   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
04578   return false;
04579 }
04580 
04581 /// \brief Checks compatibility between two pointers and return the resulting
04582 /// type.
04583 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
04584                                                      ExprResult &RHS,
04585                                                      SourceLocation Loc) {
04586   QualType LHSTy = LHS.get()->getType();
04587   QualType RHSTy = RHS.get()->getType();
04588 
04589   if (S.Context.hasSameType(LHSTy, RHSTy)) {
04590     // Two identical pointers types are always compatible.
04591     return LHSTy;
04592   }
04593 
04594   QualType lhptee, rhptee;
04595 
04596   // Get the pointee types.
04597   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
04598     lhptee = LHSBTy->getPointeeType();
04599     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
04600   } else {
04601     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
04602     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
04603   }
04604 
04605   // C99 6.5.15p6: If both operands are pointers to compatible types or to
04606   // differently qualified versions of compatible types, the result type is
04607   // a pointer to an appropriately qualified version of the composite
04608   // type.
04609 
04610   // Only CVR-qualifiers exist in the standard, and the differently-qualified
04611   // clause doesn't make sense for our extensions. E.g. address space 2 should
04612   // be incompatible with address space 3: they may live on different devices or
04613   // anything.
04614   Qualifiers lhQual = lhptee.getQualifiers();
04615   Qualifiers rhQual = rhptee.getQualifiers();
04616 
04617   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
04618   lhQual.removeCVRQualifiers();
04619   rhQual.removeCVRQualifiers();
04620 
04621   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
04622   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
04623 
04624   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
04625 
04626   if (CompositeTy.isNull()) {
04627     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
04628       << LHSTy << RHSTy << LHS.get()->getSourceRange()
04629       << RHS.get()->getSourceRange();
04630     // In this situation, we assume void* type. No especially good
04631     // reason, but this is what gcc does, and we do have to pick
04632     // to get a consistent AST.
04633     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
04634     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
04635     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
04636     return incompatTy;
04637   }
04638 
04639   // The pointer types are compatible.
04640   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
04641   ResultTy = S.Context.getPointerType(ResultTy);
04642 
04643   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
04644   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
04645   return ResultTy;
04646 }
04647 
04648 /// \brief Return the resulting type when the operands are both block pointers.
04649 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
04650                                                           ExprResult &LHS,
04651                                                           ExprResult &RHS,
04652                                                           SourceLocation Loc) {
04653   QualType LHSTy = LHS.get()->getType();
04654   QualType RHSTy = RHS.get()->getType();
04655 
04656   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
04657     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
04658       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
04659       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
04660       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
04661       return destType;
04662     }
04663     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
04664       << LHSTy << RHSTy << LHS.get()->getSourceRange()
04665       << RHS.get()->getSourceRange();
04666     return QualType();
04667   }
04668 
04669   // We have 2 block pointer types.
04670   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
04671 }
04672 
04673 /// \brief Return the resulting type when the operands are both pointers.
04674 static QualType
04675 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
04676                                             ExprResult &RHS,
04677                                             SourceLocation Loc) {
04678   // get the pointer types
04679   QualType LHSTy = LHS.get()->getType();
04680   QualType RHSTy = RHS.get()->getType();
04681 
04682   // get the "pointed to" types
04683   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04684   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04685 
04686   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
04687   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
04688     // Figure out necessary qualifiers (C99 6.5.15p6)
04689     QualType destPointee
04690       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04691     QualType destType = S.Context.getPointerType(destPointee);
04692     // Add qualifiers if necessary.
04693     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
04694     // Promote to void*.
04695     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
04696     return destType;
04697   }
04698   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
04699     QualType destPointee
04700       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04701     QualType destType = S.Context.getPointerType(destPointee);
04702     // Add qualifiers if necessary.
04703     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
04704     // Promote to void*.
04705     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
04706     return destType;
04707   }
04708 
04709   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
04710 }
04711 
04712 /// \brief Return false if the first expression is not an integer and the second
04713 /// expression is not a pointer, true otherwise.
04714 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
04715                                         Expr* PointerExpr, SourceLocation Loc,
04716                                         bool IsIntFirstExpr) {
04717   if (!PointerExpr->getType()->isPointerType() ||
04718       !Int.get()->getType()->isIntegerType())
04719     return false;
04720 
04721   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
04722   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
04723 
04724   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
04725     << Expr1->getType() << Expr2->getType()
04726     << Expr1->getSourceRange() << Expr2->getSourceRange();
04727   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
04728                             CK_IntegralToPointer);
04729   return true;
04730 }
04731 
04732 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
04733 /// In that case, LHS = cond.
04734 /// C99 6.5.15
04735 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
04736                                         ExprResult &RHS, ExprValueKind &VK,
04737                                         ExprObjectKind &OK,
04738                                         SourceLocation QuestionLoc) {
04739 
04740   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
04741   if (!LHSResult.isUsable()) return QualType();
04742   LHS = move(LHSResult);
04743 
04744   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
04745   if (!RHSResult.isUsable()) return QualType();
04746   RHS = move(RHSResult);
04747 
04748   // C++ is sufficiently different to merit its own checker.
04749   if (getLangOpts().CPlusPlus)
04750     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
04751 
04752   VK = VK_RValue;
04753   OK = OK_Ordinary;
04754 
04755   Cond = UsualUnaryConversions(Cond.take());
04756   if (Cond.isInvalid())
04757     return QualType();
04758   LHS = UsualUnaryConversions(LHS.take());
04759   if (LHS.isInvalid())
04760     return QualType();
04761   RHS = UsualUnaryConversions(RHS.take());
04762   if (RHS.isInvalid())
04763     return QualType();
04764 
04765   QualType CondTy = Cond.get()->getType();
04766   QualType LHSTy = LHS.get()->getType();
04767   QualType RHSTy = RHS.get()->getType();
04768 
04769   // first, check the condition.
04770   if (checkCondition(*this, Cond.get()))
04771     return QualType();
04772 
04773   // Now check the two expressions.
04774   if (LHSTy->isVectorType() || RHSTy->isVectorType())
04775     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
04776 
04777   // OpenCL: If the condition is a vector, and both operands are scalar,
04778   // attempt to implicity convert them to the vector type to act like the
04779   // built in select.
04780   if (getLangOpts().OpenCL && CondTy->isVectorType())
04781     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
04782       return QualType();
04783   
04784   // If both operands have arithmetic type, do the usual arithmetic conversions
04785   // to find a common type: C99 6.5.15p3,5.
04786   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
04787     UsualArithmeticConversions(LHS, RHS);
04788     if (LHS.isInvalid() || RHS.isInvalid())
04789       return QualType();
04790     return LHS.get()->getType();
04791   }
04792 
04793   // If both operands are the same structure or union type, the result is that
04794   // type.
04795   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
04796     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
04797       if (LHSRT->getDecl() == RHSRT->getDecl())
04798         // "If both the operands have structure or union type, the result has
04799         // that type."  This implies that CV qualifiers are dropped.
04800         return LHSTy.getUnqualifiedType();
04801     // FIXME: Type of conditional expression must be complete in C mode.
04802   }
04803 
04804   // C99 6.5.15p5: "If both operands have void type, the result has void type."
04805   // The following || allows only one side to be void (a GCC-ism).
04806   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
04807     return checkConditionalVoidType(*this, LHS, RHS);
04808   }
04809 
04810   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
04811   // the type of the other operand."
04812   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
04813   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
04814 
04815   // All objective-c pointer type analysis is done here.
04816   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
04817                                                         QuestionLoc);
04818   if (LHS.isInvalid() || RHS.isInvalid())
04819     return QualType();
04820   if (!compositeType.isNull())
04821     return compositeType;
04822 
04823 
04824   // Handle block pointer types.
04825   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
04826     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
04827                                                      QuestionLoc);
04828 
04829   // Check constraints for C object pointers types (C99 6.5.15p3,6).
04830   if (LHSTy->isPointerType() && RHSTy->isPointerType())
04831     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
04832                                                        QuestionLoc);
04833 
04834   // GCC compatibility: soften pointer/integer mismatch.  Note that
04835   // null pointers have been filtered out by this point.
04836   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
04837       /*isIntFirstExpr=*/true))
04838     return RHSTy;
04839   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
04840       /*isIntFirstExpr=*/false))
04841     return LHSTy;
04842 
04843   // Emit a better diagnostic if one of the expressions is a null pointer
04844   // constant and the other is not a pointer type. In this case, the user most
04845   // likely forgot to take the address of the other expression.
04846   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
04847     return QualType();
04848 
04849   // Otherwise, the operands are not compatible.
04850   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04851     << LHSTy << RHSTy << LHS.get()->getSourceRange()
04852     << RHS.get()->getSourceRange();
04853   return QualType();
04854 }
04855 
04856 /// FindCompositeObjCPointerType - Helper method to find composite type of
04857 /// two objective-c pointer types of the two input expressions.
04858 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
04859                                             SourceLocation QuestionLoc) {
04860   QualType LHSTy = LHS.get()->getType();
04861   QualType RHSTy = RHS.get()->getType();
04862 
04863   // Handle things like Class and struct objc_class*.  Here we case the result
04864   // to the pseudo-builtin, because that will be implicitly cast back to the
04865   // redefinition type if an attempt is made to access its fields.
04866   if (LHSTy->isObjCClassType() &&
04867       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
04868     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
04869     return LHSTy;
04870   }
04871   if (RHSTy->isObjCClassType() &&
04872       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
04873     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
04874     return RHSTy;
04875   }
04876   // And the same for struct objc_object* / id
04877   if (LHSTy->isObjCIdType() &&
04878       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
04879     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
04880     return LHSTy;
04881   }
04882   if (RHSTy->isObjCIdType() &&
04883       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
04884     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
04885     return RHSTy;
04886   }
04887   // And the same for struct objc_selector* / SEL
04888   if (Context.isObjCSelType(LHSTy) &&
04889       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
04890     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
04891     return LHSTy;
04892   }
04893   if (Context.isObjCSelType(RHSTy) &&
04894       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
04895     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
04896     return RHSTy;
04897   }
04898   // Check constraints for Objective-C object pointers types.
04899   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
04900 
04901     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04902       // Two identical object pointer types are always compatible.
04903       return LHSTy;
04904     }
04905     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
04906     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
04907     QualType compositeType = LHSTy;
04908 
04909     // If both operands are interfaces and either operand can be
04910     // assigned to the other, use that type as the composite
04911     // type. This allows
04912     //   xxx ? (A*) a : (B*) b
04913     // where B is a subclass of A.
04914     //
04915     // Additionally, as for assignment, if either type is 'id'
04916     // allow silent coercion. Finally, if the types are
04917     // incompatible then make sure to use 'id' as the composite
04918     // type so the result is acceptable for sending messages to.
04919 
04920     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
04921     // It could return the composite type.
04922     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
04923       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
04924     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
04925       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
04926     } else if ((LHSTy->isObjCQualifiedIdType() ||
04927                 RHSTy->isObjCQualifiedIdType()) &&
04928                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
04929       // Need to handle "id<xx>" explicitly.
04930       // GCC allows qualified id and any Objective-C type to devolve to
04931       // id. Currently localizing to here until clear this should be
04932       // part of ObjCQualifiedIdTypesAreCompatible.
04933       compositeType = Context.getObjCIdType();
04934     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
04935       compositeType = Context.getObjCIdType();
04936     } else if (!(compositeType =
04937                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
04938       ;
04939     else {
04940       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
04941       << LHSTy << RHSTy
04942       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04943       QualType incompatTy = Context.getObjCIdType();
04944       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
04945       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
04946       return incompatTy;
04947     }
04948     // The object pointer types are compatible.
04949     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
04950     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
04951     return compositeType;
04952   }
04953   // Check Objective-C object pointer types and 'void *'
04954   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
04955     if (getLangOpts().ObjCAutoRefCount) {
04956       // ARC forbids the implicit conversion of object pointers to 'void *',
04957       // so these types are not compatible.
04958       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
04959           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04960       LHS = RHS = true;
04961       return QualType();
04962     }
04963     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04964     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04965     QualType destPointee
04966     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04967     QualType destType = Context.getPointerType(destPointee);
04968     // Add qualifiers if necessary.
04969     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
04970     // Promote to void*.
04971     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
04972     return destType;
04973   }
04974   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
04975     if (getLangOpts().ObjCAutoRefCount) {
04976       // ARC forbids the implicit conversion of object pointers to 'void *',
04977       // so these types are not compatible.
04978       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
04979           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04980       LHS = RHS = true;
04981       return QualType();
04982     }
04983     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04984     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04985     QualType destPointee
04986     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04987     QualType destType = Context.getPointerType(destPointee);
04988     // Add qualifiers if necessary.
04989     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
04990     // Promote to void*.
04991     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
04992     return destType;
04993   }
04994   return QualType();
04995 }
04996 
04997 /// SuggestParentheses - Emit a note with a fixit hint that wraps
04998 /// ParenRange in parentheses.
04999 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
05000                                const PartialDiagnostic &Note,
05001                                SourceRange ParenRange) {
05002   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
05003   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
05004       EndLoc.isValid()) {
05005     Self.Diag(Loc, Note)
05006       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
05007       << FixItHint::CreateInsertion(EndLoc, ")");
05008   } else {
05009     // We can't display the parentheses, so just show the bare note.
05010     Self.Diag(Loc, Note) << ParenRange;
05011   }
05012 }
05013 
05014 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
05015   return Opc >= BO_Mul && Opc <= BO_Shr;
05016 }
05017 
05018 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
05019 /// expression, either using a built-in or overloaded operator,
05020 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
05021 /// expression.
05022 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
05023                                    Expr **RHSExprs) {
05024   // Don't strip parenthesis: we should not warn if E is in parenthesis.
05025   E = E->IgnoreImpCasts();
05026   E = E->IgnoreConversionOperator();
05027   E = E->IgnoreImpCasts();
05028 
05029   // Built-in binary operator.
05030   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
05031     if (IsArithmeticOp(OP->getOpcode())) {
05032       *Opcode = OP->getOpcode();
05033       *RHSExprs = OP->getRHS();
05034       return true;
05035     }
05036   }
05037 
05038   // Overloaded operator.
05039   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
05040     if (Call->getNumArgs() != 2)
05041       return false;
05042 
05043     // Make sure this is really a binary operator that is safe to pass into
05044     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
05045     OverloadedOperatorKind OO = Call->getOperator();
05046     if (OO < OO_Plus || OO > OO_Arrow)
05047       return false;
05048 
05049     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
05050     if (IsArithmeticOp(OpKind)) {
05051       *Opcode = OpKind;
05052       *RHSExprs = Call->getArg(1);
05053       return true;
05054     }
05055   }
05056 
05057   return false;
05058 }
05059 
05060 static bool IsLogicOp(BinaryOperatorKind Opc) {
05061   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
05062 }
05063 
05064 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
05065 /// or is a logical expression such as (x==y) which has int type, but is
05066 /// commonly interpreted as boolean.
05067 static bool ExprLooksBoolean(Expr *E) {
05068   E = E->IgnoreParenImpCasts();
05069 
05070   if (E->getType()->isBooleanType())
05071     return true;
05072   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
05073     return IsLogicOp(OP->getOpcode());
05074   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
05075     return OP->getOpcode() == UO_LNot;
05076 
05077   return false;
05078 }
05079 
05080 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
05081 /// and binary operator are mixed in a way that suggests the programmer assumed
05082 /// the conditional operator has higher precedence, for example:
05083 /// "int x = a + someBinaryCondition ? 1 : 2".
05084 static void DiagnoseConditionalPrecedence(Sema &Self,
05085                                           SourceLocation OpLoc,
05086                                           Expr *Condition,
05087                                           Expr *LHSExpr,
05088                                           Expr *RHSExpr) {
05089   BinaryOperatorKind CondOpcode;
05090   Expr *CondRHS;
05091 
05092   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
05093     return;
05094   if (!ExprLooksBoolean(CondRHS))
05095     return;
05096 
05097   // The condition is an arithmetic binary expression, with a right-
05098   // hand side that looks boolean, so warn.
05099 
05100   Self.Diag(OpLoc, diag::warn_precedence_conditional)
05101       << Condition->getSourceRange()
05102       << BinaryOperator::getOpcodeStr(CondOpcode);
05103 
05104   SuggestParentheses(Self, OpLoc,
05105     Self.PDiag(diag::note_precedence_conditional_silence)
05106       << BinaryOperator::getOpcodeStr(CondOpcode),
05107     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
05108 
05109   SuggestParentheses(Self, OpLoc,
05110     Self.PDiag(diag::note_precedence_conditional_first),
05111     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
05112 }
05113 
05114 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
05115 /// in the case of a the GNU conditional expr extension.
05116 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
05117                                     SourceLocation ColonLoc,
05118                                     Expr *CondExpr, Expr *LHSExpr,
05119                                     Expr *RHSExpr) {
05120   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
05121   // was the condition.
05122   OpaqueValueExpr *opaqueValue = 0;
05123   Expr *commonExpr = 0;
05124   if (LHSExpr == 0) {
05125     commonExpr = CondExpr;
05126 
05127     // We usually want to apply unary conversions *before* saving, except
05128     // in the special case of a C++ l-value conditional.
05129     if (!(getLangOpts().CPlusPlus
05130           && !commonExpr->isTypeDependent()
05131           && commonExpr->getValueKind() == RHSExpr->getValueKind()
05132           && commonExpr->isGLValue()
05133           && commonExpr->isOrdinaryOrBitFieldObject()
05134           && RHSExpr->isOrdinaryOrBitFieldObject()
05135           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
05136       ExprResult commonRes = UsualUnaryConversions(commonExpr);
05137       if (commonRes.isInvalid())
05138         return ExprError();
05139       commonExpr = commonRes.take();
05140     }
05141 
05142     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
05143                                                 commonExpr->getType(),
05144                                                 commonExpr->getValueKind(),
05145                                                 commonExpr->getObjectKind(),
05146                                                 commonExpr);
05147     LHSExpr = CondExpr = opaqueValue;
05148   }
05149 
05150   ExprValueKind VK = VK_RValue;
05151   ExprObjectKind OK = OK_Ordinary;
05152   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
05153   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
05154                                              VK, OK, QuestionLoc);
05155   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
05156       RHS.isInvalid())
05157     return ExprError();
05158 
05159   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
05160                                 RHS.get());
05161 
05162   if (!commonExpr)
05163     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
05164                                                    LHS.take(), ColonLoc, 
05165                                                    RHS.take(), result, VK, OK));
05166 
05167   return Owned(new (Context)
05168     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
05169                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
05170                               OK));
05171 }
05172 
05173 // checkPointerTypesForAssignment - This is a very tricky routine (despite
05174 // being closely modeled after the C99 spec:-). The odd characteristic of this
05175 // routine is it effectively iqnores the qualifiers on the top level pointee.
05176 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
05177 // FIXME: add a couple examples in this comment.
05178 static Sema::AssignConvertType
05179 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
05180   assert(LHSType.isCanonical() && "LHS not canonicalized!");
05181   assert(RHSType.isCanonical() && "RHS not canonicalized!");
05182 
05183   // get the "pointed to" type (ignoring qualifiers at the top level)
05184   const Type *lhptee, *rhptee;
05185   Qualifiers lhq, rhq;
05186   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
05187   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
05188 
05189   Sema::AssignConvertType ConvTy = Sema::Compatible;
05190 
05191   // C99 6.5.16.1p1: This following citation is common to constraints
05192   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
05193   // qualifiers of the type *pointed to* by the right;
05194   Qualifiers lq;
05195 
05196   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
05197   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
05198       lhq.compatiblyIncludesObjCLifetime(rhq)) {
05199     // Ignore lifetime for further calculation.
05200     lhq.removeObjCLifetime();
05201     rhq.removeObjCLifetime();
05202   }
05203 
05204   if (!lhq.compatiblyIncludes(rhq)) {
05205     // Treat address-space mismatches as fatal.  TODO: address subspaces
05206     if (lhq.getAddressSpace() != rhq.getAddressSpace())
05207       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
05208 
05209     // It's okay to add or remove GC or lifetime qualifiers when converting to
05210     // and from void*.
05211     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
05212                         .compatiblyIncludes(
05213                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
05214              && (lhptee->isVoidType() || rhptee->isVoidType()))
05215       ; // keep old
05216 
05217     // Treat lifetime mismatches as fatal.
05218     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
05219       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
05220     
05221     // For GCC compatibility, other qualifier mismatches are treated
05222     // as still compatible in C.
05223     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
05224   }
05225 
05226   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
05227   // incomplete type and the other is a pointer to a qualified or unqualified
05228   // version of void...
05229   if (lhptee->isVoidType()) {
05230     if (rhptee->isIncompleteOrObjectType())
05231       return ConvTy;
05232 
05233     // As an extension, we allow cast to/from void* to function pointer.
05234     assert(rhptee->isFunctionType());
05235     return Sema::FunctionVoidPointer;
05236   }
05237 
05238   if (rhptee->isVoidType()) {
05239     if (lhptee->isIncompleteOrObjectType())
05240       return ConvTy;
05241 
05242     // As an extension, we allow cast to/from void* to function pointer.
05243     assert(lhptee->isFunctionType());
05244     return Sema::FunctionVoidPointer;
05245   }
05246 
05247   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
05248   // unqualified versions of compatible types, ...
05249   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
05250   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
05251     // Check if the pointee types are compatible ignoring the sign.
05252     // We explicitly check for char so that we catch "char" vs
05253     // "unsigned char" on systems where "char" is unsigned.
05254     if (lhptee->isCharType())
05255       ltrans = S.Context.UnsignedCharTy;
05256     else if (lhptee->hasSignedIntegerRepresentation())
05257       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
05258 
05259     if (rhptee->isCharType())
05260       rtrans = S.Context.UnsignedCharTy;
05261     else if (rhptee->hasSignedIntegerRepresentation())
05262       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
05263 
05264     if (ltrans == rtrans) {
05265       // Types are compatible ignoring the sign. Qualifier incompatibility
05266       // takes priority over sign incompatibility because the sign
05267       // warning can be disabled.
05268       if (ConvTy != Sema::Compatible)
05269         return ConvTy;
05270 
05271       return Sema::IncompatiblePointerSign;
05272     }
05273 
05274     // If we are a multi-level pointer, it's possible that our issue is simply
05275     // one of qualification - e.g. char ** -> const char ** is not allowed. If
05276     // the eventual target type is the same and the pointers have the same
05277     // level of indirection, this must be the issue.
05278     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
05279       do {
05280         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
05281         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
05282       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
05283 
05284       if (lhptee == rhptee)
05285         return Sema::IncompatibleNestedPointerQualifiers;
05286     }
05287 
05288     // General pointer incompatibility takes priority over qualifiers.
05289     return Sema::IncompatiblePointer;
05290   }
05291   if (!S.getLangOpts().CPlusPlus &&
05292       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
05293     return Sema::IncompatiblePointer;
05294   return ConvTy;
05295 }
05296 
05297 /// checkBlockPointerTypesForAssignment - This routine determines whether two
05298 /// block pointer types are compatible or whether a block and normal pointer
05299 /// are compatible. It is more restrict than comparing two function pointer
05300 // types.
05301 static Sema::AssignConvertType
05302 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
05303                                     QualType RHSType) {
05304   assert(LHSType.isCanonical() && "LHS not canonicalized!");
05305   assert(RHSType.isCanonical() && "RHS not canonicalized!");
05306 
05307   QualType lhptee, rhptee;
05308 
05309   // get the "pointed to" type (ignoring qualifiers at the top level)
05310   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
05311   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
05312 
05313   // In C++, the types have to match exactly.
05314   if (S.getLangOpts().CPlusPlus)
05315     return Sema::IncompatibleBlockPointer;
05316 
05317   Sema::AssignConvertType ConvTy = Sema::Compatible;
05318 
05319   // For blocks we enforce that qualifiers are identical.
05320   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
05321     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
05322 
05323   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
05324     return Sema::IncompatibleBlockPointer;
05325 
05326   return ConvTy;
05327 }
05328 
05329 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
05330 /// for assignment compatibility.
05331 static Sema::AssignConvertType
05332 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
05333                                    QualType RHSType) {
05334   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
05335   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
05336 
05337   if (LHSType->isObjCBuiltinType()) {
05338     // Class is not compatible with ObjC object pointers.
05339     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
05340         !RHSType->isObjCQualifiedClassType())
05341       return Sema::IncompatiblePointer;
05342     return Sema::Compatible;
05343   }
05344   if (RHSType->isObjCBuiltinType()) {
05345     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
05346         !LHSType->isObjCQualifiedClassType())
05347       return Sema::IncompatiblePointer;
05348     return Sema::Compatible;
05349   }
05350   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
05351   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
05352 
05353   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
05354       // make an exception for id<P>
05355       !LHSType->isObjCQualifiedIdType())
05356     return Sema::CompatiblePointerDiscardsQualifiers;
05357 
05358   if (S.Context.typesAreCompatible(LHSType, RHSType))
05359     return Sema::Compatible;
05360   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
05361     return Sema::IncompatibleObjCQualifiedId;
05362   return Sema::IncompatiblePointer;
05363 }
05364 
05365 Sema::AssignConvertType
05366 Sema::CheckAssignmentConstraints(SourceLocation Loc,
05367                                  QualType LHSType, QualType RHSType) {
05368   // Fake up an opaque expression.  We don't actually care about what
05369   // cast operations are required, so if CheckAssignmentConstraints
05370   // adds casts to this they'll be wasted, but fortunately that doesn't
05371   // usually happen on valid code.
05372   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
05373   ExprResult RHSPtr = &RHSExpr;
05374   CastKind K = CK_Invalid;
05375 
05376   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
05377 }
05378 
05379 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
05380 /// has code to accommodate several GCC extensions when type checking
05381 /// pointers. Here are some objectionable examples that GCC considers warnings:
05382 ///
05383 ///  int a, *pint;
05384 ///  short *pshort;
05385 ///  struct foo *pfoo;
05386 ///
05387 ///  pint = pshort; // warning: assignment from incompatible pointer type
05388 ///  a = pint; // warning: assignment makes integer from pointer without a cast
05389 ///  pint = a; // warning: assignment makes pointer from integer without a cast
05390 ///  pint = pfoo; // warning: assignment from incompatible pointer type
05391 ///
05392 /// As a result, the code for dealing with pointers is more complex than the
05393 /// C99 spec dictates.
05394 ///
05395 /// Sets 'Kind' for any result kind except Incompatible.
05396 Sema::AssignConvertType
05397 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
05398                                  CastKind &Kind) {
05399   QualType RHSType = RHS.get()->getType();
05400   QualType OrigLHSType = LHSType;
05401 
05402   // Get canonical types.  We're not formatting these types, just comparing
05403   // them.
05404   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
05405   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
05406 
05407 
05408   // Common case: no conversion required.
05409   if (LHSType == RHSType) {
05410     Kind = CK_NoOp;
05411     return Compatible;
05412   }
05413 
05414   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
05415     if (AtomicTy->getValueType() == RHSType) {
05416       Kind = CK_NonAtomicToAtomic;
05417       return Compatible;
05418     }
05419   }
05420 
05421   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
05422     if (AtomicTy->getValueType() == LHSType) {
05423       Kind = CK_AtomicToNonAtomic;
05424       return Compatible;
05425     }
05426   }
05427 
05428 
05429   // If the left-hand side is a reference type, then we are in a
05430   // (rare!) case where we've allowed the use of references in C,
05431   // e.g., as a parameter type in a built-in function. In this case,
05432   // just make sure that the type referenced is compatible with the
05433   // right-hand side type. The caller is responsible for adjusting
05434   // LHSType so that the resulting expression does not have reference
05435   // type.
05436   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
05437     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
05438       Kind = CK_LValueBitCast;
05439       return Compatible;
05440     }
05441     return Incompatible;
05442   }
05443 
05444   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
05445   // to the same ExtVector type.
05446   if (LHSType->isExtVectorType()) {
05447     if (RHSType->isExtVectorType())
05448       return Incompatible;
05449     if (RHSType->isArithmeticType()) {
05450       // CK_VectorSplat does T -> vector T, so first cast to the
05451       // element type.
05452       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
05453       if (elType != RHSType) {
05454         Kind = PrepareScalarCast(RHS, elType);
05455         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
05456       }
05457       Kind = CK_VectorSplat;
05458       return Compatible;
05459     }
05460   }
05461 
05462   // Conversions to or from vector type.
05463   if (LHSType->isVectorType() || RHSType->isVectorType()) {
05464     if (LHSType->isVectorType() && RHSType->isVectorType()) {
05465       // Allow assignments of an AltiVec vector type to an equivalent GCC
05466       // vector type and vice versa
05467       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
05468         Kind = CK_BitCast;
05469         return Compatible;
05470       }
05471 
05472       // If we are allowing lax vector conversions, and LHS and RHS are both
05473       // vectors, the total size only needs to be the same. This is a bitcast;
05474       // no bits are changed but the result type is different.
05475       if (getLangOpts().LaxVectorConversions &&
05476           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
05477         Kind = CK_BitCast;
05478         return IncompatibleVectors;
05479       }
05480     }
05481     return Incompatible;
05482   }
05483 
05484   // Arithmetic conversions.
05485   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
05486       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
05487     Kind = PrepareScalarCast(RHS, LHSType);
05488     return Compatible;
05489   }
05490 
05491   // Conversions to normal pointers.
05492   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
05493     // U* -> T*
05494     if (isa<PointerType>(RHSType)) {
05495       Kind = CK_BitCast;
05496       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
05497     }
05498 
05499     // int -> T*
05500     if (RHSType->isIntegerType()) {
05501       Kind = CK_IntegralToPointer; // FIXME: null?
05502       return IntToPointer;
05503     }
05504 
05505     // C pointers are not compatible with ObjC object pointers,
05506     // with two exceptions:
05507     if (isa<ObjCObjectPointerType>(RHSType)) {
05508       //  - conversions to void*
05509       if (LHSPointer->getPointeeType()->isVoidType()) {
05510         Kind = CK_BitCast;
05511         return Compatible;
05512       }
05513 
05514       //  - conversions from 'Class' to the redefinition type
05515       if (RHSType->isObjCClassType() &&
05516           Context.hasSameType(LHSType, 
05517                               Context.getObjCClassRedefinitionType())) {
05518         Kind = CK_BitCast;
05519         return Compatible;
05520       }
05521 
05522       Kind = CK_BitCast;
05523       return IncompatiblePointer;
05524     }
05525 
05526     // U^ -> void*
05527     if (RHSType->getAs<BlockPointerType>()) {
05528       if (LHSPointer->getPointeeType()->isVoidType()) {
05529         Kind = CK_BitCast;
05530         return Compatible;
05531       }
05532     }
05533 
05534     return Incompatible;
05535   }
05536 
05537   // Conversions to block pointers.
05538   if (isa<BlockPointerType>(LHSType)) {
05539     // U^ -> T^
05540     if (RHSType->isBlockPointerType()) {
05541       Kind = CK_BitCast;
05542       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
05543     }
05544 
05545     // int or null -> T^
05546     if (RHSType->isIntegerType()) {
05547       Kind = CK_IntegralToPointer; // FIXME: null
05548       return IntToBlockPointer;
05549     }
05550 
05551     // id -> T^
05552     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
05553       Kind = CK_AnyPointerToBlockPointerCast;
05554       return Compatible;
05555     }
05556 
05557     // void* -> T^
05558     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
05559       if (RHSPT->getPointeeType()->isVoidType()) {
05560         Kind = CK_AnyPointerToBlockPointerCast;
05561         return Compatible;
05562       }
05563 
05564     return Incompatible;
05565   }
05566 
05567   // Conversions to Objective-C pointers.
05568   if (isa<ObjCObjectPointerType>(LHSType)) {
05569     // A* -> B*
05570     if (RHSType->isObjCObjectPointerType()) {
05571       Kind = CK_BitCast;
05572       Sema::AssignConvertType result = 
05573         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
05574       if (getLangOpts().ObjCAutoRefCount &&
05575           result == Compatible && 
05576           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
05577         result = IncompatibleObjCWeakRef;
05578       return result;
05579     }
05580 
05581     // int or null -> A*
05582     if (RHSType->isIntegerType()) {
05583       Kind = CK_IntegralToPointer; // FIXME: null
05584       return IntToPointer;
05585     }
05586 
05587     // In general, C pointers are not compatible with ObjC object pointers,
05588     // with two exceptions:
05589     if (isa<PointerType>(RHSType)) {
05590       Kind = CK_CPointerToObjCPointerCast;
05591 
05592       //  - conversions from 'void*'
05593       if (RHSType->isVoidPointerType()) {
05594         return Compatible;
05595       }
05596 
05597       //  - conversions to 'Class' from its redefinition type
05598       if (LHSType->isObjCClassType() &&
05599           Context.hasSameType(RHSType, 
05600                               Context.getObjCClassRedefinitionType())) {
05601         return Compatible;
05602       }
05603 
05604       return IncompatiblePointer;
05605     }
05606 
05607     // T^ -> A*
05608     if (RHSType->isBlockPointerType()) {
05609       maybeExtendBlockObject(*this, RHS);
05610       Kind = CK_BlockPointerToObjCPointerCast;
05611       return Compatible;
05612     }
05613 
05614     return Incompatible;
05615   }
05616 
05617   // Conversions from pointers that are not covered by the above.
05618   if (isa<PointerType>(RHSType)) {
05619     // T* -> _Bool
05620     if (LHSType == Context.BoolTy) {
05621       Kind = CK_PointerToBoolean;
05622       return Compatible;
05623     }
05624 
05625     // T* -> int
05626     if (LHSType->isIntegerType()) {
05627       Kind = CK_PointerToIntegral;
05628       return PointerToInt;
05629     }
05630 
05631     return Incompatible;
05632   }
05633 
05634   // Conversions from Objective-C pointers that are not covered by the above.
05635   if (isa<ObjCObjectPointerType>(RHSType)) {
05636     // T* -> _Bool
05637     if (LHSType == Context.BoolTy) {
05638       Kind = CK_PointerToBoolean;
05639       return Compatible;
05640     }
05641 
05642     // T* -> int
05643     if (LHSType->isIntegerType()) {
05644       Kind = CK_PointerToIntegral;
05645       return PointerToInt;
05646     }
05647 
05648     return Incompatible;
05649   }
05650 
05651   // struct A -> struct B
05652   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
05653     if (Context.typesAreCompatible(LHSType, RHSType)) {
05654       Kind = CK_NoOp;
05655       return Compatible;
05656     }
05657   }
05658 
05659   return Incompatible;
05660 }
05661 
05662 /// \brief Constructs a transparent union from an expression that is
05663 /// used to initialize the transparent union.
05664 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
05665                                       ExprResult &EResult, QualType UnionType,
05666                                       FieldDecl *Field) {
05667   // Build an initializer list that designates the appropriate member
05668   // of the transparent union.
05669   Expr *E = EResult.take();
05670   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
05671                                                    &E, 1,
05672                                                    SourceLocation());
05673   Initializer->setType(UnionType);
05674   Initializer->setInitializedFieldInUnion(Field);
05675 
05676   // Build a compound literal constructing a value of the transparent
05677   // union type from this initializer list.
05678   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
05679   EResult = S.Owned(
05680     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
05681                                 VK_RValue, Initializer, false));
05682 }
05683 
05684 Sema::AssignConvertType
05685 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
05686                                                ExprResult &RHS) {
05687   QualType RHSType = RHS.get()->getType();
05688 
05689   // If the ArgType is a Union type, we want to handle a potential
05690   // transparent_union GCC extension.
05691   const RecordType *UT = ArgType->getAsUnionType();
05692   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
05693     return Incompatible;
05694 
05695   // The field to initialize within the transparent union.
05696   RecordDecl *UD = UT->getDecl();
05697   FieldDecl *InitField = 0;
05698   // It's compatible if the expression matches any of the fields.
05699   for (RecordDecl::field_iterator it = UD->field_begin(),
05700          itend = UD->field_end();
05701        it != itend; ++it) {
05702     if (it->getType()->isPointerType()) {
05703       // If the transparent union contains a pointer type, we allow:
05704       // 1) void pointer
05705       // 2) null pointer constant
05706       if (RHSType->isPointerType())
05707         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
05708           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
05709           InitField = &*it;
05710           break;
05711         }
05712 
05713       if (RHS.get()->isNullPointerConstant(Context,
05714                                            Expr::NPC_ValueDependentIsNull)) {
05715         RHS = ImpCastExprToType(RHS.take(), it->getType(),
05716                                 CK_NullToPointer);
05717         InitField = &*it;
05718         break;
05719       }
05720     }
05721 
05722     CastKind Kind = CK_Invalid;
05723     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
05724           == Compatible) {
05725       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
05726       InitField = &*it;
05727       break;
05728     }
05729   }
05730 
05731   if (!InitField)
05732     return Incompatible;
05733 
05734   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
05735   return Compatible;
05736 }
05737 
05738 Sema::AssignConvertType
05739 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
05740                                        bool Diagnose) {
05741   if (getLangOpts().CPlusPlus) {
05742     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
05743       // C++ 5.17p3: If the left operand is not of class type, the
05744       // expression is implicitly converted (C++ 4) to the
05745       // cv-unqualified type of the left operand.
05746       ExprResult Res;
05747       if (Diagnose) {
05748         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
05749                                         AA_Assigning);
05750       } else {
05751         ImplicitConversionSequence ICS =
05752             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
05753                                   /*SuppressUserConversions=*/false,
05754                                   /*AllowExplicit=*/false,
05755                                   /*InOverloadResolution=*/false,
05756                                   /*CStyle=*/false,
05757                                   /*AllowObjCWritebackConversion=*/false);
05758         if (ICS.isFailure())
05759           return Incompatible;
05760         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
05761                                         ICS, AA_Assigning);
05762       }
05763       if (Res.isInvalid())
05764         return Incompatible;
05765       Sema::AssignConvertType result = Compatible;
05766       if (getLangOpts().ObjCAutoRefCount &&
05767           !CheckObjCARCUnavailableWeakConversion(LHSType,
05768                                                  RHS.get()->getType()))
05769         result = IncompatibleObjCWeakRef;
05770       RHS = move(Res);
05771       return result;
05772     }
05773 
05774     // FIXME: Currently, we fall through and treat C++ classes like C
05775     // structures.
05776     // FIXME: We also fall through for atomics; not sure what should
05777     // happen there, though.
05778   }
05779 
05780   // C99 6.5.16.1p1: the left operand is a pointer and the right is
05781   // a null pointer constant.
05782   if ((LHSType->isPointerType() ||
05783        LHSType->isObjCObjectPointerType() ||
05784        LHSType->isBlockPointerType())
05785       && RHS.get()->isNullPointerConstant(Context,
05786                                           Expr::NPC_ValueDependentIsNull)) {
05787     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
05788     return Compatible;
05789   }
05790 
05791   // This check seems unnatural, however it is necessary to ensure the proper
05792   // conversion of functions/arrays. If the conversion were done for all
05793   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
05794   // expressions that suppress this implicit conversion (&, sizeof).
05795   //
05796   // Suppress this for references: C++ 8.5.3p5.
05797   if (!LHSType->isReferenceType()) {
05798     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
05799     if (RHS.isInvalid())
05800       return Incompatible;
05801   }
05802 
05803   CastKind Kind = CK_Invalid;
05804   Sema::AssignConvertType result =
05805     CheckAssignmentConstraints(LHSType, RHS, Kind);
05806 
05807   // C99 6.5.16.1p2: The value of the right operand is converted to the
05808   // type of the assignment expression.
05809   // CheckAssignmentConstraints allows the left-hand side to be a reference,
05810   // so that we can use references in built-in functions even in C.
05811   // The getNonReferenceType() call makes sure that the resulting expression
05812   // does not have reference type.
05813   if (result != Incompatible && RHS.get()->getType() != LHSType)
05814     RHS = ImpCastExprToType(RHS.take(),
05815                             LHSType.getNonLValueExprType(Context), Kind);
05816   return result;
05817 }
05818 
05819 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
05820                                ExprResult &RHS) {
05821   Diag(Loc, diag::err_typecheck_invalid_operands)
05822     << LHS.get()->getType() << RHS.get()->getType()
05823     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05824   return QualType();
05825 }
05826 
05827 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
05828                                    SourceLocation Loc, bool IsCompAssign) {
05829   if (!IsCompAssign) {
05830     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
05831     if (LHS.isInvalid())
05832       return QualType();
05833   }
05834   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
05835   if (RHS.isInvalid())
05836     return QualType();
05837 
05838   // For conversion purposes, we ignore any qualifiers.
05839   // For example, "const float" and "float" are equivalent.
05840   QualType LHSType =
05841     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
05842   QualType RHSType =
05843     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
05844 
05845   // If the vector types are identical, return.
05846   if (LHSType == RHSType)
05847     return LHSType;
05848 
05849   // Handle the case of equivalent AltiVec and GCC vector types
05850   if (LHSType->isVectorType() && RHSType->isVectorType() &&
05851       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
05852     if (LHSType->isExtVectorType()) {
05853       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
05854       return LHSType;
05855     }
05856 
05857     if (!IsCompAssign)
05858       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
05859     return RHSType;
05860   }
05861 
05862   if (getLangOpts().LaxVectorConversions &&
05863       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
05864     // If we are allowing lax vector conversions, and LHS and RHS are both
05865     // vectors, the total size only needs to be the same. This is a
05866     // bitcast; no bits are changed but the result type is different.
05867     // FIXME: Should we really be allowing this?
05868     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
05869     return LHSType;
05870   }
05871 
05872   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
05873   // swap back (so that we don't reverse the inputs to a subtract, for instance.
05874   bool swapped = false;
05875   if (RHSType->isExtVectorType() && !IsCompAssign) {
05876     swapped = true;
05877     std::swap(RHS, LHS);
05878     std::swap(RHSType, LHSType);
05879   }
05880 
05881   // Handle the case of an ext vector and scalar.
05882   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
05883     QualType EltTy = LV->getElementType();
05884     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
05885       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
05886       if (order > 0)
05887         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
05888       if (order >= 0) {
05889         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
05890         if (swapped) std::swap(RHS, LHS);
05891         return LHSType;
05892       }
05893     }
05894     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
05895         RHSType->isRealFloatingType()) {
05896       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
05897       if (order > 0)
05898         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
05899       if (order >= 0) {
05900         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
05901         if (swapped) std::swap(RHS, LHS);
05902         return LHSType;
05903       }
05904     }
05905   }
05906 
05907   // Vectors of different size or scalar and non-ext-vector are errors.
05908   if (swapped) std::swap(RHS, LHS);
05909   Diag(Loc, diag::err_typecheck_vector_not_convertable)
05910     << LHS.get()->getType() << RHS.get()->getType()
05911     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05912   return QualType();
05913 }
05914 
05915 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
05916 // expression.  These are mainly cases where the null pointer is used as an
05917 // integer instead of a pointer.
05918 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
05919                                 SourceLocation Loc, bool IsCompare) {
05920   // The canonical way to check for a GNU null is with isNullPointerConstant,
05921   // but we use a bit of a hack here for speed; this is a relatively
05922   // hot path, and isNullPointerConstant is slow.
05923   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
05924   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
05925 
05926   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
05927 
05928   // Avoid analyzing cases where the result will either be invalid (and
05929   // diagnosed as such) or entirely valid and not something to warn about.
05930   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
05931       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
05932     return;
05933 
05934   // Comparison operations would not make sense with a null pointer no matter
05935   // what the other expression is.
05936   if (!IsCompare) {
05937     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
05938         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
05939         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
05940     return;
05941   }
05942 
05943   // The rest of the operations only make sense with a null pointer
05944   // if the other expression is a pointer.
05945   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
05946       NonNullType->canDecayToPointerType())
05947     return;
05948 
05949   S.Diag(Loc, diag::warn_null_in_comparison_operation)
05950       << LHSNull /* LHS is NULL */ << NonNullType
05951       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
05952 }
05953 
05954 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
05955                                            SourceLocation Loc,
05956                                            bool IsCompAssign, bool IsDiv) {
05957   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
05958 
05959   if (LHS.get()->getType()->isVectorType() ||
05960       RHS.get()->getType()->isVectorType())
05961     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
05962 
05963   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
05964   if (LHS.isInvalid() || RHS.isInvalid())
05965     return QualType();
05966 
05967 
05968   if (!LHS.get()->getType()->isArithmeticType() ||
05969       !RHS.get()->getType()->isArithmeticType()) {
05970     if (IsCompAssign &&
05971         LHS.get()->getType()->isAtomicType() &&
05972         RHS.get()->getType()->isArithmeticType())
05973       return compType;
05974     return InvalidOperands(Loc, LHS, RHS);
05975   }
05976 
05977   // Check for division by zero.
05978   if (IsDiv &&
05979       RHS.get()->isNullPointerConstant(Context,
05980                                        Expr::NPC_ValueDependentIsNotNull))
05981     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
05982                                           << RHS.get()->getSourceRange());
05983 
05984   return compType;
05985 }
05986 
05987 QualType Sema::CheckRemainderOperands(
05988   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
05989   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
05990 
05991   if (LHS.get()->getType()->isVectorType() ||
05992       RHS.get()->getType()->isVectorType()) {
05993     if (LHS.get()->getType()->hasIntegerRepresentation() && 
05994         RHS.get()->getType()->hasIntegerRepresentation())
05995       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
05996     return InvalidOperands(Loc, LHS, RHS);
05997   }
05998 
05999   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
06000   if (LHS.isInvalid() || RHS.isInvalid())
06001     return QualType();
06002 
06003   if (!LHS.get()->getType()->isIntegerType() ||
06004       !RHS.get()->getType()->isIntegerType())
06005     return InvalidOperands(Loc, LHS, RHS);
06006 
06007   // Check for remainder by zero.
06008   if (RHS.get()->isNullPointerConstant(Context,
06009                                        Expr::NPC_ValueDependentIsNotNull))
06010     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
06011                                  << RHS.get()->getSourceRange());
06012 
06013   return compType;
06014 }
06015 
06016 /// \brief Diagnose invalid arithmetic on two void pointers.
06017 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
06018                                                 Expr *LHSExpr, Expr *RHSExpr) {
06019   S.Diag(Loc, S.getLangOpts().CPlusPlus
06020                 ? diag::err_typecheck_pointer_arith_void_type
06021                 : diag::ext_gnu_void_ptr)
06022     << 1 /* two pointers */ << LHSExpr->getSourceRange()
06023                             << RHSExpr->getSourceRange();
06024 }
06025 
06026 /// \brief Diagnose invalid arithmetic on a void pointer.
06027 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
06028                                             Expr *Pointer) {
06029   S.Diag(Loc, S.getLangOpts().CPlusPlus
06030                 ? diag::err_typecheck_pointer_arith_void_type
06031                 : diag::ext_gnu_void_ptr)
06032     << 0 /* one pointer */ << Pointer->getSourceRange();
06033 }
06034 
06035 /// \brief Diagnose invalid arithmetic on two function pointers.
06036 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
06037                                                     Expr *LHS, Expr *RHS) {
06038   assert(LHS->getType()->isAnyPointerType());
06039   assert(RHS->getType()->isAnyPointerType());
06040   S.Diag(Loc, S.getLangOpts().CPlusPlus
06041                 ? diag::err_typecheck_pointer_arith_function_type
06042                 : diag::ext_gnu_ptr_func_arith)
06043     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
06044     // We only show the second type if it differs from the first.
06045     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
06046                                                    RHS->getType())
06047     << RHS->getType()->getPointeeType()
06048     << LHS->getSourceRange() << RHS->getSourceRange();
06049 }
06050 
06051 /// \brief Diagnose invalid arithmetic on a function pointer.
06052 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
06053                                                 Expr *Pointer) {
06054   assert(Pointer->getType()->isAnyPointerType());
06055   S.Diag(Loc, S.getLangOpts().CPlusPlus
06056                 ? diag::err_typecheck_pointer_arith_function_type
06057                 : diag::ext_gnu_ptr_func_arith)
06058     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
06059     << 0 /* one pointer, so only one type */
06060     << Pointer->getSourceRange();
06061 }
06062 
06063 /// \brief Emit error if Operand is incomplete pointer type
06064 ///
06065 /// \returns True if pointer has incomplete type
06066 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
06067                                                  Expr *Operand) {
06068   if ((Operand->getType()->isPointerType() &&
06069        !Operand->getType()->isDependentType()) ||
06070       Operand->getType()->isObjCObjectPointerType()) {
06071     QualType PointeeTy = Operand->getType()->getPointeeType();
06072     if (S.RequireCompleteType(
06073           Loc, PointeeTy,
06074           diag::err_typecheck_arithmetic_incomplete_type,
06075           PointeeTy, Operand->getSourceRange()))
06076       return true;
06077   }
06078   return false;
06079 }
06080 
06081 /// \brief Check the validity of an arithmetic pointer operand.
06082 ///
06083 /// If the operand has pointer type, this code will check for pointer types
06084 /// which are invalid in arithmetic operations. These will be diagnosed
06085 /// appropriately, including whether or not the use is supported as an
06086 /// extension.
06087 ///
06088 /// \returns True when the operand is valid to use (even if as an extension).
06089 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
06090                                             Expr *Operand) {
06091   if (!Operand->getType()->isAnyPointerType()) return true;
06092 
06093   QualType PointeeTy = Operand->getType()->getPointeeType();
06094   if (PointeeTy->isVoidType()) {
06095     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
06096     return !S.getLangOpts().CPlusPlus;
06097   }
06098   if (PointeeTy->isFunctionType()) {
06099     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
06100     return !S.getLangOpts().CPlusPlus;
06101   }
06102 
06103   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
06104 
06105   return true;
06106 }
06107 
06108 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
06109 /// operands.
06110 ///
06111 /// This routine will diagnose any invalid arithmetic on pointer operands much
06112 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
06113 /// for emitting a single diagnostic even for operations where both LHS and RHS
06114 /// are (potentially problematic) pointers.
06115 ///
06116 /// \returns True when the operand is valid to use (even if as an extension).
06117 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
06118                                                 Expr *LHSExpr, Expr *RHSExpr) {
06119   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
06120   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
06121   if (!isLHSPointer && !isRHSPointer) return true;
06122 
06123   QualType LHSPointeeTy, RHSPointeeTy;
06124   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
06125   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
06126 
06127   // Check for arithmetic on pointers to incomplete types.
06128   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
06129   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
06130   if (isLHSVoidPtr || isRHSVoidPtr) {
06131     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
06132     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
06133     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
06134 
06135     return !S.getLangOpts().CPlusPlus;
06136   }
06137 
06138   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
06139   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
06140   if (isLHSFuncPtr || isRHSFuncPtr) {
06141     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
06142     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
06143                                                                 RHSExpr);
06144     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
06145 
06146     return !S.getLangOpts().CPlusPlus;
06147   }
06148 
06149   if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
06150   if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
06151 
06152   return true;
06153 }
06154 
06155 /// \brief Check bad cases where we step over interface counts.
06156 static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
06157                                                    SourceLocation OpLoc,
06158                                                    Expr *Op) {
06159   assert(Op->getType()->isAnyPointerType());
06160   QualType PointeeTy = Op->getType()->getPointeeType();
06161   if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
06162     return true;
06163 
06164   S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
06165     << PointeeTy << Op->getSourceRange();
06166   return false;
06167 }
06168 
06169 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
06170 /// literal.
06171 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
06172                                   Expr *LHSExpr, Expr *RHSExpr) {
06173   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
06174   Expr* IndexExpr = RHSExpr;
06175   if (!StrExpr) {
06176     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
06177     IndexExpr = LHSExpr;
06178   }
06179 
06180   bool IsStringPlusInt = StrExpr &&
06181       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
06182   if (!IsStringPlusInt)
06183     return;
06184 
06185   llvm::APSInt index;
06186   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
06187     unsigned StrLenWithNull = StrExpr->getLength() + 1;
06188     if (index.isNonNegative() &&
06189         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
06190                               index.isUnsigned()))
06191       return;
06192   }
06193 
06194   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
06195   Self.Diag(OpLoc, diag::warn_string_plus_int)
06196       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
06197 
06198   // Only print a fixit for "str" + int, not for int + "str".
06199   if (IndexExpr == RHSExpr) {
06200     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
06201     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
06202         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
06203         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
06204         << FixItHint::CreateInsertion(EndLoc, "]");
06205   } else
06206     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
06207 }
06208 
06209 /// \brief Emit error when two pointers are incompatible.
06210 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
06211                                            Expr *LHSExpr, Expr *RHSExpr) {
06212   assert(LHSExpr->getType()->isAnyPointerType());
06213   assert(RHSExpr->getType()->isAnyPointerType());
06214   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
06215     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
06216     << RHSExpr->getSourceRange();
06217 }
06218 
06219 QualType Sema::CheckAdditionOperands( // C99 6.5.6
06220     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
06221     QualType* CompLHSTy) {
06222   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
06223 
06224   if (LHS.get()->getType()->isVectorType() ||
06225       RHS.get()->getType()->isVectorType()) {
06226     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
06227     if (CompLHSTy) *CompLHSTy = compType;
06228     return compType;
06229   }
06230 
06231   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
06232   if (LHS.isInvalid() || RHS.isInvalid())
06233     return QualType();
06234 
06235   // Diagnose "string literal" '+' int.
06236   if (Opc == BO_Add)
06237     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
06238 
06239   // handle the common case first (both operands are arithmetic).
06240   if (LHS.get()->getType()->isArithmeticType() &&
06241       RHS.get()->getType()->isArithmeticType()) {
06242     if (CompLHSTy) *CompLHSTy = compType;
06243     return compType;
06244   }
06245 
06246   if (LHS.get()->getType()->isAtomicType() &&
06247       RHS.get()->getType()->isArithmeticType()) {
06248     *CompLHSTy = LHS.get()->getType();
06249     return compType;
06250   }
06251 
06252   // Put any potential pointer into PExp
06253   Expr* PExp = LHS.get(), *IExp = RHS.get();
06254   if (IExp->getType()->isAnyPointerType())
06255     std::swap(PExp, IExp);
06256 
06257   if (!PExp->getType()->isAnyPointerType())
06258     return InvalidOperands(Loc, LHS, RHS);
06259 
06260   if (!IExp->getType()->isIntegerType())
06261     return InvalidOperands(Loc, LHS, RHS);
06262 
06263   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
06264     return QualType();
06265 
06266   // Diagnose bad cases where we step over interface counts.
06267   if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
06268     return QualType();
06269 
06270   // Check array bounds for pointer arithemtic
06271   CheckArrayAccess(PExp, IExp);
06272 
06273   if (CompLHSTy) {
06274     QualType LHSTy = Context.isPromotableBitField(LHS.get());
06275     if (LHSTy.isNull()) {
06276       LHSTy = LHS.get()->getType();
06277       if (LHSTy->isPromotableIntegerType())
06278         LHSTy = Context.getPromotedIntegerType(LHSTy);
06279     }
06280     *CompLHSTy = LHSTy;
06281   }
06282 
06283   return PExp->getType();
06284 }
06285 
06286 // C99 6.5.6
06287 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
06288                                         SourceLocation Loc,
06289                                         QualType* CompLHSTy) {
06290   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
06291 
06292   if (LHS.get()->getType()->isVectorType() ||
06293       RHS.get()->getType()->isVectorType()) {
06294     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
06295     if (CompLHSTy) *CompLHSTy = compType;
06296     return compType;
06297   }
06298 
06299   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
06300   if (LHS.isInvalid() || RHS.isInvalid())
06301     return QualType();
06302 
06303   // Enforce type constraints: C99 6.5.6p3.
06304 
06305   // Handle the common case first (both operands are arithmetic).
06306   if (LHS.get()->getType()->isArithmeticType() &&
06307       RHS.get()->getType()->isArithmeticType()) {
06308     if (CompLHSTy) *CompLHSTy = compType;
06309     return compType;
06310   }
06311 
06312   if (LHS.get()->getType()->isAtomicType() &&
06313       RHS.get()->getType()->isArithmeticType()) {
06314     *CompLHSTy = LHS.get()->getType();
06315     return compType;
06316   }
06317 
06318   // Either ptr - int   or   ptr - ptr.
06319   if (LHS.get()->getType()->isAnyPointerType()) {
06320     QualType lpointee = LHS.get()->getType()->getPointeeType();
06321 
06322     // Diagnose bad cases where we step over interface counts.
06323     if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
06324       return QualType();
06325 
06326     // The result type of a pointer-int computation is the pointer type.
06327     if (RHS.get()->getType()->isIntegerType()) {
06328       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
06329         return QualType();
06330 
06331       // Check array bounds for pointer arithemtic
06332       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
06333                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
06334 
06335       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
06336       return LHS.get()->getType();
06337     }
06338 
06339     // Handle pointer-pointer subtractions.
06340     if (const PointerType *RHSPTy
06341           = RHS.get()->getType()->getAs<PointerType>()) {
06342       QualType rpointee = RHSPTy->getPointeeType();
06343 
06344       if (getLangOpts().CPlusPlus) {
06345         // Pointee types must be the same: C++ [expr.add]
06346         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
06347           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
06348         }
06349       } else {
06350         // Pointee types must be compatible C99 6.5.6p3
06351         if (!Context.typesAreCompatible(
06352                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
06353                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
06354           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
06355           return QualType();
06356         }
06357       }
06358 
06359       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
06360                                                LHS.get(), RHS.get()))
06361         return QualType();
06362 
06363       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
06364       return Context.getPointerDiffType();
06365     }
06366   }
06367 
06368   return InvalidOperands(Loc, LHS, RHS);
06369 }
06370 
06371 static bool isScopedEnumerationType(QualType T) {
06372   if (const EnumType *ET = dyn_cast<EnumType>(T))
06373     return ET->getDecl()->isScoped();
06374   return false;
06375 }
06376 
06377 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
06378                                    SourceLocation Loc, unsigned Opc,
06379                                    QualType LHSType) {
06380   llvm::APSInt Right;
06381   // Check right/shifter operand
06382   if (RHS.get()->isValueDependent() ||
06383       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
06384     return;
06385 
06386   if (Right.isNegative()) {
06387     S.DiagRuntimeBehavior(Loc, RHS.get(),
06388                           S.PDiag(diag::warn_shift_negative)
06389                             << RHS.get()->getSourceRange());
06390     return;
06391   }
06392   llvm::APInt LeftBits(Right.getBitWidth(),
06393                        S.Context.getTypeSize(LHS.get()->getType()));
06394   if (Right.uge(LeftBits)) {
06395     S.DiagRuntimeBehavior(Loc, RHS.get(),
06396                           S.PDiag(diag::warn_shift_gt_typewidth)
06397                             << RHS.get()->getSourceRange());
06398     return;
06399   }
06400   if (Opc != BO_Shl)
06401     return;
06402 
06403   // When left shifting an ICE which is signed, we can check for overflow which
06404   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
06405   // integers have defined behavior modulo one more than the maximum value
06406   // representable in the result type, so never warn for those.
06407   llvm::APSInt Left;
06408   if (LHS.get()->isValueDependent() ||
06409       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
06410       LHSType->hasUnsignedIntegerRepresentation())
06411     return;
06412   llvm::APInt ResultBits =
06413       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
06414   if (LeftBits.uge(ResultBits))
06415     return;
06416   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
06417   Result = Result.shl(Right);
06418 
06419   // Print the bit representation of the signed integer as an unsigned
06420   // hexadecimal number.
06421   SmallString<40> HexResult;
06422   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
06423 
06424   // If we are only missing a sign bit, this is less likely to result in actual
06425   // bugs -- if the result is cast back to an unsigned type, it will have the
06426   // expected value. Thus we place this behind a different warning that can be
06427   // turned off separately if needed.
06428   if (LeftBits == ResultBits - 1) {
06429     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
06430         << HexResult.str() << LHSType
06431         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06432     return;
06433   }
06434 
06435   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
06436     << HexResult.str() << Result.getMinSignedBits() << LHSType
06437     << Left.getBitWidth() << LHS.get()->getSourceRange()
06438     << RHS.get()->getSourceRange();
06439 }
06440 
06441 // C99 6.5.7
06442 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
06443                                   SourceLocation Loc, unsigned Opc,
06444                                   bool IsCompAssign) {
06445   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
06446 
06447   // C99 6.5.7p2: Each of the operands shall have integer type.
06448   if (!LHS.get()->getType()->hasIntegerRepresentation() || 
06449       !RHS.get()->getType()->hasIntegerRepresentation())
06450     return InvalidOperands(Loc, LHS, RHS);
06451 
06452   // C++0x: Don't allow scoped enums. FIXME: Use something better than
06453   // hasIntegerRepresentation() above instead of this.
06454   if (isScopedEnumerationType(LHS.get()->getType()) ||
06455       isScopedEnumerationType(RHS.get()->getType())) {
06456     return InvalidOperands(Loc, LHS, RHS);
06457   }
06458 
06459   // Vector shifts promote their scalar inputs to vector type.
06460   if (LHS.get()->getType()->isVectorType() ||
06461       RHS.get()->getType()->isVectorType())
06462     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
06463 
06464   // Shifts don't perform usual arithmetic conversions, they just do integer
06465   // promotions on each operand. C99 6.5.7p3
06466 
06467   // For the LHS, do usual unary conversions, but then reset them away
06468   // if this is a compound assignment.
06469   ExprResult OldLHS = LHS;
06470   LHS = UsualUnaryConversions(LHS.take());
06471   if (LHS.isInvalid())
06472     return QualType();
06473   QualType LHSType = LHS.get()->getType();
06474   if (IsCompAssign) LHS = OldLHS;
06475 
06476   // The RHS is simpler.
06477   RHS = UsualUnaryConversions(RHS.take());
06478   if (RHS.isInvalid())
06479     return QualType();
06480 
06481   // Sanity-check shift operands
06482   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
06483 
06484   // "The type of the result is that of the promoted left operand."
06485   return LHSType;
06486 }
06487 
06488 static bool IsWithinTemplateSpecialization(Decl *D) {
06489   if (DeclContext *DC = D->getDeclContext()) {
06490     if (isa<ClassTemplateSpecializationDecl>(DC))
06491       return true;
06492     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
06493       return FD->isFunctionTemplateSpecialization();
06494   }
06495   return false;
06496 }
06497 
06498 /// If two different enums are compared, raise a warning.
06499 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
06500                                 ExprResult &RHS) {
06501   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
06502   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
06503 
06504   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
06505   if (!LHSEnumType)
06506     return;
06507   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
06508   if (!RHSEnumType)
06509     return;
06510 
06511   // Ignore anonymous enums.
06512   if (!LHSEnumType->getDecl()->getIdentifier())
06513     return;
06514   if (!RHSEnumType->getDecl()->getIdentifier())
06515     return;
06516 
06517   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
06518     return;
06519 
06520   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
06521       << LHSStrippedType << RHSStrippedType
06522       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06523 }
06524 
06525 /// \brief Diagnose bad pointer comparisons.
06526 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
06527                                               ExprResult &LHS, ExprResult &RHS,
06528                                               bool IsError) {
06529   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
06530                       : diag::ext_typecheck_comparison_of_distinct_pointers)
06531     << LHS.get()->getType() << RHS.get()->getType()
06532     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06533 }
06534 
06535 /// \brief Returns false if the pointers are converted to a composite type,
06536 /// true otherwise.
06537 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
06538                                            ExprResult &LHS, ExprResult &RHS) {
06539   // C++ [expr.rel]p2:
06540   //   [...] Pointer conversions (4.10) and qualification
06541   //   conversions (4.4) are performed on pointer operands (or on
06542   //   a pointer operand and a null pointer constant) to bring
06543   //   them to their composite pointer type. [...]
06544   //
06545   // C++ [expr.eq]p1 uses the same notion for (in)equality
06546   // comparisons of pointers.
06547 
06548   // C++ [expr.eq]p2:
06549   //   In addition, pointers to members can be compared, or a pointer to
06550   //   member and a null pointer constant. Pointer to member conversions
06551   //   (4.11) and qualification conversions (4.4) are performed to bring
06552   //   them to a common type. If one operand is a null pointer constant,
06553   //   the common type is the type of the other operand. Otherwise, the
06554   //   common type is a pointer to member type similar (4.4) to the type
06555   //   of one of the operands, with a cv-qualification signature (4.4)
06556   //   that is the union of the cv-qualification signatures of the operand
06557   //   types.
06558 
06559   QualType LHSType = LHS.get()->getType();
06560   QualType RHSType = RHS.get()->getType();
06561   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
06562          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
06563 
06564   bool NonStandardCompositeType = false;
06565   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
06566   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
06567   if (T.isNull()) {
06568     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
06569     return true;
06570   }
06571 
06572   if (NonStandardCompositeType)
06573     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
06574       << LHSType << RHSType << T << LHS.get()->getSourceRange()
06575       << RHS.get()->getSourceRange();
06576 
06577   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
06578   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
06579   return false;
06580 }
06581 
06582 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
06583                                                     ExprResult &LHS,
06584                                                     ExprResult &RHS,
06585                                                     bool IsError) {
06586   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
06587                       : diag::ext_typecheck_comparison_of_fptr_to_void)
06588     << LHS.get()->getType() << RHS.get()->getType()
06589     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
06590 }
06591 
06592 // C99 6.5.8, C++ [expr.rel]
06593 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
06594                                     SourceLocation Loc, unsigned OpaqueOpc,
06595                                     bool IsRelational) {
06596   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
06597 
06598   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
06599 
06600   // Handle vector comparisons separately.
06601   if (LHS.get()->getType()->isVectorType() ||
06602       RHS.get()->getType()->isVectorType())
06603     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
06604 
06605   QualType LHSType = LHS.get()->getType();
06606   QualType RHSType = RHS.get()->getType();
06607 
06608   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
06609   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
06610 
06611   checkEnumComparison(*this, Loc, LHS, RHS);
06612 
06613   if (!LHSType->hasFloatingRepresentation() &&
06614       !(LHSType->isBlockPointerType() && IsRelational) &&
06615       !LHS.get()->getLocStart().isMacroID() &&
06616       !RHS.get()->getLocStart().isMacroID()) {
06617     // For non-floating point types, check for self-comparisons of the form
06618     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
06619     // often indicate logic errors in the program.
06620     //
06621     // NOTE: Don't warn about comparison expressions resulting from macro
06622     // expansion. Also don't warn about comparisons which are only self
06623     // comparisons within a template specialization. The warnings should catch
06624     // obvious cases in the definition of the template anyways. The idea is to
06625     // warn when the typed comparison operator will always evaluate to the same
06626     // result.
06627     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
06628       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
06629         if (DRL->getDecl() == DRR->getDecl() &&
06630             !IsWithinTemplateSpecialization(DRL->getDecl())) {
06631           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
06632                               << 0 // self-
06633                               << (Opc == BO_EQ
06634                                   || Opc == BO_LE
06635                                   || Opc == BO_GE));
06636         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
06637                    !DRL->getDecl()->getType()->isReferenceType() &&
06638                    !DRR->getDecl()->getType()->isReferenceType()) {
06639             // what is it always going to eval to?
06640             char always_evals_to;
06641             switch(Opc) {
06642             case BO_EQ: // e.g. array1 == array2
06643               always_evals_to = 0; // false
06644               break;
06645             case BO_NE: // e.g. array1 != array2
06646               always_evals_to = 1; // true
06647               break;
06648             default:
06649               // best we can say is 'a constant'
06650               always_evals_to = 2; // e.g. array1 <= array2
06651               break;
06652             }
06653             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
06654                                 << 1 // array
06655                                 << always_evals_to);
06656         }
06657       }
06658     }
06659 
06660     if (isa<CastExpr>(LHSStripped))
06661       LHSStripped = LHSStripped->IgnoreParenCasts();
06662     if (isa<CastExpr>(RHSStripped))
06663       RHSStripped = RHSStripped->IgnoreParenCasts();
06664 
06665     // Warn about comparisons against a string constant (unless the other
06666     // operand is null), the user probably wants strcmp.
06667     Expr *literalString = 0;
06668     Expr *literalStringStripped = 0;
06669     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
06670         !RHSStripped->isNullPointerConstant(Context,
06671                                             Expr::NPC_ValueDependentIsNull)) {
06672       literalString = LHS.get();
06673       literalStringStripped = LHSStripped;
06674     } else if ((isa<StringLiteral>(RHSStripped) ||
06675                 isa<ObjCEncodeExpr>(RHSStripped)) &&
06676                !LHSStripped->isNullPointerConstant(Context,
06677                                             Expr::NPC_ValueDependentIsNull)) {
06678       literalString = RHS.get();
06679       literalStringStripped = RHSStripped;
06680     }
06681 
06682     if (literalString) {
06683       std::string resultComparison;
06684       switch (Opc) {
06685       case BO_LT: resultComparison = ") < 0"; break;
06686       case BO_GT: resultComparison = ") > 0"; break;
06687       case BO_LE: resultComparison = ") <= 0"; break;
06688       case BO_GE: resultComparison = ") >= 0"; break;
06689       case BO_EQ: resultComparison = ") == 0"; break;
06690       case BO_NE: resultComparison = ") != 0"; break;
06691       default: llvm_unreachable("Invalid comparison operator");
06692       }
06693 
06694       DiagRuntimeBehavior(Loc, 0,
06695         PDiag(diag::warn_stringcompare)
06696           << isa<ObjCEncodeExpr>(literalStringStripped)
06697           << literalString->getSourceRange());
06698     }
06699   }
06700 
06701   // C99 6.5.8p3 / C99 6.5.9p4
06702   if (LHS.get()->getType()->isArithmeticType() &&
06703       RHS.get()->getType()->isArithmeticType()) {
06704     UsualArithmeticConversions(LHS, RHS);
06705     if (LHS.isInvalid() || RHS.isInvalid())
06706       return QualType();
06707   }
06708   else {
06709     LHS = UsualUnaryConversions(LHS.take());
06710     if (LHS.isInvalid())
06711       return QualType();
06712 
06713     RHS = UsualUnaryConversions(RHS.take());
06714     if (RHS.isInvalid())
06715       return QualType();
06716   }
06717 
06718   LHSType = LHS.get()->getType();
06719   RHSType = RHS.get()->getType();
06720 
06721   // The result of comparisons is 'bool' in C++, 'int' in C.
06722   QualType ResultTy = Context.getLogicalOperationType();
06723 
06724   if (IsRelational) {
06725     if (LHSType->isRealType() && RHSType->isRealType())
06726       return ResultTy;
06727   } else {
06728     // Check for comparisons of floating point operands using != and ==.
06729     if (LHSType->hasFloatingRepresentation())
06730       CheckFloatComparison(Loc, LHS.get(), RHS.get());
06731 
06732     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
06733       return ResultTy;
06734   }
06735 
06736   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
06737                                               Expr::NPC_ValueDependentIsNull);
06738   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
06739                                               Expr::NPC_ValueDependentIsNull);
06740 
06741   // All of the following pointer-related warnings are GCC extensions, except
06742   // when handling null pointer constants. 
06743   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
06744     QualType LCanPointeeTy =
06745       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
06746     QualType RCanPointeeTy =
06747       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
06748 
06749     if (getLangOpts().CPlusPlus) {
06750       if (LCanPointeeTy == RCanPointeeTy)
06751         return ResultTy;
06752       if (!IsRelational &&
06753           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
06754         // Valid unless comparison between non-null pointer and function pointer
06755         // This is a gcc extension compatibility comparison.
06756         // In a SFINAE context, we treat this as a hard error to maintain
06757         // conformance with the C++ standard.
06758         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
06759             && !LHSIsNull && !RHSIsNull) {
06760           diagnoseFunctionPointerToVoidComparison(
06761               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
06762           
06763           if (isSFINAEContext())
06764             return QualType();
06765           
06766           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
06767           return ResultTy;
06768         }
06769       }
06770 
06771       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
06772         return QualType();
06773       else
06774         return ResultTy;
06775     }
06776     // C99 6.5.9p2 and C99 6.5.8p2
06777     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
06778                                    RCanPointeeTy.getUnqualifiedType())) {
06779       // Valid unless a relational comparison of function pointers
06780       if (IsRelational && LCanPointeeTy->isFunctionType()) {
06781         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
06782           << LHSType << RHSType << LHS.get()->getSourceRange()
06783           << RHS.get()->getSourceRange();
06784       }
06785     } else if (!IsRelational &&
06786                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
06787       // Valid unless comparison between non-null pointer and function pointer
06788       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
06789           && !LHSIsNull && !RHSIsNull)
06790         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
06791                                                 /*isError*/false);
06792     } else {
06793       // Invalid
06794       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
06795     }
06796     if (LCanPointeeTy != RCanPointeeTy) {
06797       if (LHSIsNull && !RHSIsNull)
06798         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
06799       else
06800         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
06801     }
06802     return ResultTy;
06803   }
06804 
06805   if (getLangOpts().CPlusPlus) {
06806     // Comparison of nullptr_t with itself.
06807     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
06808       return ResultTy;
06809     
06810     // Comparison of pointers with null pointer constants and equality
06811     // comparisons of member pointers to null pointer constants.
06812     if (RHSIsNull &&
06813         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
06814          (!IsRelational && 
06815           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
06816       RHS = ImpCastExprToType(RHS.take(), LHSType, 
06817                         LHSType->isMemberPointerType()
06818                           ? CK_NullToMemberPointer
06819                           : CK_NullToPointer);
06820       return ResultTy;
06821     }
06822     if (LHSIsNull &&
06823         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
06824          (!IsRelational && 
06825           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
06826       LHS = ImpCastExprToType(LHS.take(), RHSType, 
06827                         RHSType->isMemberPointerType()
06828                           ? CK_NullToMemberPointer
06829                           : CK_NullToPointer);
06830       return ResultTy;
06831     }
06832 
06833     // Comparison of member pointers.
06834     if (!IsRelational &&
06835         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
06836       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
06837         return QualType();
06838       else
06839         return ResultTy;
06840     }
06841 
06842     // Handle scoped enumeration types specifically, since they don't promote
06843     // to integers.
06844     if (LHS.get()->getType()->isEnumeralType() &&
06845         Context.hasSameUnqualifiedType(LHS.get()->getType(),
06846                                        RHS.get()->getType()))
06847       return ResultTy;
06848   }
06849 
06850   // Handle block pointer types.
06851   if (!IsRelational && LHSType->isBlockPointerType() &&
06852       RHSType->isBlockPointerType()) {
06853     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
06854     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
06855 
06856     if (!LHSIsNull && !RHSIsNull &&
06857         !Context.typesAreCompatible(lpointee, rpointee)) {
06858       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
06859         << LHSType << RHSType << LHS.get()->getSourceRange()
06860         << RHS.get()->getSourceRange();
06861     }
06862     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
06863     return ResultTy;
06864   }
06865 
06866   // Allow block pointers to be compared with null pointer constants.
06867   if (!IsRelational
06868       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
06869           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
06870     if (!LHSIsNull && !RHSIsNull) {
06871       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
06872              ->getPointeeType()->isVoidType())
06873             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
06874                 ->getPointeeType()->isVoidType())))
06875         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
06876           << LHSType << RHSType << LHS.get()->getSourceRange()
06877           << RHS.get()->getSourceRange();
06878     }
06879     if (LHSIsNull && !RHSIsNull)
06880       LHS = ImpCastExprToType(LHS.take(), RHSType,
06881                               RHSType->isPointerType() ? CK_BitCast
06882                                 : CK_AnyPointerToBlockPointerCast);
06883     else
06884       RHS = ImpCastExprToType(RHS.take(), LHSType,
06885                               LHSType->isPointerType() ? CK_BitCast
06886                                 : CK_AnyPointerToBlockPointerCast);
06887     return ResultTy;
06888   }
06889 
06890   if (LHSType->isObjCObjectPointerType() ||
06891       RHSType->isObjCObjectPointerType()) {
06892     const PointerType *LPT = LHSType->getAs<PointerType>();
06893     const PointerType *RPT = RHSType->getAs<PointerType>();
06894     if (LPT || RPT) {
06895       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
06896       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
06897 
06898       if (!LPtrToVoid && !RPtrToVoid &&
06899           !Context.typesAreCompatible(LHSType, RHSType)) {
06900         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
06901                                           /*isError*/false);
06902       }
06903       if (LHSIsNull && !RHSIsNull)
06904         LHS = ImpCastExprToType(LHS.take(), RHSType,
06905                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
06906       else
06907         RHS = ImpCastExprToType(RHS.take(), LHSType,
06908                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
06909       return ResultTy;
06910     }
06911     if (LHSType->isObjCObjectPointerType() &&
06912         RHSType->isObjCObjectPointerType()) {
06913       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
06914         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
06915                                           /*isError*/false);
06916       if (LHSIsNull && !RHSIsNull)
06917         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
06918       else
06919         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
06920       return ResultTy;
06921     }
06922   }
06923   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
06924       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
06925     unsigned DiagID = 0;
06926     bool isError = false;
06927     if ((LHSIsNull && LHSType->isIntegerType()) ||
06928         (RHSIsNull && RHSType->isIntegerType())) {
06929       if (IsRelational && !getLangOpts().CPlusPlus)
06930         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
06931     } else if (IsRelational && !getLangOpts().CPlusPlus)
06932       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
06933     else if (getLangOpts().CPlusPlus) {
06934       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
06935       isError = true;
06936     } else
06937       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
06938 
06939     if (DiagID) {
06940       Diag(Loc, DiagID)
06941         << LHSType << RHSType << LHS.get()->getSourceRange()
06942         << RHS.get()->getSourceRange();
06943       if (isError)
06944         return QualType();
06945     }
06946     
06947     if (LHSType->isIntegerType())
06948       LHS = ImpCastExprToType(LHS.take(), RHSType,
06949                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
06950     else
06951       RHS = ImpCastExprToType(RHS.take(), LHSType,
06952                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
06953     return ResultTy;
06954   }
06955   
06956   // Handle block pointers.
06957   if (!IsRelational && RHSIsNull
06958       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
06959     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
06960     return ResultTy;
06961   }
06962   if (!IsRelational && LHSIsNull
06963       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
06964     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
06965     return ResultTy;
06966   }
06967 
06968   return InvalidOperands(Loc, LHS, RHS);
06969 }
06970 
06971 
06972 // Return a signed type that is of identical size and number of elements.
06973 // For floating point vectors, return an integer type of identical size 
06974 // and number of elements.
06975 QualType Sema::GetSignedVectorType(QualType V) {
06976   const VectorType *VTy = V->getAs<VectorType>();
06977   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
06978   if (TypeSize == Context.getTypeSize(Context.CharTy))
06979     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
06980   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
06981     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
06982   else if (TypeSize == Context.getTypeSize(Context.IntTy))
06983     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
06984   else if (TypeSize == Context.getTypeSize(Context.LongTy))
06985     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
06986   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
06987          "Unhandled vector element size in vector compare");
06988   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
06989 }
06990 
06991 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
06992 /// operates on extended vector types.  Instead of producing an IntTy result,
06993 /// like a scalar comparison, a vector comparison produces a vector of integer
06994 /// types.
06995 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
06996                                           SourceLocation Loc,
06997                                           bool IsRelational) {
06998   // Check to make sure we're operating on vectors of the same type and width,
06999   // Allowing one side to be a scalar of element type.
07000   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
07001   if (vType.isNull())
07002     return vType;
07003 
07004   QualType LHSType = LHS.get()->getType();
07005 
07006   // If AltiVec, the comparison results in a numeric type, i.e.
07007   // bool for C++, int for C
07008   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
07009     return Context.getLogicalOperationType();
07010 
07011   // For non-floating point types, check for self-comparisons of the form
07012   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
07013   // often indicate logic errors in the program.
07014   if (!LHSType->hasFloatingRepresentation()) {
07015     if (DeclRefExpr* DRL
07016           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
07017       if (DeclRefExpr* DRR
07018             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
07019         if (DRL->getDecl() == DRR->getDecl())
07020           DiagRuntimeBehavior(Loc, 0,
07021                               PDiag(diag::warn_comparison_always)
07022                                 << 0 // self-
07023                                 << 2 // "a constant"
07024                               );
07025   }
07026 
07027   // Check for comparisons of floating point operands using != and ==.
07028   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
07029     assert (RHS.get()->getType()->hasFloatingRepresentation());
07030     CheckFloatComparison(Loc, LHS.get(), RHS.get());
07031   }
07032   
07033   // Return a signed type for the vector.
07034   return GetSignedVectorType(LHSType);
07035 }
07036 
07037 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
07038                                           SourceLocation Loc) {
07039   // Ensure that either both operands are of the same vector type, or
07040   // one operand is of a vector type and the other is of its element type.
07041   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
07042   if (vType.isNull() || vType->isFloatingType())
07043     return InvalidOperands(Loc, LHS, RHS);
07044   
07045   return GetSignedVectorType(LHS.get()->getType());
07046 }
07047 
07048 inline QualType Sema::CheckBitwiseOperands(
07049   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
07050   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
07051 
07052   if (LHS.get()->getType()->isVectorType() ||
07053       RHS.get()->getType()->isVectorType()) {
07054     if (LHS.get()->getType()->hasIntegerRepresentation() &&
07055         RHS.get()->getType()->hasIntegerRepresentation())
07056       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
07057     
07058     return InvalidOperands(Loc, LHS, RHS);
07059   }
07060 
07061   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
07062   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
07063                                                  IsCompAssign);
07064   if (LHSResult.isInvalid() || RHSResult.isInvalid())
07065     return QualType();
07066   LHS = LHSResult.take();
07067   RHS = RHSResult.take();
07068 
07069   if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
07070       RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
07071     return compType;
07072   return InvalidOperands(Loc, LHS, RHS);
07073 }
07074 
07075 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
07076   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
07077   
07078   // Check vector operands differently.
07079   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
07080     return CheckVectorLogicalOperands(LHS, RHS, Loc);
07081   
07082   // Diagnose cases where the user write a logical and/or but probably meant a
07083   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
07084   // is a constant.
07085   if (LHS.get()->getType()->isIntegerType() &&
07086       !LHS.get()->getType()->isBooleanType() &&
07087       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
07088       // Don't warn in macros or template instantiations.
07089       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
07090     // If the RHS can be constant folded, and if it constant folds to something
07091     // that isn't 0 or 1 (which indicate a potential logical operation that
07092     // happened to fold to true/false) then warn.
07093     // Parens on the RHS are ignored.
07094     llvm::APSInt Result;
07095     if (RHS.get()->EvaluateAsInt(Result, Context))
07096       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
07097           (Result != 0 && Result != 1)) {
07098         Diag(Loc, diag::warn_logical_instead_of_bitwise)
07099           << RHS.get()->getSourceRange()
07100           << (Opc == BO_LAnd ? "&&" : "||");
07101         // Suggest replacing the logical operator with the bitwise version
07102         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
07103             << (Opc == BO_LAnd ? "&" : "|")
07104             << FixItHint::CreateReplacement(SourceRange(
07105                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
07106                                                 getLangOpts())),
07107                                             Opc == BO_LAnd ? "&" : "|");
07108         if (Opc == BO_LAnd)
07109           // Suggest replacing "Foo() && kNonZero" with "Foo()"
07110           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
07111               << FixItHint::CreateRemoval(
07112                   SourceRange(
07113                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
07114                                                  0, getSourceManager(),
07115                                                  getLangOpts()),
07116                       RHS.get()->getLocEnd()));
07117       }
07118   }
07119   
07120   if (!Context.getLangOpts().CPlusPlus) {
07121     LHS = UsualUnaryConversions(LHS.take());
07122     if (LHS.isInvalid())
07123       return QualType();
07124 
07125     RHS = UsualUnaryConversions(RHS.take());
07126     if (RHS.isInvalid())
07127       return QualType();
07128 
07129     if (!LHS.get()->getType()->isScalarType() ||
07130         !RHS.get()->getType()->isScalarType())
07131       return InvalidOperands(Loc, LHS, RHS);
07132 
07133     return Context.IntTy;
07134   }
07135 
07136   // The following is safe because we only use this method for
07137   // non-overloadable operands.
07138 
07139   // C++ [expr.log.and]p1
07140   // C++ [expr.log.or]p1
07141   // The operands are both contextually converted to type bool.
07142   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
07143   if (LHSRes.isInvalid())
07144     return InvalidOperands(Loc, LHS, RHS);
07145   LHS = move(LHSRes);
07146 
07147   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
07148   if (RHSRes.isInvalid())
07149     return InvalidOperands(Loc, LHS, RHS);
07150   RHS = move(RHSRes);
07151 
07152   // C++ [expr.log.and]p2
07153   // C++ [expr.log.or]p2
07154   // The result is a bool.
07155   return Context.BoolTy;
07156 }
07157 
07158 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
07159 /// is a read-only property; return true if so. A readonly property expression
07160 /// depends on various declarations and thus must be treated specially.
07161 ///
07162 static bool IsReadonlyProperty(Expr *E, Sema &S) {
07163   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
07164   if (!PropExpr) return false;
07165   if (PropExpr->isImplicitProperty()) return false;
07166 
07167   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
07168   QualType BaseType = PropExpr->isSuperReceiver() ? 
07169                             PropExpr->getSuperReceiverType() :  
07170                             PropExpr->getBase()->getType();
07171       
07172   if (const ObjCObjectPointerType *OPT =
07173       BaseType->getAsObjCInterfacePointerType())
07174     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
07175       if (S.isPropertyReadonly(PDecl, IFace))
07176         return true;
07177   return false;
07178 }
07179 
07180 static bool IsReadonlyMessage(Expr *E, Sema &S) {
07181   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
07182   if (!ME) return false;
07183   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
07184   ObjCMessageExpr *Base =
07185     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
07186   if (!Base) return false;
07187   return Base->getMethodDecl() != 0;
07188 }
07189 
07190 /// Is the given expression (which must be 'const') a reference to a
07191 /// variable which was originally non-const, but which has become
07192 /// 'const' due to being captured within a block?
07193 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
07194 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
07195   assert(E->isLValue() && E->getType().isConstQualified());
07196   E = E->IgnoreParens();
07197 
07198   // Must be a reference to a declaration from an enclosing scope.
07199   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
07200   if (!DRE) return NCCK_None;
07201   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
07202 
07203   // The declaration must be a variable which is not declared 'const'.
07204   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
07205   if (!var) return NCCK_None;
07206   if (var->getType().isConstQualified()) return NCCK_None;
07207   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
07208 
07209   // Decide whether the first capture was for a block or a lambda.
07210   DeclContext *DC = S.CurContext;
07211   while (DC->getParent() != var->getDeclContext())
07212     DC = DC->getParent();
07213   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
07214 }
07215 
07216 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
07217 /// emit an error and return true.  If so, return false.
07218 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
07219   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
07220   SourceLocation OrigLoc = Loc;
07221   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
07222                                                               &Loc);
07223   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
07224     IsLV = Expr::MLV_ReadonlyProperty;
07225   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
07226     IsLV = Expr::MLV_InvalidMessageExpression;
07227   if (IsLV == Expr::MLV_Valid)
07228     return false;
07229 
07230   unsigned Diag = 0;
07231   bool NeedType = false;
07232   switch (IsLV) { // C99 6.5.16p2
07233   case Expr::MLV_ConstQualified:
07234     Diag = diag::err_typecheck_assign_const;
07235 
07236     // Use a specialized diagnostic when we're assigning to an object
07237     // from an enclosing function or block.
07238     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
07239       if (NCCK == NCCK_Block)
07240         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
07241       else
07242         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
07243       break;
07244     }
07245 
07246     // In ARC, use some specialized diagnostics for occasions where we
07247     // infer 'const'.  These are always pseudo-strong variables.
07248     if (S.getLangOpts().ObjCAutoRefCount) {
07249       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
07250       if (declRef && isa<VarDecl>(declRef->getDecl())) {
07251         VarDecl *var = cast<VarDecl>(declRef->getDecl());
07252 
07253         // Use the normal diagnostic if it's pseudo-__strong but the
07254         // user actually wrote 'const'.
07255         if (var->isARCPseudoStrong() &&
07256             (!var->getTypeSourceInfo() ||
07257              !var->getTypeSourceInfo()->getType().isConstQualified())) {
07258           // There are two pseudo-strong cases:
07259           //  - self
07260           ObjCMethodDecl *method = S.getCurMethodDecl();
07261           if (method && var == method->getSelfDecl())
07262             Diag = method->isClassMethod()
07263               ? diag::err_typecheck_arc_assign_self_class_method
07264               : diag::err_typecheck_arc_assign_self;
07265 
07266           //  - fast enumeration variables
07267           else
07268             Diag = diag::err_typecheck_arr_assign_enumeration;
07269 
07270           SourceRange Assign;
07271           if (Loc != OrigLoc)
07272             Assign = SourceRange(OrigLoc, OrigLoc);
07273           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
07274           // We need to preserve the AST regardless, so migration tool 
07275           // can do its job.
07276           return false;
07277         }
07278       }
07279     }
07280 
07281     break;
07282   case Expr::MLV_ArrayType:
07283     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
07284     NeedType = true;
07285     break;
07286   case Expr::MLV_NotObjectType:
07287     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
07288     NeedType = true;
07289     break;
07290   case Expr::MLV_LValueCast:
07291     Diag = diag::err_typecheck_lvalue_casts_not_supported;
07292     break;
07293   case Expr::MLV_Valid:
07294     llvm_unreachable("did not take early return for MLV_Valid");
07295   case Expr::MLV_InvalidExpression:
07296   case Expr::MLV_MemberFunction:
07297   case Expr::MLV_ClassTemporary:
07298     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
07299     break;
07300   case Expr::MLV_IncompleteType:
07301   case Expr::MLV_IncompleteVoidType:
07302     return S.RequireCompleteType(Loc, E->getType(),
07303              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
07304   case Expr::MLV_DuplicateVectorComponents:
07305     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
07306     break;
07307   case Expr::MLV_ReadonlyProperty:
07308   case Expr::MLV_NoSetterProperty:
07309     llvm_unreachable("readonly properties should be processed differently");
07310   case Expr::MLV_InvalidMessageExpression:
07311     Diag = diag::error_readonly_message_assignment;
07312     break;
07313   case Expr::MLV_SubObjCPropertySetting:
07314     Diag = diag::error_no_subobject_property_setting;
07315     break;
07316   }
07317 
07318   SourceRange Assign;
07319   if (Loc != OrigLoc)
07320     Assign = SourceRange(OrigLoc, OrigLoc);
07321   if (NeedType)
07322     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
07323   else
07324     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
07325   return true;
07326 }
07327 
07328 
07329 
07330 // C99 6.5.16.1
07331 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
07332                                        SourceLocation Loc,
07333                                        QualType CompoundType) {
07334   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
07335 
07336   // Verify that LHS is a modifiable lvalue, and emit error if not.
07337   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
07338     return QualType();
07339 
07340   QualType LHSType = LHSExpr->getType();
07341   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
07342                                              CompoundType;
07343   AssignConvertType ConvTy;
07344   if (CompoundType.isNull()) {
07345     QualType LHSTy(LHSType);
07346     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
07347     if (RHS.isInvalid())
07348       return QualType();
07349     // Special case of NSObject attributes on c-style pointer types.
07350     if (ConvTy == IncompatiblePointer &&
07351         ((Context.isObjCNSObjectType(LHSType) &&
07352           RHSType->isObjCObjectPointerType()) ||
07353          (Context.isObjCNSObjectType(RHSType) &&
07354           LHSType->isObjCObjectPointerType())))
07355       ConvTy = Compatible;
07356 
07357     if (ConvTy == Compatible &&
07358         LHSType->isObjCObjectType())
07359         Diag(Loc, diag::err_objc_object_assignment)
07360           << LHSType;
07361 
07362     // If the RHS is a unary plus or minus, check to see if they = and + are
07363     // right next to each other.  If so, the user may have typo'd "x =+ 4"
07364     // instead of "x += 4".
07365     Expr *RHSCheck = RHS.get();
07366     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
07367       RHSCheck = ICE->getSubExpr();
07368     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
07369       if ((UO->getOpcode() == UO_Plus ||
07370            UO->getOpcode() == UO_Minus) &&
07371           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
07372           // Only if the two operators are exactly adjacent.
07373           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
07374           // And there is a space or other character before the subexpr of the
07375           // unary +/-.  We don't want to warn on "x=-1".
07376           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
07377           UO->getSubExpr()->getLocStart().isFileID()) {
07378         Diag(Loc, diag::warn_not_compound_assign)
07379           << (UO->getOpcode() == UO_Plus ? "+" : "-")
07380           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
07381       }
07382     }
07383 
07384     if (ConvTy == Compatible) {
07385       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
07386         checkRetainCycles(LHSExpr, RHS.get());
07387       else if (getLangOpts().ObjCAutoRefCount)
07388         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
07389     }
07390   } else {
07391     // Compound assignment "x += y"
07392     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
07393   }
07394 
07395   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
07396                                RHS.get(), AA_Assigning))
07397     return QualType();
07398 
07399   CheckForNullPointerDereference(*this, LHSExpr);
07400 
07401   // C99 6.5.16p3: The type of an assignment expression is the type of the
07402   // left operand unless the left operand has qualified type, in which case
07403   // it is the unqualified version of the type of the left operand.
07404   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
07405   // is converted to the type of the assignment expression (above).
07406   // C++ 5.17p1: the type of the assignment expression is that of its left
07407   // operand.
07408   return (getLangOpts().CPlusPlus
07409           ? LHSType : LHSType.getUnqualifiedType());
07410 }
07411 
07412 // C99 6.5.17
07413 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
07414                                    SourceLocation Loc) {
07415   S.DiagnoseUnusedExprResult(LHS.get());
07416 
07417   LHS = S.CheckPlaceholderExpr(LHS.take());
07418   RHS = S.CheckPlaceholderExpr(RHS.take());
07419   if (LHS.isInvalid() || RHS.isInvalid())
07420     return QualType();
07421 
07422   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
07423   // operands, but not unary promotions.
07424   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
07425 
07426   // So we treat the LHS as a ignored value, and in C++ we allow the
07427   // containing site to determine what should be done with the RHS.
07428   LHS = S.IgnoredValueConversions(LHS.take());
07429   if (LHS.isInvalid())
07430     return QualType();
07431 
07432   if (!S.getLangOpts().CPlusPlus) {
07433     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
07434     if (RHS.isInvalid())
07435       return QualType();
07436     if (!RHS.get()->getType()->isVoidType())
07437       S.RequireCompleteType(Loc, RHS.get()->getType(),
07438                             diag::err_incomplete_type);
07439   }
07440 
07441   return RHS.get()->getType();
07442 }
07443 
07444 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
07445 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
07446 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
07447                                                ExprValueKind &VK,
07448                                                SourceLocation OpLoc,
07449                                                bool IsInc, bool IsPrefix) {
07450   if (Op->isTypeDependent())
07451     return S.Context.DependentTy;
07452 
07453   QualType ResType = Op->getType();
07454   // Atomic types can be used for increment / decrement where the non-atomic
07455   // versions can, so ignore the _Atomic() specifier for the purpose of
07456   // checking.
07457   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
07458     ResType = ResAtomicType->getValueType();
07459 
07460   assert(!ResType.isNull() && "no type for increment/decrement expression");
07461 
07462   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
07463     // Decrement of bool is not allowed.
07464     if (!IsInc) {
07465       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
07466       return QualType();
07467     }
07468     // Increment of bool sets it to true, but is deprecated.
07469     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
07470   } else if (ResType->isRealType()) {
07471     // OK!
07472   } else if (ResType->isAnyPointerType()) {
07473     // C99 6.5.2.4p2, 6.5.6p2
07474     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
07475       return QualType();
07476 
07477     // Diagnose bad cases where we step over interface counts.
07478     else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
07479       return QualType();
07480   } else if (ResType->isAnyComplexType()) {
07481     // C99 does not support ++/-- on complex types, we allow as an extension.
07482     S.Diag(OpLoc, diag::ext_integer_increment_complex)
07483       << ResType << Op->getSourceRange();
07484   } else if (ResType->isPlaceholderType()) {
07485     ExprResult PR = S.CheckPlaceholderExpr(Op);
07486     if (PR.isInvalid()) return QualType();
07487     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
07488                                           IsInc, IsPrefix);
07489   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
07490     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
07491   } else {
07492     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
07493       << ResType << int(IsInc) << Op->getSourceRange();
07494     return QualType();
07495   }
07496   // At this point, we know we have a real, complex or pointer type.
07497   // Now make sure the operand is a modifiable lvalue.
07498   if (CheckForModifiableLvalue(Op, OpLoc, S))
07499     return QualType();
07500   // In C++, a prefix increment is the same type as the operand. Otherwise
07501   // (in C or with postfix), the increment is the unqualified type of the
07502   // operand.
07503   if (IsPrefix && S.getLangOpts().CPlusPlus) {
07504     VK = VK_LValue;
07505     return ResType;
07506   } else {
07507     VK = VK_RValue;
07508     return ResType.getUnqualifiedType();
07509   }
07510 }
07511   
07512 
07513 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
07514 /// This routine allows us to typecheck complex/recursive expressions
07515 /// where the declaration is needed for type checking. We only need to
07516 /// handle cases when the expression references a function designator
07517 /// or is an lvalue. Here are some examples:
07518 ///  - &(x) => x
07519 ///  - &*****f => f for f a function designator.
07520 ///  - &s.xx => s
07521 ///  - &s.zz[1].yy -> s, if zz is an array
07522 ///  - *(x + 1) -> x, if x is an array
07523 ///  - &"123"[2] -> 0
07524 ///  - & __real__ x -> x
07525 static ValueDecl *getPrimaryDecl(Expr *E) {
07526   switch (E->getStmtClass()) {
07527   case Stmt::DeclRefExprClass:
07528     return cast<DeclRefExpr>(E)->getDecl();
07529   case Stmt::MemberExprClass:
07530     // If this is an arrow operator, the address is an offset from
07531     // the base's value, so the object the base refers to is
07532     // irrelevant.
07533     if (cast<MemberExpr>(E)->isArrow())
07534       return 0;
07535     // Otherwise, the expression refers to a part of the base
07536     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
07537   case Stmt::ArraySubscriptExprClass: {
07538     // FIXME: This code shouldn't be necessary!  We should catch the implicit
07539     // promotion of register arrays earlier.
07540     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
07541     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
07542       if (ICE->getSubExpr()->getType()->isArrayType())
07543         return getPrimaryDecl(ICE->getSubExpr());
07544     }
07545     return 0;
07546   }
07547   case Stmt::UnaryOperatorClass: {
07548     UnaryOperator *UO = cast<UnaryOperator>(E);
07549 
07550     switch(UO->getOpcode()) {
07551     case UO_Real:
07552     case UO_Imag:
07553     case UO_Extension:
07554       return getPrimaryDecl(UO->getSubExpr());
07555     default:
07556       return 0;
07557     }
07558   }
07559   case Stmt::ParenExprClass:
07560     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
07561   case Stmt::ImplicitCastExprClass:
07562     // If the result of an implicit cast is an l-value, we care about
07563     // the sub-expression; otherwise, the result here doesn't matter.
07564     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
07565   default:
07566     return 0;
07567   }
07568 }
07569 
07570 namespace {
07571   enum {
07572     AO_Bit_Field = 0,
07573     AO_Vector_Element = 1,
07574     AO_Property_Expansion = 2,
07575     AO_Register_Variable = 3,
07576     AO_No_Error = 4
07577   };
07578 }
07579 /// \brief Diagnose invalid operand for address of operations.
07580 ///
07581 /// \param Type The type of operand which cannot have its address taken.
07582 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
07583                                          Expr *E, unsigned Type) {
07584   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
07585 }
07586 
07587 /// CheckAddressOfOperand - The operand of & must be either a function
07588 /// designator or an lvalue designating an object. If it is an lvalue, the
07589 /// object cannot be declared with storage class register or be a bit field.
07590 /// Note: The usual conversions are *not* applied to the operand of the &
07591 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
07592 /// In C++, the operand might be an overloaded function name, in which case
07593 /// we allow the '&' but retain the overloaded-function type.
07594 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
07595                                       SourceLocation OpLoc) {
07596   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
07597     if (PTy->getKind() == BuiltinType::Overload) {
07598       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
07599         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
07600           << OrigOp.get()->getSourceRange();
07601         return QualType();
07602       }
07603                   
07604       return S.Context.OverloadTy;
07605     }
07606 
07607     if (PTy->getKind() == BuiltinType::UnknownAny)
07608       return S.Context.UnknownAnyTy;
07609 
07610     if (PTy->getKind() == BuiltinType::BoundMember) {
07611       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
07612         << OrigOp.get()->getSourceRange();
07613       return QualType();
07614     }
07615 
07616     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
07617     if (OrigOp.isInvalid()) return QualType();
07618   }
07619 
07620   if (OrigOp.get()->isTypeDependent())
07621     return S.Context.DependentTy;
07622 
07623   assert(!OrigOp.get()->getType()->isPlaceholderType());
07624 
07625   // Make sure to ignore parentheses in subsequent checks
07626   Expr *op = OrigOp.get()->IgnoreParens();
07627 
07628   if (S.getLangOpts().C99) {
07629     // Implement C99-only parts of addressof rules.
07630     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
07631       if (uOp->getOpcode() == UO_Deref)
07632         // Per C99 6.5.3.2, the address of a deref always returns a valid result
07633         // (assuming the deref expression is valid).
07634         return uOp->getSubExpr()->getType();
07635     }
07636     // Technically, there should be a check for array subscript
07637     // expressions here, but the result of one is always an lvalue anyway.
07638   }
07639   ValueDecl *dcl = getPrimaryDecl(op);
07640   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
07641   unsigned AddressOfError = AO_No_Error;
07642 
07643   if (lval == Expr::LV_ClassTemporary) { 
07644     bool sfinae = S.isSFINAEContext();
07645     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
07646                          : diag::ext_typecheck_addrof_class_temporary)
07647       << op->getType() << op->getSourceRange();
07648     if (sfinae)
07649       return QualType();
07650   } else if (isa<ObjCSelectorExpr>(op)) {
07651     return S.Context.getPointerType(op->getType());
07652   } else if (lval == Expr::LV_MemberFunction) {
07653     // If it's an instance method, make a member pointer.
07654     // The expression must have exactly the form &A::foo.
07655 
07656     // If the underlying expression isn't a decl ref, give up.
07657     if (!isa<DeclRefExpr>(op)) {
07658       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
07659         << OrigOp.get()->getSourceRange();
07660       return QualType();
07661     }
07662     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
07663     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
07664 
07665     // The id-expression was parenthesized.
07666     if (OrigOp.get() != DRE) {
07667       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
07668         << OrigOp.get()->getSourceRange();
07669 
07670     // The method was named without a qualifier.
07671     } else if (!DRE->getQualifier()) {
07672       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
07673         << op->getSourceRange();
07674     }
07675 
07676     return S.Context.getMemberPointerType(op->getType(),
07677               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
07678   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
07679     // C99 6.5.3.2p1
07680     // The operand must be either an l-value or a function designator
07681     if (!op->getType()->isFunctionType()) {
07682       // Use a special diagnostic for loads from property references.
07683       if (isa<PseudoObjectExpr>(op)) {
07684         AddressOfError = AO_Property_Expansion;
07685       } else {
07686         // FIXME: emit more specific diag...
07687         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
07688           << op->getSourceRange();
07689         return QualType();
07690       }
07691     }
07692   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
07693     // The operand cannot be a bit-field
07694     AddressOfError = AO_Bit_Field;
07695   } else if (op->getObjectKind() == OK_VectorComponent) {
07696     // The operand cannot be an element of a vector
07697     AddressOfError = AO_Vector_Element;
07698   } else if (dcl) { // C99 6.5.3.2p1
07699     // We have an lvalue with a decl. Make sure the decl is not declared
07700     // with the register storage-class specifier.
07701     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
07702       // in C++ it is not error to take address of a register
07703       // variable (c++03 7.1.1P3)
07704       if (vd->getStorageClass() == SC_Register &&
07705           !S.getLangOpts().CPlusPlus) {
07706         AddressOfError = AO_Register_Variable;
07707       }
07708     } else if (isa<FunctionTemplateDecl>(dcl)) {
07709       return S.Context.OverloadTy;
07710     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
07711       // Okay: we can take the address of a field.
07712       // Could be a pointer to member, though, if there is an explicit
07713       // scope qualifier for the class.
07714       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
07715         DeclContext *Ctx = dcl->getDeclContext();
07716         if (Ctx && Ctx->isRecord()) {
07717           if (dcl->getType()->isReferenceType()) {
07718             S.Diag(OpLoc,
07719                    diag::err_cannot_form_pointer_to_member_of_reference_type)
07720               << dcl->getDeclName() << dcl->getType();
07721             return QualType();
07722           }
07723 
07724           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
07725             Ctx = Ctx->getParent();
07726           return S.Context.getMemberPointerType(op->getType(),
07727                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
07728         }
07729       }
07730     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
07731       llvm_unreachable("Unknown/unexpected decl type");
07732   }
07733 
07734   if (AddressOfError != AO_No_Error) {
07735     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
07736     return QualType();
07737   }
07738 
07739   if (lval == Expr::LV_IncompleteVoidType) {
07740     // Taking the address of a void variable is technically illegal, but we
07741     // allow it in cases which are otherwise valid.
07742     // Example: "extern void x; void* y = &x;".
07743     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
07744   }
07745 
07746   // If the operand has type "type", the result has type "pointer to type".
07747   if (op->getType()->isObjCObjectType())
07748     return S.Context.getObjCObjectPointerType(op->getType());
07749   return S.Context.getPointerType(op->getType());
07750 }
07751 
07752 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
07753 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
07754                                         SourceLocation OpLoc) {
07755   if (Op->isTypeDependent())
07756     return S.Context.DependentTy;
07757 
07758   ExprResult ConvResult = S.UsualUnaryConversions(Op);
07759   if (ConvResult.isInvalid())
07760     return QualType();
07761   Op = ConvResult.take();
07762   QualType OpTy = Op->getType();
07763   QualType Result;
07764 
07765   if (isa<CXXReinterpretCastExpr>(Op)) {
07766     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
07767     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
07768                                      Op->getSourceRange());
07769   }
07770 
07771   // Note that per both C89 and C99, indirection is always legal, even if OpTy
07772   // is an incomplete type or void.  It would be possible to warn about
07773   // dereferencing a void pointer, but it's completely well-defined, and such a
07774   // warning is unlikely to catch any mistakes.
07775   if (const PointerType *PT = OpTy->getAs<PointerType>())
07776     Result = PT->getPointeeType();
07777   else if (const ObjCObjectPointerType *OPT =
07778              OpTy->getAs<ObjCObjectPointerType>())
07779     Result = OPT->getPointeeType();
07780   else {
07781     ExprResult PR = S.CheckPlaceholderExpr(Op);
07782     if (PR.isInvalid()) return QualType();
07783     if (PR.take() != Op)
07784       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
07785   }
07786 
07787   if (Result.isNull()) {
07788     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
07789       << OpTy << Op->getSourceRange();
07790     return QualType();
07791   }
07792 
07793   // Dereferences are usually l-values...
07794   VK = VK_LValue;
07795 
07796   // ...except that certain expressions are never l-values in C.
07797   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
07798     VK = VK_RValue;
07799   
07800   return Result;
07801 }
07802 
07803 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
07804   tok::TokenKind Kind) {
07805   BinaryOperatorKind Opc;
07806   switch (Kind) {
07807   default: llvm_unreachable("Unknown binop!");
07808   case tok::periodstar:           Opc = BO_PtrMemD; break;
07809   case tok::arrowstar:            Opc = BO_PtrMemI; break;
07810   case tok::star:                 Opc = BO_Mul; break;
07811   case tok::slash:                Opc = BO_Div; break;
07812   case tok::percent:              Opc = BO_Rem; break;
07813   case tok::plus:                 Opc = BO_Add; break;
07814   case tok::minus:                Opc = BO_Sub; break;
07815   case tok::lessless:             Opc = BO_Shl; break;
07816   case tok::greatergreater:       Opc = BO_Shr; break;
07817   case tok::lessequal:            Opc = BO_LE; break;
07818   case tok::less:                 Opc = BO_LT; break;
07819   case tok::greaterequal:         Opc = BO_GE; break;
07820   case tok::greater:              Opc = BO_GT; break;
07821   case tok::exclaimequal:         Opc = BO_NE; break;
07822   case tok::equalequal:           Opc = BO_EQ; break;
07823   case tok::amp:                  Opc = BO_And; break;
07824   case tok::caret:                Opc = BO_Xor; break;
07825   case tok::pipe:                 Opc = BO_Or; break;
07826   case tok::ampamp:               Opc = BO_LAnd; break;
07827   case tok::pipepipe:             Opc = BO_LOr; break;
07828   case tok::equal:                Opc = BO_Assign; break;
07829   case tok::starequal:            Opc = BO_MulAssign; break;
07830   case tok::slashequal:           Opc = BO_DivAssign; break;
07831   case tok::percentequal:         Opc = BO_RemAssign; break;
07832   case tok::plusequal:            Opc = BO_AddAssign; break;
07833   case tok::minusequal:           Opc = BO_SubAssign; break;
07834   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
07835   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
07836   case tok::ampequal:             Opc = BO_AndAssign; break;
07837   case tok::caretequal:           Opc = BO_XorAssign; break;
07838   case tok::pipeequal:            Opc = BO_OrAssign; break;
07839   case tok::comma:                Opc = BO_Comma; break;
07840   }
07841   return Opc;
07842 }
07843 
07844 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
07845   tok::TokenKind Kind) {
07846   UnaryOperatorKind Opc;
07847   switch (Kind) {
07848   default: llvm_unreachable("Unknown unary op!");
07849   case tok::plusplus:     Opc = UO_PreInc; break;
07850   case tok::minusminus:   Opc = UO_PreDec; break;
07851   case tok::amp:          Opc = UO_AddrOf; break;
07852   case tok::star:         Opc = UO_Deref; break;
07853   case tok::plus:         Opc = UO_Plus; break;
07854   case tok::minus:        Opc = UO_Minus; break;
07855   case tok::tilde:        Opc = UO_Not; break;
07856   case tok::exclaim:      Opc = UO_LNot; break;
07857   case tok::kw___real:    Opc = UO_Real; break;
07858   case tok::kw___imag:    Opc = UO_Imag; break;
07859   case tok::kw___extension__: Opc = UO_Extension; break;
07860   }
07861   return Opc;
07862 }
07863 
07864 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
07865 /// This warning is only emitted for builtin assignment operations. It is also
07866 /// suppressed in the event of macro expansions.
07867 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
07868                                    SourceLocation OpLoc) {
07869   if (!S.ActiveTemplateInstantiations.empty())
07870     return;
07871   if (OpLoc.isInvalid() || OpLoc.isMacroID())
07872     return;
07873   LHSExpr = LHSExpr->IgnoreParenImpCasts();
07874   RHSExpr = RHSExpr->IgnoreParenImpCasts();
07875   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
07876   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
07877   if (!LHSDeclRef || !RHSDeclRef ||
07878       LHSDeclRef->getLocation().isMacroID() ||
07879       RHSDeclRef->getLocation().isMacroID())
07880     return;
07881   const ValueDecl *LHSDecl =
07882     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
07883   const ValueDecl *RHSDecl =
07884     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
07885   if (LHSDecl != RHSDecl)
07886     return;
07887   if (LHSDecl->getType().isVolatileQualified())
07888     return;
07889   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
07890     if (RefTy->getPointeeType().isVolatileQualified())
07891       return;
07892 
07893   S.Diag(OpLoc, diag::warn_self_assignment)
07894       << LHSDeclRef->getType()
07895       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
07896 }
07897 
07898 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
07899 /// operator @p Opc at location @c TokLoc. This routine only supports
07900 /// built-in operations; ActOnBinOp handles overloaded operators.
07901 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
07902                                     BinaryOperatorKind Opc,
07903                                     Expr *LHSExpr, Expr *RHSExpr) {
07904   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
07905     // The syntax only allows initializer lists on the RHS of assignment,
07906     // so we don't need to worry about accepting invalid code for
07907     // non-assignment operators.
07908     // C++11 5.17p9:
07909     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
07910     //   of x = {} is x = T().
07911     InitializationKind Kind =
07912         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
07913     InitializedEntity Entity =
07914         InitializedEntity::InitializeTemporary(LHSExpr->getType());
07915     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
07916     ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
07917                                       MultiExprArg(&RHSExpr, 1));
07918     if (Init.isInvalid())
07919       return Init;
07920     RHSExpr = Init.take();
07921   }
07922 
07923   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
07924   QualType ResultTy;     // Result type of the binary operator.
07925   // The following two variables are used for compound assignment operators
07926   QualType CompLHSTy;    // Type of LHS after promotions for computation
07927   QualType CompResultTy; // Type of computation result
07928   ExprValueKind VK = VK_RValue;
07929   ExprObjectKind OK = OK_Ordinary;
07930 
07931   switch (Opc) {
07932   case BO_Assign:
07933     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
07934     if (getLangOpts().CPlusPlus &&
07935         LHS.get()->getObjectKind() != OK_ObjCProperty) {
07936       VK = LHS.get()->getValueKind();
07937       OK = LHS.get()->getObjectKind();
07938     }
07939     if (!ResultTy.isNull())
07940       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
07941     break;
07942   case BO_PtrMemD:
07943   case BO_PtrMemI:
07944     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
07945                                             Opc == BO_PtrMemI);
07946     break;
07947   case BO_Mul:
07948   case BO_Div:
07949     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
07950                                            Opc == BO_Div);
07951     break;
07952   case BO_Rem:
07953     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
07954     break;
07955   case BO_Add:
07956     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
07957     break;
07958   case BO_Sub:
07959     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
07960     break;
07961   case BO_Shl:
07962   case BO_Shr:
07963     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
07964     break;
07965   case BO_LE:
07966   case BO_LT:
07967   case BO_GE:
07968   case BO_GT:
07969     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
07970     break;
07971   case BO_EQ:
07972   case BO_NE:
07973     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
07974     break;
07975   case BO_And:
07976   case BO_Xor:
07977   case BO_Or:
07978     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
07979     break;
07980   case BO_LAnd:
07981   case BO_LOr:
07982     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
07983     break;
07984   case BO_MulAssign:
07985   case BO_DivAssign:
07986     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
07987                                                Opc == BO_DivAssign);
07988     CompLHSTy = CompResultTy;
07989     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
07990       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
07991     break;
07992   case BO_RemAssign:
07993     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
07994     CompLHSTy = CompResultTy;
07995     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
07996       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
07997     break;
07998   case BO_AddAssign:
07999     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
08000     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
08001       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
08002     break;
08003   case BO_SubAssign:
08004     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
08005     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
08006       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
08007     break;
08008   case BO_ShlAssign:
08009   case BO_ShrAssign:
08010     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
08011     CompLHSTy = CompResultTy;
08012     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
08013       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
08014     break;
08015   case BO_AndAssign:
08016   case BO_XorAssign:
08017   case BO_OrAssign:
08018     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
08019     CompLHSTy = CompResultTy;
08020     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
08021       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
08022     break;
08023   case BO_Comma:
08024     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
08025     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
08026       VK = RHS.get()->getValueKind();
08027       OK = RHS.get()->getObjectKind();
08028     }
08029     break;
08030   }
08031   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
08032     return ExprError();
08033 
08034   // Check for array bounds violations for both sides of the BinaryOperator
08035   CheckArrayAccess(LHS.get());
08036   CheckArrayAccess(RHS.get());
08037 
08038   if (CompResultTy.isNull())
08039     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
08040                                               ResultTy, VK, OK, OpLoc));
08041   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
08042       OK_ObjCProperty) {
08043     VK = VK_LValue;
08044     OK = LHS.get()->getObjectKind();
08045   }
08046   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
08047                                                     ResultTy, VK, OK, CompLHSTy,
08048                                                     CompResultTy, OpLoc));
08049 }
08050 
08051 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
08052 /// operators are mixed in a way that suggests that the programmer forgot that
08053 /// comparison operators have higher precedence. The most typical example of
08054 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
08055 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
08056                                       SourceLocation OpLoc, Expr *LHSExpr,
08057                                       Expr *RHSExpr) {
08058   typedef BinaryOperator BinOp;
08059   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
08060                 RHSopc = static_cast<BinOp::Opcode>(-1);
08061   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
08062     LHSopc = BO->getOpcode();
08063   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
08064     RHSopc = BO->getOpcode();
08065 
08066   // Subs are not binary operators.
08067   if (LHSopc == -1 && RHSopc == -1)
08068     return;
08069 
08070   // Bitwise operations are sometimes used as eager logical ops.
08071   // Don't diagnose this.
08072   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
08073       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
08074     return;
08075 
08076   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
08077   bool isRightComp = BinOp::isComparisonOp(RHSopc);
08078   if (!isLeftComp && !isRightComp) return;
08079 
08080   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
08081                                                    OpLoc)
08082                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
08083   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
08084                                  : BinOp::getOpcodeStr(RHSopc);
08085   SourceRange ParensRange = isLeftComp ?
08086       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
08087                   RHSExpr->getLocEnd())
08088     : SourceRange(LHSExpr->getLocStart(),
08089                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
08090 
08091   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
08092     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
08093   SuggestParentheses(Self, OpLoc,
08094     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
08095     RHSExpr->getSourceRange());
08096   SuggestParentheses(Self, OpLoc,
08097     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
08098     ParensRange);
08099 }
08100 
08101 /// \brief It accepts a '&' expr that is inside a '|' one.
08102 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
08103 /// in parentheses.
08104 static void
08105 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
08106                                        BinaryOperator *Bop) {
08107   assert(Bop->getOpcode() == BO_And);
08108   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
08109       << Bop->getSourceRange() << OpLoc;
08110   SuggestParentheses(Self, Bop->getOperatorLoc(),
08111     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
08112     Bop->getSourceRange());
08113 }
08114 
08115 /// \brief It accepts a '&&' expr that is inside a '||' one.
08116 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
08117 /// in parentheses.
08118 static void
08119 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
08120                                        BinaryOperator *Bop) {
08121   assert(Bop->getOpcode() == BO_LAnd);
08122   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
08123       << Bop->getSourceRange() << OpLoc;
08124   SuggestParentheses(Self, Bop->getOperatorLoc(),
08125     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
08126     Bop->getSourceRange());
08127 }
08128 
08129 /// \brief Returns true if the given expression can be evaluated as a constant
08130 /// 'true'.
08131 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
08132   bool Res;
08133   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
08134 }
08135 
08136 /// \brief Returns true if the given expression can be evaluated as a constant
08137 /// 'false'.
08138 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
08139   bool Res;
08140   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
08141 }
08142 
08143 /// \brief Look for '&&' in the left hand of a '||' expr.
08144 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
08145                                              Expr *LHSExpr, Expr *RHSExpr) {
08146   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
08147     if (Bop->getOpcode() == BO_LAnd) {
08148       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
08149       if (EvaluatesAsFalse(S, RHSExpr))
08150         return;
08151       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
08152       if (!EvaluatesAsTrue(S, Bop->getLHS()))
08153         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
08154     } else if (Bop->getOpcode() == BO_LOr) {
08155       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
08156         // If it's "a || b && 1 || c" we didn't warn earlier for
08157         // "a || b && 1", but warn now.
08158         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
08159           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
08160       }
08161     }
08162   }
08163 }
08164 
08165 /// \brief Look for '&&' in the right hand of a '||' expr.
08166 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
08167                                              Expr *LHSExpr, Expr *RHSExpr) {
08168   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
08169     if (Bop->getOpcode() == BO_LAnd) {
08170       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
08171       if (EvaluatesAsFalse(S, LHSExpr))
08172         return;
08173       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
08174       if (!EvaluatesAsTrue(S, Bop->getRHS()))
08175         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
08176     }
08177   }
08178 }
08179 
08180 /// \brief Look for '&' in the left or right hand of a '|' expr.
08181 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
08182                                              Expr *OrArg) {
08183   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
08184     if (Bop->getOpcode() == BO_And)
08185       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
08186   }
08187 }
08188 
08189 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
08190 /// precedence.
08191 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
08192                                     SourceLocation OpLoc, Expr *LHSExpr,
08193                                     Expr *RHSExpr){
08194   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
08195   if (BinaryOperator::isBitwiseOp(Opc))
08196     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
08197 
08198   // Diagnose "arg1 & arg2 | arg3"
08199   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
08200     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
08201     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
08202   }
08203 
08204   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
08205   // We don't warn for 'assert(a || b && "bad")' since this is safe.
08206   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
08207     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
08208     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
08209   }
08210 }
08211 
08212 // Binary Operators.  'Tok' is the token for the operator.
08213 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
08214                             tok::TokenKind Kind,
08215                             Expr *LHSExpr, Expr *RHSExpr) {
08216   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
08217   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
08218   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
08219 
08220   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
08221   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
08222 
08223   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
08224 }
08225 
08226 /// Build an overloaded binary operator expression in the given scope.
08227 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
08228                                        BinaryOperatorKind Opc,
08229                                        Expr *LHS, Expr *RHS) {
08230   // Find all of the overloaded operators visible from this
08231   // point. We perform both an operator-name lookup from the local
08232   // scope and an argument-dependent lookup based on the types of
08233   // the arguments.
08234   UnresolvedSet<16> Functions;
08235   OverloadedOperatorKind OverOp
08236     = BinaryOperator::getOverloadedOperator(Opc);
08237   if (Sc && OverOp != OO_None)
08238     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
08239                                    RHS->getType(), Functions);
08240 
08241   // Build the (potentially-overloaded, potentially-dependent)
08242   // binary operation.
08243   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
08244 }
08245 
08246 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
08247                             BinaryOperatorKind Opc,
08248                             Expr *LHSExpr, Expr *RHSExpr) {
08249   // We want to end up calling one of checkPseudoObjectAssignment
08250   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
08251   // both expressions are overloadable or either is type-dependent),
08252   // or CreateBuiltinBinOp (in any other case).  We also want to get
08253   // any placeholder types out of the way.
08254 
08255   // Handle pseudo-objects in the LHS.
08256   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
08257     // Assignments with a pseudo-object l-value need special analysis.
08258     if (pty->getKind() == BuiltinType::PseudoObject &&
08259         BinaryOperator::isAssignmentOp(Opc))
08260       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
08261 
08262     // Don't resolve overloads if the other type is overloadable.
08263     if (pty->getKind() == BuiltinType::Overload) {
08264       // We can't actually test that if we still have a placeholder,
08265       // though.  Fortunately, none of the exceptions we see in that
08266       // code below are valid when the LHS is an overload set.  Note
08267       // that an overload set can be dependently-typed, but it never
08268       // instantiates to having an overloadable type.
08269       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
08270       if (resolvedRHS.isInvalid()) return ExprError();
08271       RHSExpr = resolvedRHS.take();
08272 
08273       if (RHSExpr->isTypeDependent() ||
08274           RHSExpr->getType()->isOverloadableType())
08275         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08276     }
08277         
08278     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
08279     if (LHS.isInvalid()) return ExprError();
08280     LHSExpr = LHS.take();
08281   }
08282 
08283   // Handle pseudo-objects in the RHS.
08284   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
08285     // An overload in the RHS can potentially be resolved by the type
08286     // being assigned to.
08287     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
08288       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
08289         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08290 
08291       if (LHSExpr->getType()->isOverloadableType())
08292         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08293 
08294       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
08295     }
08296 
08297     // Don't resolve overloads if the other type is overloadable.
08298     if (pty->getKind() == BuiltinType::Overload &&
08299         LHSExpr->getType()->isOverloadableType())
08300       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08301 
08302     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
08303     if (!resolvedRHS.isUsable()) return ExprError();
08304     RHSExpr = resolvedRHS.take();
08305   }
08306 
08307   if (getLangOpts().CPlusPlus) {
08308     // If either expression is type-dependent, always build an
08309     // overloaded op.
08310     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
08311       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08312 
08313     // Otherwise, build an overloaded op if either expression has an
08314     // overloadable type.
08315     if (LHSExpr->getType()->isOverloadableType() ||
08316         RHSExpr->getType()->isOverloadableType())
08317       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
08318   }
08319 
08320   // Build a built-in binary operation.
08321   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
08322 }
08323 
08324 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
08325                                       UnaryOperatorKind Opc,
08326                                       Expr *InputExpr) {
08327   ExprResult Input = Owned(InputExpr);
08328   ExprValueKind VK = VK_RValue;
08329   ExprObjectKind OK = OK_Ordinary;
08330   QualType resultType;
08331   switch (Opc) {
08332   case UO_PreInc:
08333   case UO_PreDec:
08334   case UO_PostInc:
08335   case UO_PostDec:
08336     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
08337                                                 Opc == UO_PreInc ||
08338                                                 Opc == UO_PostInc,
08339                                                 Opc == UO_PreInc ||
08340                                                 Opc == UO_PreDec);
08341     break;
08342   case UO_AddrOf:
08343     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
08344     break;
08345   case UO_Deref: {
08346     Input = DefaultFunctionArrayLvalueConversion(Input.take());
08347     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
08348     break;
08349   }
08350   case UO_Plus:
08351   case UO_Minus:
08352     Input = UsualUnaryConversions(Input.take());
08353     if (Input.isInvalid()) return ExprError();
08354     resultType = Input.get()->getType();
08355     if (resultType->isDependentType())
08356       break;
08357     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
08358         resultType->isVectorType()) 
08359       break;
08360     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
08361              resultType->isEnumeralType())
08362       break;
08363     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
08364              Opc == UO_Plus &&
08365              resultType->isPointerType())
08366       break;
08367 
08368     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
08369       << resultType << Input.get()->getSourceRange());
08370 
08371   case UO_Not: // bitwise complement
08372     Input = UsualUnaryConversions(Input.take());
08373     if (Input.isInvalid()) return ExprError();
08374     resultType = Input.get()->getType();
08375     if (resultType->isDependentType())
08376       break;
08377     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
08378     if (resultType->isComplexType() || resultType->isComplexIntegerType())
08379       // C99 does not support '~' for complex conjugation.
08380       Diag(OpLoc, diag::ext_integer_complement_complex)
08381         << resultType << Input.get()->getSourceRange();
08382     else if (resultType->hasIntegerRepresentation())
08383       break;
08384     else {
08385       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
08386         << resultType << Input.get()->getSourceRange());
08387     }
08388     break;
08389 
08390   case UO_LNot: // logical negation
08391     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
08392     Input = DefaultFunctionArrayLvalueConversion(Input.take());
08393     if (Input.isInvalid()) return ExprError();
08394     resultType = Input.get()->getType();
08395 
08396     // Though we still have to promote half FP to float...
08397     if (resultType->isHalfType()) {
08398       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
08399       resultType = Context.FloatTy;
08400     }
08401 
08402     if (resultType->isDependentType())
08403       break;
08404     if (resultType->isScalarType()) {
08405       // C99 6.5.3.3p1: ok, fallthrough;
08406       if (Context.getLangOpts().CPlusPlus) {
08407         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
08408         // operand contextually converted to bool.
08409         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
08410                                   ScalarTypeToBooleanCastKind(resultType));
08411       }
08412     } else if (resultType->isExtVectorType()) {
08413       // Vector logical not returns the signed variant of the operand type.
08414       resultType = GetSignedVectorType(resultType);
08415       break;
08416     } else {
08417       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
08418         << resultType << Input.get()->getSourceRange());
08419     }
08420     
08421     // LNot always has type int. C99 6.5.3.3p5.
08422     // In C++, it's bool. C++ 5.3.1p8
08423     resultType = Context.getLogicalOperationType();
08424     break;
08425   case UO_Real:
08426   case UO_Imag:
08427     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
08428     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
08429     // complex l-values to ordinary l-values and all other values to r-values.
08430     if (Input.isInvalid()) return ExprError();
08431     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
08432       if (Input.get()->getValueKind() != VK_RValue &&
08433           Input.get()->getObjectKind() == OK_Ordinary)
08434         VK = Input.get()->getValueKind();
08435     } else if (!getLangOpts().CPlusPlus) {
08436       // In C, a volatile scalar is read by __imag. In C++, it is not.
08437       Input = DefaultLvalueConversion(Input.take());
08438     }
08439     break;
08440   case UO_Extension:
08441     resultType = Input.get()->getType();
08442     VK = Input.get()->getValueKind();
08443     OK = Input.get()->getObjectKind();
08444     break;
08445   }
08446   if (resultType.isNull() || Input.isInvalid())
08447     return ExprError();
08448 
08449   // Check for array bounds violations in the operand of the UnaryOperator,
08450   // except for the '*' and '&' operators that have to be handled specially
08451   // by CheckArrayAccess (as there are special cases like &array[arraysize]
08452   // that are explicitly defined as valid by the standard).
08453   if (Opc != UO_AddrOf && Opc != UO_Deref)
08454     CheckArrayAccess(Input.get());
08455 
08456   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
08457                                            VK, OK, OpLoc));
08458 }
08459 
08460 /// \brief Determine whether the given expression is a qualified member
08461 /// access expression, of a form that could be turned into a pointer to member
08462 /// with the address-of operator.
08463 static bool isQualifiedMemberAccess(Expr *E) {
08464   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
08465     if (!DRE->getQualifier())
08466       return false;
08467     
08468     ValueDecl *VD = DRE->getDecl();
08469     if (!VD->isCXXClassMember())
08470       return false;
08471     
08472     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
08473       return true;
08474     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
08475       return Method->isInstance();
08476       
08477     return false;
08478   }
08479   
08480   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
08481     if (!ULE->getQualifier())
08482       return false;
08483     
08484     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
08485                                            DEnd = ULE->decls_end();
08486          D != DEnd; ++D) {
08487       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
08488         if (Method->isInstance())
08489           return true;
08490       } else {
08491         // Overload set does not contain methods.
08492         break;
08493       }
08494     }
08495     
08496     return false;
08497   }
08498   
08499   return false;
08500 }
08501 
08502 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
08503                               UnaryOperatorKind Opc, Expr *Input) {
08504   // First things first: handle placeholders so that the
08505   // overloaded-operator check considers the right type.
08506   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
08507     // Increment and decrement of pseudo-object references.
08508     if (pty->getKind() == BuiltinType::PseudoObject &&
08509         UnaryOperator::isIncrementDecrementOp(Opc))
08510       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
08511 
08512     // extension is always a builtin operator.
08513     if (Opc == UO_Extension)
08514       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
08515 
08516     // & gets special logic for several kinds of placeholder.
08517     // The builtin code knows what to do.
08518     if (Opc == UO_AddrOf &&
08519         (pty->getKind() == BuiltinType::Overload ||
08520          pty->getKind() == BuiltinType::UnknownAny ||
08521          pty->getKind() == BuiltinType::BoundMember))
08522       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
08523 
08524     // Anything else needs to be handled now.
08525     ExprResult Result = CheckPlaceholderExpr(Input);
08526     if (Result.isInvalid()) return ExprError();
08527     Input = Result.take();
08528   }
08529 
08530   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
08531       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
08532       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
08533     // Find all of the overloaded operators visible from this
08534     // point. We perform both an operator-name lookup from the local
08535     // scope and an argument-dependent lookup based on the types of
08536     // the arguments.
08537     UnresolvedSet<16> Functions;
08538     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
08539     if (S && OverOp != OO_None)
08540       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
08541                                    Functions);
08542 
08543     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
08544   }
08545 
08546   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
08547 }
08548 
08549 // Unary Operators.  'Tok' is the token for the operator.
08550 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
08551                               tok::TokenKind Op, Expr *Input) {
08552   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
08553 }
08554 
08555 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
08556 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
08557                                 LabelDecl *TheDecl) {
08558   TheDecl->setUsed();
08559   // Create the AST node.  The address of a label always has type 'void*'.
08560   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
08561                                        Context.getPointerType(Context.VoidTy)));
08562 }
08563 
08564 /// Given the last statement in a statement-expression, check whether
08565 /// the result is a producing expression (like a call to an
08566 /// ns_returns_retained function) and, if so, rebuild it to hoist the
08567 /// release out of the full-expression.  Otherwise, return null.
08568 /// Cannot fail.
08569 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
08570   // Should always be wrapped with one of these.
08571   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
08572   if (!cleanups) return 0;
08573 
08574   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
08575   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
08576     return 0;
08577 
08578   // Splice out the cast.  This shouldn't modify any interesting
08579   // features of the statement.
08580   Expr *producer = cast->getSubExpr();
08581   assert(producer->getType() == cast->getType());
08582   assert(producer->getValueKind() == cast->getValueKind());
08583   cleanups->setSubExpr(producer);
08584   return cleanups;
08585 }
08586 
08587 void Sema::ActOnStartStmtExpr() {
08588   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
08589 }
08590 
08591 void Sema::ActOnStmtExprError() {
08592   // Note that function is also called by TreeTransform when leaving a
08593   // StmtExpr scope without rebuilding anything.
08594 
08595   DiscardCleanupsInEvaluationContext();
08596   PopExpressionEvaluationContext();
08597 }
08598 
08599 ExprResult
08600 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
08601                     SourceLocation RPLoc) { // "({..})"
08602   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
08603   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
08604 
08605   if (hasAnyUnrecoverableErrorsInThisFunction())
08606     DiscardCleanupsInEvaluationContext();
08607   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
08608   PopExpressionEvaluationContext();
08609 
08610   bool isFileScope
08611     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
08612   if (isFileScope)
08613     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
08614 
08615   // FIXME: there are a variety of strange constraints to enforce here, for
08616   // example, it is not possible to goto into a stmt expression apparently.
08617   // More semantic analysis is needed.
08618 
08619   // If there are sub stmts in the compound stmt, take the type of the last one
08620   // as the type of the stmtexpr.
08621   QualType Ty = Context.VoidTy;
08622   bool StmtExprMayBindToTemp = false;
08623   if (!Compound->body_empty()) {
08624     Stmt *LastStmt = Compound->body_back();
08625     LabelStmt *LastLabelStmt = 0;
08626     // If LastStmt is a label, skip down through into the body.
08627     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
08628       LastLabelStmt = Label;
08629       LastStmt = Label->getSubStmt();
08630     }
08631 
08632     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
08633       // Do function/array conversion on the last expression, but not
08634       // lvalue-to-rvalue.  However, initialize an unqualified type.
08635       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
08636       if (LastExpr.isInvalid())
08637         return ExprError();
08638       Ty = LastExpr.get()->getType().getUnqualifiedType();
08639 
08640       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
08641         // In ARC, if the final expression ends in a consume, splice
08642         // the consume out and bind it later.  In the alternate case
08643         // (when dealing with a retainable type), the result
08644         // initialization will create a produce.  In both cases the
08645         // result will be +1, and we'll need to balance that out with
08646         // a bind.
08647         if (Expr *rebuiltLastStmt
08648               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
08649           LastExpr = rebuiltLastStmt;
08650         } else {
08651           LastExpr = PerformCopyInitialization(
08652                             InitializedEntity::InitializeResult(LPLoc, 
08653                                                                 Ty,
08654                                                                 false),
08655                                                    SourceLocation(),
08656                                                LastExpr);
08657         }
08658 
08659         if (LastExpr.isInvalid())
08660           return ExprError();
08661         if (LastExpr.get() != 0) {
08662           if (!LastLabelStmt)
08663             Compound->setLastStmt(LastExpr.take());
08664           else
08665             LastLabelStmt->setSubStmt(LastExpr.take());
08666           StmtExprMayBindToTemp = true;
08667         }
08668       }
08669     }
08670   }
08671 
08672   // FIXME: Check that expression type is complete/non-abstract; statement
08673   // expressions are not lvalues.
08674   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
08675   if (StmtExprMayBindToTemp)
08676     return MaybeBindToTemporary(ResStmtExpr);
08677   return Owned(ResStmtExpr);
08678 }
08679 
08680 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
08681                                       TypeSourceInfo *TInfo,
08682                                       OffsetOfComponent *CompPtr,
08683                                       unsigned NumComponents,
08684                                       SourceLocation RParenLoc) {
08685   QualType ArgTy = TInfo->getType();
08686   bool Dependent = ArgTy->isDependentType();
08687   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
08688   
08689   // We must have at least one component that refers to the type, and the first
08690   // one is known to be a field designator.  Verify that the ArgTy represents
08691   // a struct/union/class.
08692   if (!Dependent && !ArgTy->isRecordType())
08693     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
08694                        << ArgTy << TypeRange);
08695   
08696   // Type must be complete per C99 7.17p3 because a declaring a variable
08697   // with an incomplete type would be ill-formed.
08698   if (!Dependent 
08699       && RequireCompleteType(BuiltinLoc, ArgTy,
08700                              diag::err_offsetof_incomplete_type, TypeRange))
08701     return ExprError();
08702   
08703   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
08704   // GCC extension, diagnose them.
08705   // FIXME: This diagnostic isn't actually visible because the location is in
08706   // a system header!
08707   if (NumComponents != 1)
08708     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
08709       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
08710   
08711   bool DidWarnAboutNonPOD = false;
08712   QualType CurrentType = ArgTy;
08713   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
08714   SmallVector<OffsetOfNode, 4> Comps;
08715   SmallVector<Expr*, 4> Exprs;
08716   for (unsigned i = 0; i != NumComponents; ++i) {
08717     const OffsetOfComponent &OC = CompPtr[i];
08718     if (OC.isBrackets) {
08719       // Offset of an array sub-field.  TODO: Should we allow vector elements?
08720       if (!CurrentType->isDependentType()) {
08721         const ArrayType *AT = Context.getAsArrayType(CurrentType);
08722         if(!AT)
08723           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
08724                            << CurrentType);
08725         CurrentType = AT->getElementType();
08726       } else
08727         CurrentType = Context.DependentTy;
08728       
08729       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
08730       if (IdxRval.isInvalid())
08731         return ExprError();
08732       Expr *Idx = IdxRval.take();
08733 
08734       // The expression must be an integral expression.
08735       // FIXME: An integral constant expression?
08736       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
08737           !Idx->getType()->isIntegerType())
08738         return ExprError(Diag(Idx->getLocStart(),
08739                               diag::err_typecheck_subscript_not_integer)
08740                          << Idx->getSourceRange());
08741 
08742       // Record this array index.
08743       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
08744       Exprs.push_back(Idx);
08745       continue;
08746     }
08747     
08748     // Offset of a field.
08749     if (CurrentType->isDependentType()) {
08750       // We have the offset of a field, but we can't look into the dependent
08751       // type. Just record the identifier of the field.
08752       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
08753       CurrentType = Context.DependentTy;
08754       continue;
08755     }
08756     
08757     // We need to have a complete type to look into.
08758     if (RequireCompleteType(OC.LocStart, CurrentType,
08759                             diag::err_offsetof_incomplete_type))
08760       return ExprError();
08761     
08762     // Look for the designated field.
08763     const RecordType *RC = CurrentType->getAs<RecordType>();
08764     if (!RC) 
08765       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
08766                        << CurrentType);
08767     RecordDecl *RD = RC->getDecl();
08768     
08769     // C++ [lib.support.types]p5:
08770     //   The macro offsetof accepts a restricted set of type arguments in this
08771     //   International Standard. type shall be a POD structure or a POD union
08772     //   (clause 9).
08773     // C++11 [support.types]p4:
08774     //   If type is not a standard-layout class (Clause 9), the results are
08775     //   undefined.
08776     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
08777       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
08778       unsigned DiagID =
08779         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
08780                             : diag::warn_offsetof_non_pod_type;
08781 
08782       if (!IsSafe && !DidWarnAboutNonPOD &&
08783           DiagRuntimeBehavior(BuiltinLoc, 0,
08784                               PDiag(DiagID)
08785                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
08786                               << CurrentType))
08787         DidWarnAboutNonPOD = true;
08788     }
08789     
08790     // Look for the field.
08791     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
08792     LookupQualifiedName(R, RD);
08793     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
08794     IndirectFieldDecl *IndirectMemberDecl = 0;
08795     if (!MemberDecl) {
08796       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
08797         MemberDecl = IndirectMemberDecl->getAnonField();
08798     }
08799 
08800     if (!MemberDecl)
08801       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
08802                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
08803                                                               OC.LocEnd));
08804     
08805     // C99 7.17p3:
08806     //   (If the specified member is a bit-field, the behavior is undefined.)
08807     //
08808     // We diagnose this as an error.
08809     if (MemberDecl->isBitField()) {
08810       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
08811         << MemberDecl->getDeclName()
08812         << SourceRange(BuiltinLoc, RParenLoc);
08813       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
08814       return ExprError();
08815     }
08816 
08817     RecordDecl *Parent = MemberDecl->getParent();
08818     if (IndirectMemberDecl)
08819       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
08820 
08821     // If the member was found in a base class, introduce OffsetOfNodes for
08822     // the base class indirections.
08823     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
08824                        /*DetectVirtual=*/false);
08825     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
08826       CXXBasePath &Path = Paths.front();
08827       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
08828            B != BEnd; ++B)
08829         Comps.push_back(OffsetOfNode(B->Base));
08830     }
08831 
08832     if (IndirectMemberDecl) {
08833       for (IndirectFieldDecl::chain_iterator FI =
08834            IndirectMemberDecl->chain_begin(),
08835            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
08836         assert(isa<FieldDecl>(*FI));
08837         Comps.push_back(OffsetOfNode(OC.LocStart,
08838                                      cast<FieldDecl>(*FI), OC.LocEnd));
08839       }
08840     } else
08841       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
08842 
08843     CurrentType = MemberDecl->getType().getNonReferenceType(); 
08844   }
08845   
08846   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 
08847                                     TInfo, Comps.data(), Comps.size(),
08848                                     Exprs.data(), Exprs.size(), RParenLoc));  
08849 }
08850 
08851 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
08852                                       SourceLocation BuiltinLoc,
08853                                       SourceLocation TypeLoc,
08854                                       ParsedType ParsedArgTy,
08855                                       OffsetOfComponent *CompPtr,
08856                                       unsigned NumComponents,
08857                                       SourceLocation RParenLoc) {
08858   
08859   TypeSourceInfo *ArgTInfo;
08860   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
08861   if (ArgTy.isNull())
08862     return ExprError();
08863 
08864   if (!ArgTInfo)
08865     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
08866 
08867   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
08868                               RParenLoc);
08869 }
08870 
08871 
08872 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
08873                                  Expr *CondExpr,
08874                                  Expr *LHSExpr, Expr *RHSExpr,
08875                                  SourceLocation RPLoc) {
08876   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
08877 
08878   ExprValueKind VK = VK_RValue;
08879   ExprObjectKind OK = OK_Ordinary;
08880   QualType resType;
08881   bool ValueDependent = false;
08882   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
08883     resType = Context.DependentTy;
08884     ValueDependent = true;
08885   } else {
08886     // The conditional expression is required to be a constant expression.
08887     llvm::APSInt condEval(32);
08888     ExprResult CondICE
08889       = VerifyIntegerConstantExpression(CondExpr, &condEval,
08890           diag::err_typecheck_choose_expr_requires_constant, false);
08891     if (CondICE.isInvalid())
08892       return ExprError();
08893     CondExpr = CondICE.take();
08894 
08895     // If the condition is > zero, then the AST type is the same as the LSHExpr.
08896     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
08897 
08898     resType = ActiveExpr->getType();
08899     ValueDependent = ActiveExpr->isValueDependent();
08900     VK = ActiveExpr->getValueKind();
08901     OK = ActiveExpr->getObjectKind();
08902   }
08903 
08904   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
08905                                         resType, VK, OK, RPLoc,
08906                                         resType->isDependentType(),
08907                                         ValueDependent));
08908 }
08909 
08910 //===----------------------------------------------------------------------===//
08911 // Clang Extensions.
08912 //===----------------------------------------------------------------------===//
08913 
08914 /// ActOnBlockStart - This callback is invoked when a block literal is started.
08915 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
08916   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
08917   PushBlockScope(CurScope, Block);
08918   CurContext->addDecl(Block);
08919   if (CurScope)
08920     PushDeclContext(CurScope, Block);
08921   else
08922     CurContext = Block;
08923 
08924   getCurBlock()->HasImplicitReturnType = true;
08925 
08926   // Enter a new evaluation context to insulate the block from any
08927   // cleanups from the enclosing full-expression.
08928   PushExpressionEvaluationContext(PotentiallyEvaluated);  
08929 }
08930 
08931 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
08932   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
08933   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
08934   BlockScopeInfo *CurBlock = getCurBlock();
08935 
08936   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
08937   QualType T = Sig->getType();
08938 
08939   // GetTypeForDeclarator always produces a function type for a block
08940   // literal signature.  Furthermore, it is always a FunctionProtoType
08941   // unless the function was written with a typedef.
08942   assert(T->isFunctionType() &&
08943          "GetTypeForDeclarator made a non-function block signature");
08944 
08945   // Look for an explicit signature in that function type.
08946   FunctionProtoTypeLoc ExplicitSignature;
08947 
08948   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
08949   if (isa<FunctionProtoTypeLoc>(tmp)) {
08950     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
08951 
08952     // Check whether that explicit signature was synthesized by
08953     // GetTypeForDeclarator.  If so, don't save that as part of the
08954     // written signature.
08955     if (ExplicitSignature.getLocalRangeBegin() ==
08956         ExplicitSignature.getLocalRangeEnd()) {
08957       // This would be much cheaper if we stored TypeLocs instead of
08958       // TypeSourceInfos.
08959       TypeLoc Result = ExplicitSignature.getResultLoc();
08960       unsigned Size = Result.getFullDataSize();
08961       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
08962       Sig->getTypeLoc().initializeFullCopy(Result, Size);
08963 
08964       ExplicitSignature = FunctionProtoTypeLoc();
08965     }
08966   }
08967 
08968   CurBlock->TheDecl->setSignatureAsWritten(Sig);
08969   CurBlock->FunctionType = T;
08970 
08971   const FunctionType *Fn = T->getAs<FunctionType>();
08972   QualType RetTy = Fn->getResultType();
08973   bool isVariadic =
08974     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
08975 
08976   CurBlock->TheDecl->setIsVariadic(isVariadic);
08977 
08978   // Don't allow returning a objc interface by value.
08979   if (RetTy->isObjCObjectType()) {
08980     Diag(ParamInfo.getLocStart(),
08981          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
08982     return;
08983   }
08984 
08985   // Context.DependentTy is used as a placeholder for a missing block
08986   // return type.  TODO:  what should we do with declarators like:
08987   //   ^ * { ... }
08988   // If the answer is "apply template argument deduction"....
08989   if (RetTy != Context.DependentTy) {
08990     CurBlock->ReturnType = RetTy;
08991     CurBlock->TheDecl->setBlockMissingReturnType(false);
08992     CurBlock->HasImplicitReturnType = false;
08993   }
08994 
08995   // Push block parameters from the declarator if we had them.
08996   SmallVector<ParmVarDecl*, 8> Params;
08997   if (ExplicitSignature) {
08998     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
08999       ParmVarDecl *Param = ExplicitSignature.getArg(I);
09000       if (Param->getIdentifier() == 0 &&
09001           !Param->isImplicit() &&
09002           !Param->isInvalidDecl() &&
09003           !getLangOpts().CPlusPlus)
09004         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
09005       Params.push_back(Param);
09006     }
09007 
09008   // Fake up parameter variables if we have a typedef, like
09009   //   ^ fntype { ... }
09010   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
09011     for (FunctionProtoType::arg_type_iterator
09012            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
09013       ParmVarDecl *Param =
09014         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
09015                                    ParamInfo.getLocStart(),
09016                                    *I);
09017       Params.push_back(Param);
09018     }
09019   }
09020 
09021   // Set the parameters on the block decl.
09022   if (!Params.empty()) {
09023     CurBlock->TheDecl->setParams(Params);
09024     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
09025                              CurBlock->TheDecl->param_end(),
09026                              /*CheckParameterNames=*/false);
09027   }
09028   
09029   // Finally we can process decl attributes.
09030   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
09031 
09032   // Put the parameter variables in scope.  We can bail out immediately
09033   // if we don't have any.
09034   if (Params.empty())
09035     return;
09036 
09037   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
09038          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
09039     (*AI)->setOwningFunction(CurBlock->TheDecl);
09040 
09041     // If this has an identifier, add it to the scope stack.
09042     if ((*AI)->getIdentifier()) {
09043       CheckShadow(CurBlock->TheScope, *AI);
09044 
09045       PushOnScopeChains(*AI, CurBlock->TheScope);
09046     }
09047   }
09048 }
09049 
09050 /// ActOnBlockError - If there is an error parsing a block, this callback
09051 /// is invoked to pop the information about the block from the action impl.
09052 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
09053   // Leave the expression-evaluation context.
09054   DiscardCleanupsInEvaluationContext();
09055   PopExpressionEvaluationContext();
09056 
09057   // Pop off CurBlock, handle nested blocks.
09058   PopDeclContext();
09059   PopFunctionScopeInfo();
09060 }
09061 
09062 /// ActOnBlockStmtExpr - This is called when the body of a block statement
09063 /// literal was successfully completed.  ^(int x){...}
09064 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
09065                                     Stmt *Body, Scope *CurScope) {
09066   // If blocks are disabled, emit an error.
09067   if (!LangOpts.Blocks)
09068     Diag(CaretLoc, diag::err_blocks_disable);
09069 
09070   // Leave the expression-evaluation context.
09071   if (hasAnyUnrecoverableErrorsInThisFunction())
09072     DiscardCleanupsInEvaluationContext();
09073   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
09074   PopExpressionEvaluationContext();
09075 
09076   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
09077   
09078   PopDeclContext();
09079 
09080   QualType RetTy = Context.VoidTy;
09081   if (!BSI->ReturnType.isNull())
09082     RetTy = BSI->ReturnType;
09083 
09084   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
09085   QualType BlockTy;
09086 
09087   // Set the captured variables on the block.
09088   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
09089   SmallVector<BlockDecl::Capture, 4> Captures;
09090   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
09091     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
09092     if (Cap.isThisCapture())
09093       continue;
09094     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
09095                               Cap.isNested(), Cap.getCopyExpr());
09096     Captures.push_back(NewCap);
09097   }
09098   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
09099                             BSI->CXXThisCaptureIndex != 0);
09100 
09101   // If the user wrote a function type in some form, try to use that.
09102   if (!BSI->FunctionType.isNull()) {
09103     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
09104 
09105     FunctionType::ExtInfo Ext = FTy->getExtInfo();
09106     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
09107     
09108     // Turn protoless block types into nullary block types.
09109     if (isa<FunctionNoProtoType>(FTy)) {
09110       FunctionProtoType::ExtProtoInfo EPI;
09111       EPI.ExtInfo = Ext;
09112       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
09113 
09114     // Otherwise, if we don't need to change anything about the function type,
09115     // preserve its sugar structure.
09116     } else if (FTy->getResultType() == RetTy &&
09117                (!NoReturn || FTy->getNoReturnAttr())) {
09118       BlockTy = BSI->FunctionType;
09119 
09120     // Otherwise, make the minimal modifications to the function type.
09121     } else {
09122       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
09123       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
09124       EPI.TypeQuals = 0; // FIXME: silently?
09125       EPI.ExtInfo = Ext;
09126       BlockTy = Context.getFunctionType(RetTy,
09127                                         FPT->arg_type_begin(),
09128                                         FPT->getNumArgs(),
09129                                         EPI);
09130     }
09131 
09132   // If we don't have a function type, just build one from nothing.
09133   } else {
09134     FunctionProtoType::ExtProtoInfo EPI;
09135     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
09136     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
09137   }
09138 
09139   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
09140                            BSI->TheDecl->param_end());
09141   BlockTy = Context.getBlockPointerType(BlockTy);
09142 
09143   // If needed, diagnose invalid gotos and switches in the block.
09144   if (getCurFunction()->NeedsScopeChecking() &&
09145       !hasAnyUnrecoverableErrorsInThisFunction())
09146     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
09147 
09148   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
09149 
09150   computeNRVO(Body, getCurBlock());
09151   
09152   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
09153   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
09154   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
09155 
09156   // If the block isn't obviously global, i.e. it captures anything at
09157   // all, then we need to do a few things in the surrounding context:
09158   if (Result->getBlockDecl()->hasCaptures()) {
09159     // First, this expression has a new cleanup object.
09160     ExprCleanupObjects.push_back(Result->getBlockDecl());
09161     ExprNeedsCleanups = true;
09162 
09163     // It also gets a branch-protected scope if any of the captured
09164     // variables needs destruction.
09165     for (BlockDecl::capture_const_iterator
09166            ci = Result->getBlockDecl()->capture_begin(),
09167            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
09168       const VarDecl *var = ci->getVariable();
09169       if (var->getType().isDestructedType() != QualType::DK_none) {
09170         getCurFunction()->setHasBranchProtectedScope();
09171         break;
09172       }
09173     }
09174   }
09175 
09176   return Owned(Result);
09177 }
09178 
09179 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
09180                                         Expr *E, ParsedType Ty,
09181                                         SourceLocation RPLoc) {
09182   TypeSourceInfo *TInfo;
09183   GetTypeFromParser(Ty, &TInfo);
09184   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
09185 }
09186 
09187 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
09188                                 Expr *E, TypeSourceInfo *TInfo,
09189                                 SourceLocation RPLoc) {
09190   Expr *OrigExpr = E;
09191 
09192   // Get the va_list type
09193   QualType VaListType = Context.getBuiltinVaListType();
09194   if (VaListType->isArrayType()) {
09195     // Deal with implicit array decay; for example, on x86-64,
09196     // va_list is an array, but it's supposed to decay to
09197     // a pointer for va_arg.
09198     VaListType = Context.getArrayDecayedType(VaListType);
09199     // Make sure the input expression also decays appropriately.
09200     ExprResult Result = UsualUnaryConversions(E);
09201     if (Result.isInvalid())
09202       return ExprError();
09203     E = Result.take();
09204   } else {
09205     // Otherwise, the va_list argument must be an l-value because
09206     // it is modified by va_arg.
09207     if (!E->isTypeDependent() &&
09208         CheckForModifiableLvalue(E, BuiltinLoc, *this))
09209       return ExprError();
09210   }
09211 
09212   if (!E->isTypeDependent() &&
09213       !Context.hasSameType(VaListType, E->getType())) {
09214     return ExprError(Diag(E->getLocStart(),
09215                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
09216       << OrigExpr->getType() << E->getSourceRange());
09217   }
09218 
09219   if (!TInfo->getType()->isDependentType()) {
09220     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
09221                             diag::err_second_parameter_to_va_arg_incomplete,
09222                             TInfo->getTypeLoc()))
09223       return ExprError();
09224 
09225     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
09226                                TInfo->getType(),
09227                                diag::err_second_parameter_to_va_arg_abstract,
09228                                TInfo->getTypeLoc()))
09229       return ExprError();
09230 
09231     if (!TInfo->getType().isPODType(Context)) {
09232       Diag(TInfo->getTypeLoc().getBeginLoc(),
09233            TInfo->getType()->isObjCLifetimeType()
09234              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
09235              : diag::warn_second_parameter_to_va_arg_not_pod)
09236         << TInfo->getType()
09237         << TInfo->getTypeLoc().getSourceRange();
09238     }
09239 
09240     // Check for va_arg where arguments of the given type will be promoted
09241     // (i.e. this va_arg is guaranteed to have undefined behavior).
09242     QualType PromoteType;
09243     if (TInfo->getType()->isPromotableIntegerType()) {
09244       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
09245       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
09246         PromoteType = QualType();
09247     }
09248     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
09249       PromoteType = Context.DoubleTy;
09250     if (!PromoteType.isNull())
09251       Diag(TInfo->getTypeLoc().getBeginLoc(),
09252           diag::warn_second_parameter_to_va_arg_never_compatible)
09253         << TInfo->getType()
09254         << PromoteType
09255         << TInfo->getTypeLoc().getSourceRange();
09256   }
09257 
09258   QualType T = TInfo->getType().getNonLValueExprType(Context);
09259   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
09260 }
09261 
09262 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
09263   // The type of __null will be int or long, depending on the size of
09264   // pointers on the target.
09265   QualType Ty;
09266   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
09267   if (pw == Context.getTargetInfo().getIntWidth())
09268     Ty = Context.IntTy;
09269   else if (pw == Context.getTargetInfo().getLongWidth())
09270     Ty = Context.LongTy;
09271   else if (pw == Context.getTargetInfo().getLongLongWidth())
09272     Ty = Context.LongLongTy;
09273   else {
09274     llvm_unreachable("I don't know size of pointer!");
09275   }
09276 
09277   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
09278 }
09279 
09280 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
09281                                            Expr *SrcExpr, FixItHint &Hint) {
09282   if (!SemaRef.getLangOpts().ObjC1)
09283     return;
09284 
09285   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
09286   if (!PT)
09287     return;
09288 
09289   // Check if the destination is of type 'id'.
09290   if (!PT->isObjCIdType()) {
09291     // Check if the destination is the 'NSString' interface.
09292     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
09293     if (!ID || !ID->getIdentifier()->isStr("NSString"))
09294       return;
09295   }
09296 
09297   // Ignore any parens, implicit casts (should only be
09298   // array-to-pointer decays), and not-so-opaque values.  The last is
09299   // important for making this trigger for property assignments.
09300   SrcExpr = SrcExpr->IgnoreParenImpCasts();
09301   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
09302     if (OV->getSourceExpr())
09303       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
09304 
09305   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
09306   if (!SL || !SL->isAscii())
09307     return;
09308 
09309   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
09310 }
09311 
09312 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
09313                                     SourceLocation Loc,
09314                                     QualType DstType, QualType SrcType,
09315                                     Expr *SrcExpr, AssignmentAction Action,
09316                                     bool *Complained) {
09317   if (Complained)
09318     *Complained = false;
09319 
09320   // Decode the result (notice that AST's are still created for extensions).
09321   bool CheckInferredResultType = false;
09322   bool isInvalid = false;
09323   unsigned DiagKind = 0;
09324   FixItHint Hint;
09325   ConversionFixItGenerator ConvHints;
09326   bool MayHaveConvFixit = false;
09327   bool MayHaveFunctionDiff = false;
09328 
09329   switch (ConvTy) {
09330   case Compatible: return false;
09331   case PointerToInt:
09332     DiagKind = diag::ext_typecheck_convert_pointer_int;
09333     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
09334     MayHaveConvFixit = true;
09335     break;
09336   case IntToPointer:
09337     DiagKind = diag::ext_typecheck_convert_int_pointer;
09338     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
09339     MayHaveConvFixit = true;
09340     break;
09341   case IncompatiblePointer:
09342     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
09343     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
09344     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
09345       SrcType->isObjCObjectPointerType();
09346     if (Hint.isNull() && !CheckInferredResultType) {
09347       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
09348     }
09349     MayHaveConvFixit = true;
09350     break;
09351   case IncompatiblePointerSign:
09352     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
09353     break;
09354   case FunctionVoidPointer:
09355     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
09356     break;
09357   case IncompatiblePointerDiscardsQualifiers: {
09358     // Perform array-to-pointer decay if necessary.
09359     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
09360 
09361     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
09362     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
09363     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
09364       DiagKind = diag::err_typecheck_incompatible_address_space;
09365       break;
09366 
09367 
09368     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
09369       DiagKind = diag::err_typecheck_incompatible_ownership;
09370       break;
09371     }
09372 
09373     llvm_unreachable("unknown error case for discarding qualifiers!");
09374     // fallthrough
09375   }
09376   case CompatiblePointerDiscardsQualifiers:
09377     // If the qualifiers lost were because we were applying the
09378     // (deprecated) C++ conversion from a string literal to a char*
09379     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
09380     // Ideally, this check would be performed in
09381     // checkPointerTypesForAssignment. However, that would require a
09382     // bit of refactoring (so that the second argument is an
09383     // expression, rather than a type), which should be done as part
09384     // of a larger effort to fix checkPointerTypesForAssignment for
09385     // C++ semantics.
09386     if (getLangOpts().CPlusPlus &&
09387         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
09388       return false;
09389     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
09390     break;
09391   case IncompatibleNestedPointerQualifiers:
09392     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
09393     break;
09394   case IntToBlockPointer:
09395     DiagKind = diag::err_int_to_block_pointer;
09396     break;
09397   case IncompatibleBlockPointer:
09398     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
09399     break;
09400   case IncompatibleObjCQualifiedId:
09401     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
09402     // it can give a more specific diagnostic.
09403     DiagKind = diag::warn_incompatible_qualified_id;
09404     break;
09405   case IncompatibleVectors:
09406     DiagKind = diag::warn_incompatible_vectors;
09407     break;
09408   case IncompatibleObjCWeakRef:
09409     DiagKind = diag::err_arc_weak_unavailable_assign;
09410     break;
09411   case Incompatible:
09412     DiagKind = diag::err_typecheck_convert_incompatible;
09413     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
09414     MayHaveConvFixit = true;
09415     isInvalid = true;
09416     MayHaveFunctionDiff = true;
09417     break;
09418   }
09419 
09420   QualType FirstType, SecondType;
09421   switch (Action) {
09422   case AA_Assigning:
09423   case AA_Initializing:
09424     // The destination type comes first.
09425     FirstType = DstType;
09426     SecondType = SrcType;
09427     break;
09428 
09429   case AA_Returning:
09430   case AA_Passing:
09431   case AA_Converting:
09432   case AA_Sending:
09433   case AA_Casting:
09434     // The source type comes first.
09435     FirstType = SrcType;
09436     SecondType = DstType;
09437     break;
09438   }
09439 
09440   PartialDiagnostic FDiag = PDiag(DiagKind);
09441   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
09442 
09443   // If we can fix the conversion, suggest the FixIts.
09444   assert(ConvHints.isNull() || Hint.isNull());
09445   if (!ConvHints.isNull()) {
09446     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
09447          HE = ConvHints.Hints.end(); HI != HE; ++HI)
09448       FDiag << *HI;
09449   } else {
09450     FDiag << Hint;
09451   }
09452   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
09453 
09454   if (MayHaveFunctionDiff)
09455     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
09456 
09457   Diag(Loc, FDiag);
09458 
09459   if (SecondType == Context.OverloadTy)
09460     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
09461                               FirstType);
09462 
09463   if (CheckInferredResultType)
09464     EmitRelatedResultTypeNote(SrcExpr);
09465   
09466   if (Complained)
09467     *Complained = true;
09468   return isInvalid;
09469 }
09470 
09471 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
09472                                                  llvm::APSInt *Result) {
09473   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
09474   public:
09475     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
09476       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
09477     }
09478   } Diagnoser;
09479   
09480   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
09481 }
09482 
09483 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
09484                                                  llvm::APSInt *Result,
09485                                                  unsigned DiagID,
09486                                                  bool AllowFold) {
09487   class IDDiagnoser : public VerifyICEDiagnoser {
09488     unsigned DiagID;
09489     
09490   public:
09491     IDDiagnoser(unsigned DiagID)
09492       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
09493     
09494     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
09495       S.Diag(Loc, DiagID) << SR;
09496     }
09497   } Diagnoser(DiagID);
09498   
09499   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
09500 }
09501 
09502 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
09503                                             SourceRange SR) {
09504   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
09505 }
09506 
09507 ExprResult
09508 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
09509                                       VerifyICEDiagnoser &Diagnoser,
09510                                       bool AllowFold) {
09511   SourceLocation DiagLoc = E->getLocStart();
09512 
09513   if (getLangOpts().CPlusPlus0x) {
09514     // C++11 [expr.const]p5:
09515     //   If an expression of literal class type is used in a context where an
09516     //   integral constant expression is required, then that class type shall
09517     //   have a single non-explicit conversion function to an integral or
09518     //   unscoped enumeration type
09519     ExprResult Converted;
09520     if (!Diagnoser.Suppress) {
09521       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
09522       public:
09523         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
09524         
09525         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
09526                                                  QualType T) {
09527           return S.Diag(Loc, diag::err_ice_not_integral) << T;
09528         }
09529         
09530         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
09531                                                      SourceLocation Loc,
09532                                                      QualType T) {
09533           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
09534         }
09535         
09536         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
09537                                                        SourceLocation Loc,
09538                                                        QualType T,
09539                                                        QualType ConvTy) {
09540           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
09541         }
09542         
09543         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
09544                                                    CXXConversionDecl *Conv,
09545                                                    QualType ConvTy) {
09546           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
09547                    << ConvTy->isEnumeralType() << ConvTy;
09548         }
09549         
09550         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
09551                                                     QualType T) {
09552           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
09553         }
09554         
09555         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
09556                                                 CXXConversionDecl *Conv,
09557                                                 QualType ConvTy) {
09558           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
09559                    << ConvTy->isEnumeralType() << ConvTy;
09560         }
09561         
09562         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
09563                                                      SourceLocation Loc,
09564                                                      QualType T,
09565                                                      QualType ConvTy) {
09566           return DiagnosticBuilder::getEmpty();
09567         }
09568       } ConvertDiagnoser;
09569 
09570       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
09571                                                      ConvertDiagnoser,
09572                                              /*AllowScopedEnumerations*/ false);
09573     } else {
09574       // The caller wants to silently enquire whether this is an ICE. Don't
09575       // produce any diagnostics if it isn't.
09576       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
09577       public:
09578         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
09579         
09580         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
09581                                                  QualType T) {
09582           return DiagnosticBuilder::getEmpty();
09583         }
09584         
09585         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
09586                                                      SourceLocation Loc,
09587                                                      QualType T) {
09588           return DiagnosticBuilder::getEmpty();
09589         }
09590         
09591         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
09592                                                        SourceLocation Loc,
09593                                                        QualType T,
09594                                                        QualType ConvTy) {
09595           return DiagnosticBuilder::getEmpty();
09596         }
09597         
09598         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
09599                                                    CXXConversionDecl *Conv,
09600                                                    QualType ConvTy) {
09601           return DiagnosticBuilder::getEmpty();
09602         }
09603         
09604         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
09605                                                     QualType T) {
09606           return DiagnosticBuilder::getEmpty();
09607         }
09608         
09609         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
09610                                                 CXXConversionDecl *Conv,
09611                                                 QualType ConvTy) {
09612           return DiagnosticBuilder::getEmpty();
09613         }
09614         
09615         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
09616                                                      SourceLocation Loc,
09617                                                      QualType T,
09618                                                      QualType ConvTy) {
09619           return DiagnosticBuilder::getEmpty();
09620         }
09621       } ConvertDiagnoser;
09622       
09623       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
09624                                                      ConvertDiagnoser, false);
09625     }
09626     if (Converted.isInvalid())
09627       return Converted;
09628     E = Converted.take();
09629     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
09630       return ExprError();
09631   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
09632     // An ICE must be of integral or unscoped enumeration type.
09633     if (!Diagnoser.Suppress)
09634       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
09635     return ExprError();
09636   }
09637 
09638   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
09639   // in the non-ICE case.
09640   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
09641     if (Result)
09642       *Result = E->EvaluateKnownConstInt(Context);
09643     return Owned(E);
09644   }
09645 
09646   Expr::EvalResult EvalResult;
09647   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
09648   EvalResult.Diag = &Notes;
09649 
09650   // Try to evaluate the expression, and produce diagnostics explaining why it's
09651   // not a constant expression as a side-effect.
09652   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
09653                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
09654 
09655   // In C++11, we can rely on diagnostics being produced for any expression
09656   // which is not a constant expression. If no diagnostics were produced, then
09657   // this is a constant expression.
09658   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
09659     if (Result)
09660       *Result = EvalResult.Val.getInt();
09661     return Owned(E);
09662   }
09663 
09664   // If our only note is the usual "invalid subexpression" note, just point
09665   // the caret at its location rather than producing an essentially
09666   // redundant note.
09667   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
09668         diag::note_invalid_subexpr_in_const_expr) {
09669     DiagLoc = Notes[0].first;
09670     Notes.clear();
09671   }
09672 
09673   if (!Folded || !AllowFold) {
09674     if (!Diagnoser.Suppress) {
09675       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
09676       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
09677         Diag(Notes[I].first, Notes[I].second);
09678     }
09679 
09680     return ExprError();
09681   }
09682 
09683   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
09684   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
09685     Diag(Notes[I].first, Notes[I].second);
09686 
09687   if (Result)
09688     *Result = EvalResult.Val.getInt();
09689   return Owned(E);
09690 }
09691 
09692 namespace {
09693   // Handle the case where we conclude a expression which we speculatively
09694   // considered to be unevaluated is actually evaluated.
09695   class TransformToPE : public TreeTransform<TransformToPE> {
09696     typedef TreeTransform<TransformToPE> BaseTransform;
09697 
09698   public:
09699     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
09700 
09701     // Make sure we redo semantic analysis
09702     bool AlwaysRebuild() { return true; }
09703 
09704     // Make sure we handle LabelStmts correctly.
09705     // FIXME: This does the right thing, but maybe we need a more general
09706     // fix to TreeTransform?
09707     StmtResult TransformLabelStmt(LabelStmt *S) {
09708       S->getDecl()->setStmt(0);
09709       return BaseTransform::TransformLabelStmt(S);
09710     }
09711 
09712     // We need to special-case DeclRefExprs referring to FieldDecls which
09713     // are not part of a member pointer formation; normal TreeTransforming
09714     // doesn't catch this case because of the way we represent them in the AST.
09715     // FIXME: This is a bit ugly; is it really the best way to handle this
09716     // case?
09717     //
09718     // Error on DeclRefExprs referring to FieldDecls.
09719     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
09720       if (isa<FieldDecl>(E->getDecl()) &&
09721           SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
09722         return SemaRef.Diag(E->getLocation(),
09723                             diag::err_invalid_non_static_member_use)
09724             << E->getDecl() << E->getSourceRange();
09725 
09726       return BaseTransform::TransformDeclRefExpr(E);
09727     }
09728 
09729     // Exception: filter out member pointer formation
09730     ExprResult TransformUnaryOperator(UnaryOperator *E) {
09731       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
09732         return E;
09733 
09734       return BaseTransform::TransformUnaryOperator(E);
09735     }
09736 
09737     ExprResult TransformLambdaExpr(LambdaExpr *E) {
09738       // Lambdas never need to be transformed.
09739       return E;
09740     }
09741   };
09742 }
09743 
09744 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
09745   assert(ExprEvalContexts.back().Context == Unevaluated &&
09746          "Should only transform unevaluated expressions");
09747   ExprEvalContexts.back().Context =
09748       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
09749   if (ExprEvalContexts.back().Context == Unevaluated)
09750     return E;
09751   return TransformToPE(*this).TransformExpr(E);
09752 }
09753 
09754 void
09755 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
09756                                       Decl *LambdaContextDecl,
09757                                       bool IsDecltype) {
09758   ExprEvalContexts.push_back(
09759              ExpressionEvaluationContextRecord(NewContext,
09760                                                ExprCleanupObjects.size(),
09761                                                ExprNeedsCleanups,
09762                                                LambdaContextDecl,
09763                                                IsDecltype));
09764   ExprNeedsCleanups = false;
09765   if (!MaybeODRUseExprs.empty())
09766     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
09767 }
09768 
09769 void Sema::PopExpressionEvaluationContext() {
09770   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
09771 
09772   if (!Rec.Lambdas.empty()) {
09773     if (Rec.Context == Unevaluated) {
09774       // C++11 [expr.prim.lambda]p2:
09775       //   A lambda-expression shall not appear in an unevaluated operand
09776       //   (Clause 5).
09777       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
09778         Diag(Rec.Lambdas[I]->getLocStart(), 
09779              diag::err_lambda_unevaluated_operand);
09780     } else {
09781       // Mark the capture expressions odr-used. This was deferred
09782       // during lambda expression creation.
09783       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
09784         LambdaExpr *Lambda = Rec.Lambdas[I];
09785         for (LambdaExpr::capture_init_iterator 
09786                   C = Lambda->capture_init_begin(),
09787                CEnd = Lambda->capture_init_end();
09788              C != CEnd; ++C) {
09789           MarkDeclarationsReferencedInExpr(*C);
09790         }
09791       }
09792     }
09793   }
09794 
09795   // When are coming out of an unevaluated context, clear out any
09796   // temporaries that we may have created as part of the evaluation of
09797   // the expression in that context: they aren't relevant because they
09798   // will never be constructed.
09799   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
09800     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
09801                              ExprCleanupObjects.end());
09802     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
09803     CleanupVarDeclMarking();
09804     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
09805   // Otherwise, merge the contexts together.
09806   } else {
09807     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
09808     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
09809                             Rec.SavedMaybeODRUseExprs.end());
09810   }
09811 
09812   // Pop the current expression evaluation context off the stack.
09813   ExprEvalContexts.pop_back();
09814 }
09815 
09816 void Sema::DiscardCleanupsInEvaluationContext() {
09817   ExprCleanupObjects.erase(
09818          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
09819          ExprCleanupObjects.end());
09820   ExprNeedsCleanups = false;
09821   MaybeODRUseExprs.clear();
09822 }
09823 
09824 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
09825   if (!E->getType()->isVariablyModifiedType())
09826     return E;
09827   return TranformToPotentiallyEvaluated(E);
09828 }
09829 
09830 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
09831   // Do not mark anything as "used" within a dependent context; wait for
09832   // an instantiation.
09833   if (SemaRef.CurContext->isDependentContext())
09834     return false;
09835 
09836   switch (SemaRef.ExprEvalContexts.back().Context) {
09837     case Sema::Unevaluated:
09838       // We are in an expression that is not potentially evaluated; do nothing.
09839       // (Depending on how you read the standard, we actually do need to do
09840       // something here for null pointer constants, but the standard's
09841       // definition of a null pointer constant is completely crazy.)
09842       return false;
09843 
09844     case Sema::ConstantEvaluated:
09845     case Sema::PotentiallyEvaluated:
09846       // We are in a potentially evaluated expression (or a constant-expression
09847       // in C++03); we need to do implicit template instantiation, implicitly
09848       // define class members, and mark most declarations as used.
09849       return true;
09850 
09851     case Sema::PotentiallyEvaluatedIfUsed:
09852       // Referenced declarations will only be used if the construct in the
09853       // containing expression is used.
09854       return false;
09855   }
09856   llvm_unreachable("Invalid context");
09857 }
09858 
09859 /// \brief Mark a function referenced, and check whether it is odr-used
09860 /// (C++ [basic.def.odr]p2, C99 6.9p3)
09861 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
09862   assert(Func && "No function?");
09863 
09864   Func->setReferenced();
09865 
09866   // Don't mark this function as used multiple times, unless it's a constexpr
09867   // function which we need to instantiate.
09868   if (Func->isUsed(false) &&
09869       !(Func->isConstexpr() && !Func->getBody() &&
09870         Func->isImplicitlyInstantiable()))
09871     return;
09872 
09873   if (!IsPotentiallyEvaluatedContext(*this))
09874     return;
09875 
09876   // Note that this declaration has been used.
09877   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
09878     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
09879       if (Constructor->isDefaultConstructor()) {
09880         if (Constructor->isTrivial())
09881           return;
09882         if (!Constructor->isUsed(false))
09883           DefineImplicitDefaultConstructor(Loc, Constructor);
09884       } else if (Constructor->isCopyConstructor()) {
09885         if (!Constructor->isUsed(false))
09886           DefineImplicitCopyConstructor(Loc, Constructor);
09887       } else if (Constructor->isMoveConstructor()) {
09888         if (!Constructor->isUsed(false))
09889           DefineImplicitMoveConstructor(Loc, Constructor);
09890       }
09891     }
09892 
09893     MarkVTableUsed(Loc, Constructor->getParent());
09894   } else if (CXXDestructorDecl *Destructor =
09895                  dyn_cast<CXXDestructorDecl>(Func)) {
09896     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
09897         !Destructor->isUsed(false))
09898       DefineImplicitDestructor(Loc, Destructor);
09899     if (Destructor->isVirtual())
09900       MarkVTableUsed(Loc, Destructor->getParent());
09901   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
09902     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
09903         MethodDecl->isOverloadedOperator() &&
09904         MethodDecl->getOverloadedOperator() == OO_Equal) {
09905       if (!MethodDecl->isUsed(false)) {
09906         if (MethodDecl->isCopyAssignmentOperator())
09907           DefineImplicitCopyAssignment(Loc, MethodDecl);
09908         else
09909           DefineImplicitMoveAssignment(Loc, MethodDecl);
09910       }
09911     } else if (isa<CXXConversionDecl>(MethodDecl) &&
09912                MethodDecl->getParent()->isLambda()) {
09913       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
09914       if (Conversion->isLambdaToBlockPointerConversion())
09915         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
09916       else
09917         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
09918     } else if (MethodDecl->isVirtual())
09919       MarkVTableUsed(Loc, MethodDecl->getParent());
09920   }
09921 
09922   // Recursive functions should be marked when used from another function.
09923   // FIXME: Is this really right?
09924   if (CurContext == Func) return;
09925 
09926   // Instantiate the exception specification for any function which is
09927   // used: CodeGen will need it.
09928   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
09929   if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
09930     InstantiateExceptionSpec(Loc, Func);
09931 
09932   // Implicit instantiation of function templates and member functions of
09933   // class templates.
09934   if (Func->isImplicitlyInstantiable()) {
09935     bool AlreadyInstantiated = false;
09936     SourceLocation PointOfInstantiation = Loc;
09937     if (FunctionTemplateSpecializationInfo *SpecInfo
09938                               = Func->getTemplateSpecializationInfo()) {
09939       if (SpecInfo->getPointOfInstantiation().isInvalid())
09940         SpecInfo->setPointOfInstantiation(Loc);
09941       else if (SpecInfo->getTemplateSpecializationKind()
09942                  == TSK_ImplicitInstantiation) {
09943         AlreadyInstantiated = true;
09944         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
09945       }
09946     } else if (MemberSpecializationInfo *MSInfo
09947                                 = Func->getMemberSpecializationInfo()) {
09948       if (MSInfo->getPointOfInstantiation().isInvalid())
09949         MSInfo->setPointOfInstantiation(Loc);
09950       else if (MSInfo->getTemplateSpecializationKind()
09951                  == TSK_ImplicitInstantiation) {
09952         AlreadyInstantiated = true;
09953         PointOfInstantiation = MSInfo->getPointOfInstantiation();
09954       }
09955     }
09956 
09957     if (!AlreadyInstantiated || Func->isConstexpr()) {
09958       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
09959           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
09960         PendingLocalImplicitInstantiations.push_back(
09961             std::make_pair(Func, PointOfInstantiation));
09962       else if (Func->isConstexpr())
09963         // Do not defer instantiations of constexpr functions, to avoid the
09964         // expression evaluator needing to call back into Sema if it sees a
09965         // call to such a function.
09966         InstantiateFunctionDefinition(PointOfInstantiation, Func);
09967       else {
09968         PendingInstantiations.push_back(std::make_pair(Func,
09969                                                        PointOfInstantiation));
09970         // Notify the consumer that a function was implicitly instantiated.
09971         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
09972       }
09973     }
09974   } else {
09975     // Walk redefinitions, as some of them may be instantiable.
09976     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
09977          e(Func->redecls_end()); i != e; ++i) {
09978       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
09979         MarkFunctionReferenced(Loc, *i);
09980     }
09981   }
09982 
09983   // Keep track of used but undefined functions.
09984   if (!Func->isPure() && !Func->hasBody() &&
09985       Func->getLinkage() != ExternalLinkage) {
09986     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
09987     if (old.isInvalid()) old = Loc;
09988   }
09989 
09990   Func->setUsed(true);
09991 }
09992 
09993 static void
09994 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
09995                                    VarDecl *var, DeclContext *DC) {
09996   DeclContext *VarDC = var->getDeclContext();
09997 
09998   //  If the parameter still belongs to the translation unit, then
09999   //  we're actually just using one parameter in the declaration of
10000   //  the next.
10001   if (isa<ParmVarDecl>(var) &&
10002       isa<TranslationUnitDecl>(VarDC))
10003     return;
10004 
10005   // For C code, don't diagnose about capture if we're not actually in code
10006   // right now; it's impossible to write a non-constant expression outside of
10007   // function context, so we'll get other (more useful) diagnostics later.
10008   //
10009   // For C++, things get a bit more nasty... it would be nice to suppress this
10010   // diagnostic for certain cases like using a local variable in an array bound
10011   // for a member of a local class, but the correct predicate is not obvious.
10012   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10013     return;
10014 
10015   if (isa<CXXMethodDecl>(VarDC) &&
10016       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10017     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10018       << var->getIdentifier();
10019   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10020     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10021       << var->getIdentifier() << fn->getDeclName();
10022   } else if (isa<BlockDecl>(VarDC)) {
10023     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10024       << var->getIdentifier();
10025   } else {
10026     // FIXME: Is there any other context where a local variable can be
10027     // declared?
10028     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10029       << var->getIdentifier();
10030   }
10031 
10032   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10033     << var->getIdentifier();
10034 
10035   // FIXME: Add additional diagnostic info about class etc. which prevents
10036   // capture.
10037 }
10038 
10039 /// \brief Capture the given variable in the given lambda expression.
10040 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10041                                   VarDecl *Var, QualType FieldType, 
10042                                   QualType DeclRefType,
10043                                   SourceLocation Loc,
10044                                   bool RefersToEnclosingLocal) {
10045   CXXRecordDecl *Lambda = LSI->Lambda;
10046 
10047   // Build the non-static data member.
10048   FieldDecl *Field
10049     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10050                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10051                         0, false, false);
10052   Field->setImplicit(true);
10053   Field->setAccess(AS_private);
10054   Lambda->addDecl(Field);
10055 
10056   // C++11 [expr.prim.lambda]p21:
10057   //   When the lambda-expression is evaluated, the entities that
10058   //   are captured by copy are used to direct-initialize each
10059   //   corresponding non-static data member of the resulting closure
10060   //   object. (For array members, the array elements are
10061   //   direct-initialized in increasing subscript order.) These
10062   //   initializations are performed in the (unspecified) order in
10063   //   which the non-static data members are declared.
10064       
10065   // Introduce a new evaluation context for the initialization, so
10066   // that temporaries introduced as part of the capture are retained
10067   // to be re-"exported" from the lambda expression itself.
10068   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10069 
10070   // C++ [expr.prim.labda]p12:
10071   //   An entity captured by a lambda-expression is odr-used (3.2) in
10072   //   the scope containing the lambda-expression.
10073   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 
10074                                           DeclRefType, VK_LValue, Loc);
10075   Var->setReferenced(true);
10076   Var->setUsed(true);
10077 
10078   // When the field has array type, create index variables for each
10079   // dimension of the array. We use these index variables to subscript
10080   // the source array, and other clients (e.g., CodeGen) will perform
10081   // the necessary iteration with these index variables.
10082   SmallVector<VarDecl *, 4> IndexVariables;
10083   QualType BaseType = FieldType;
10084   QualType SizeType = S.Context.getSizeType();
10085   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10086   while (const ConstantArrayType *Array
10087                         = S.Context.getAsConstantArrayType(BaseType)) {
10088     // Create the iteration variable for this array index.
10089     IdentifierInfo *IterationVarName = 0;
10090     {
10091       SmallString<8> Str;
10092       llvm::raw_svector_ostream OS(Str);
10093       OS << "__i" << IndexVariables.size();
10094       IterationVarName = &S.Context.Idents.get(OS.str());
10095     }
10096     VarDecl *IterationVar
10097       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10098                         IterationVarName, SizeType,
10099                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10100                         SC_None, SC_None);
10101     IndexVariables.push_back(IterationVar);
10102     LSI->ArrayIndexVars.push_back(IterationVar);
10103     
10104     // Create a reference to the iteration variable.
10105     ExprResult IterationVarRef
10106       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10107     assert(!IterationVarRef.isInvalid() &&
10108            "Reference to invented variable cannot fail!");
10109     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10110     assert(!IterationVarRef.isInvalid() &&
10111            "Conversion of invented variable cannot fail!");
10112     
10113     // Subscript the array with this iteration variable.
10114     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10115                              Ref, Loc, IterationVarRef.take(), Loc);
10116     if (Subscript.isInvalid()) {
10117       S.CleanupVarDeclMarking();
10118       S.DiscardCleanupsInEvaluationContext();
10119       S.PopExpressionEvaluationContext();
10120       return ExprError();
10121     }
10122 
10123     Ref = Subscript.take();
10124     BaseType = Array->getElementType();
10125   }
10126 
10127   // Construct the entity that we will be initializing. For an array, this
10128   // will be first element in the array, which may require several levels
10129   // of array-subscript entities. 
10130   SmallVector<InitializedEntity, 4> Entities;
10131   Entities.reserve(1 + IndexVariables.size());
10132   Entities.push_back(
10133     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10134   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10135     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10136                                                             0,
10137                                                             Entities.back()));
10138 
10139   InitializationKind InitKind
10140     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10141   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10142   ExprResult Result(true);
10143   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10144     Result = Init.Perform(S, Entities.back(), InitKind, 
10145                           MultiExprArg(S, &Ref, 1));
10146 
10147   // If this initialization requires any cleanups (e.g., due to a
10148   // default argument to a copy constructor), note that for the
10149   // lambda.
10150   if (S.ExprNeedsCleanups)
10151     LSI->ExprNeedsCleanups = true;
10152 
10153   // Exit the expression evaluation context used for the capture.
10154   S.CleanupVarDeclMarking();
10155   S.DiscardCleanupsInEvaluationContext();
10156   S.PopExpressionEvaluationContext();
10157   return Result;
10158 }
10159 
10160 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 
10161                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10162                               bool BuildAndDiagnose, 
10163                               QualType &CaptureType,
10164                               QualType &DeclRefType) {
10165   bool Nested = false;
10166   
10167   DeclContext *DC = CurContext;
10168   if (Var->getDeclContext() == DC) return true;
10169   if (!Var->hasLocalStorage()) return true;
10170 
10171   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10172 
10173   // Walk up the stack to determine whether we can capture the variable,
10174   // performing the "simple" checks that don't depend on type. We stop when
10175   // we've either hit the declared scope of the variable or find an existing
10176   // capture of that variable.
10177   CaptureType = Var->getType();
10178   DeclRefType = CaptureType.getNonReferenceType();
10179   bool Explicit = (Kind != TryCapture_Implicit);
10180   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10181   do {
10182     // Only block literals and lambda expressions can capture; other
10183     // scopes don't work.
10184     DeclContext *ParentDC;
10185     if (isa<BlockDecl>(DC))
10186       ParentDC = DC->getParent();
10187     else if (isa<CXXMethodDecl>(DC) &&
10188              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10189              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10190       ParentDC = DC->getParent()->getParent();
10191     else {
10192       if (BuildAndDiagnose)
10193         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10194       return true;
10195     }
10196 
10197     CapturingScopeInfo *CSI =
10198       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10199 
10200     // Check whether we've already captured it.
10201     if (CSI->CaptureMap.count(Var)) {
10202       // If we found a capture, any subcaptures are nested.
10203       Nested = true;
10204       
10205       // Retrieve the capture type for this variable.
10206       CaptureType = CSI->getCapture(Var).getCaptureType();
10207       
10208       // Compute the type of an expression that refers to this variable.
10209       DeclRefType = CaptureType.getNonReferenceType();
10210       
10211       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10212       if (Cap.isCopyCapture() &&
10213           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10214         DeclRefType.addConst();
10215       break;
10216     }
10217 
10218     bool IsBlock = isa<BlockScopeInfo>(CSI);
10219     bool IsLambda = !IsBlock;
10220 
10221     // Lambdas are not allowed to capture unnamed variables
10222     // (e.g. anonymous unions).
10223     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10224     // assuming that's the intent.
10225     if (IsLambda && !Var->getDeclName()) {
10226       if (BuildAndDiagnose) {
10227         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10228         Diag(Var->getLocation(), diag::note_declared_at);
10229       }
10230       return true;
10231     }
10232 
10233     // Prohibit variably-modified types; they're difficult to deal with.
10234     if (Var->getType()->isVariablyModifiedType()) {
10235       if (BuildAndDiagnose) {
10236         if (IsBlock)
10237           Diag(Loc, diag::err_ref_vm_type);
10238         else
10239           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10240         Diag(Var->getLocation(), diag::note_previous_decl) 
10241           << Var->getDeclName();
10242       }
10243       return true;
10244     }
10245 
10246     // Lambdas are not allowed to capture __block variables; they don't
10247     // support the expected semantics.
10248     if (IsLambda && HasBlocksAttr) {
10249       if (BuildAndDiagnose) {
10250         Diag(Loc, diag::err_lambda_capture_block) 
10251           << Var->getDeclName();
10252         Diag(Var->getLocation(), diag::note_previous_decl) 
10253           << Var->getDeclName();
10254       }
10255       return true;
10256     }
10257 
10258     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10259       // No capture-default
10260       if (BuildAndDiagnose) {
10261         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10262         Diag(Var->getLocation(), diag::note_previous_decl) 
10263           << Var->getDeclName();
10264         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10265              diag::note_lambda_decl);
10266       }
10267       return true;
10268     }
10269 
10270     FunctionScopesIndex--;
10271     DC = ParentDC;
10272     Explicit = false;
10273   } while (!Var->getDeclContext()->Equals(DC));
10274 
10275   // Walk back down the scope stack, computing the type of the capture at
10276   // each step, checking type-specific requirements, and adding captures if
10277   // requested.
10278   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 
10279        ++I) {
10280     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10281     
10282     // Compute the type of the capture and of a reference to the capture within
10283     // this scope.
10284     if (isa<BlockScopeInfo>(CSI)) {
10285       Expr *CopyExpr = 0;
10286       bool ByRef = false;
10287       
10288       // Blocks are not allowed to capture arrays.
10289       if (CaptureType->isArrayType()) {
10290         if (BuildAndDiagnose) {
10291           Diag(Loc, diag::err_ref_array_type);
10292           Diag(Var->getLocation(), diag::note_previous_decl) 
10293           << Var->getDeclName();
10294         }
10295         return true;
10296       }
10297 
10298       // Forbid the block-capture of autoreleasing variables.
10299       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10300         if (BuildAndDiagnose) {
10301           Diag(Loc, diag::err_arc_autoreleasing_capture)
10302             << /*block*/ 0;
10303           Diag(Var->getLocation(), diag::note_previous_decl)
10304             << Var->getDeclName();
10305         }
10306         return true;
10307       }
10308 
10309       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10310         // Block capture by reference does not change the capture or
10311         // declaration reference types.
10312         ByRef = true;
10313       } else {
10314         // Block capture by copy introduces 'const'.
10315         CaptureType = CaptureType.getNonReferenceType().withConst();
10316         DeclRefType = CaptureType;
10317                 
10318         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10319           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10320             // The capture logic needs the destructor, so make sure we mark it.
10321             // Usually this is unnecessary because most local variables have
10322             // their destructors marked at declaration time, but parameters are
10323             // an exception because it's technically only the call site that
10324             // actually requires the destructor.
10325             if (isa<ParmVarDecl>(Var))
10326               FinalizeVarWithDestructor(Var, Record);
10327             
10328             // According to the blocks spec, the capture of a variable from
10329             // the stack requires a const copy constructor.  This is not true
10330             // of the copy/move done to move a __block variable to the heap.
10331             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10332                                                       DeclRefType.withConst(), 
10333                                                       VK_LValue, Loc);
10334             ExprResult Result
10335               = PerformCopyInitialization(
10336                   InitializedEntity::InitializeBlock(Var->getLocation(),
10337                                                      CaptureType, false),
10338                   Loc, Owned(DeclRef));
10339             
10340             // Build a full-expression copy expression if initialization
10341             // succeeded and used a non-trivial constructor.  Recover from
10342             // errors by pretending that the copy isn't necessary.
10343             if (!Result.isInvalid() &&
10344                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10345                    ->isTrivial()) {
10346               Result = MaybeCreateExprWithCleanups(Result);
10347               CopyExpr = Result.take();
10348             }
10349           }
10350         }
10351       }
10352 
10353       // Actually capture the variable.
10354       if (BuildAndDiagnose)
10355         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
10356                         SourceLocation(), CaptureType, CopyExpr);
10357       Nested = true;
10358       continue;
10359     } 
10360     
10361     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10362     
10363     // Determine whether we are capturing by reference or by value.
10364     bool ByRef = false;
10365     if (I == N - 1 && Kind != TryCapture_Implicit) {
10366       ByRef = (Kind == TryCapture_ExplicitByRef);
10367     } else {
10368       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10369     }
10370     
10371     // Compute the type of the field that will capture this variable.
10372     if (ByRef) {
10373       // C++11 [expr.prim.lambda]p15:
10374       //   An entity is captured by reference if it is implicitly or
10375       //   explicitly captured but not captured by copy. It is
10376       //   unspecified whether additional unnamed non-static data
10377       //   members are declared in the closure type for entities
10378       //   captured by reference.
10379       //
10380       // FIXME: It is not clear whether we want to build an lvalue reference
10381       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10382       // to do the former, while EDG does the latter. Core issue 1249 will 
10383       // clarify, but for now we follow GCC because it's a more permissive and
10384       // easily defensible position.
10385       CaptureType = Context.getLValueReferenceType(DeclRefType);
10386     } else {
10387       // C++11 [expr.prim.lambda]p14:
10388       //   For each entity captured by copy, an unnamed non-static
10389       //   data member is declared in the closure type. The
10390       //   declaration order of these members is unspecified. The type
10391       //   of such a data member is the type of the corresponding
10392       //   captured entity if the entity is not a reference to an
10393       //   object, or the referenced type otherwise. [Note: If the
10394       //   captured entity is a reference to a function, the
10395       //   corresponding data member is also a reference to a
10396       //   function. - end note ]
10397       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10398         if (!RefType->getPointeeType()->isFunctionType())
10399           CaptureType = RefType->getPointeeType();
10400       }
10401 
10402       // Forbid the lambda copy-capture of autoreleasing variables.
10403       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10404         if (BuildAndDiagnose) {
10405           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10406           Diag(Var->getLocation(), diag::note_previous_decl)
10407             << Var->getDeclName();
10408         }
10409         return true;
10410       }
10411     }
10412 
10413     // Capture this variable in the lambda.
10414     Expr *CopyExpr = 0;
10415     if (BuildAndDiagnose) {
10416       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10417                                           DeclRefType, Loc,
10418                                           I == N-1);
10419       if (!Result.isInvalid())
10420         CopyExpr = Result.take();
10421     }
10422     
10423     // Compute the type of a reference to this captured variable.
10424     if (ByRef)
10425       DeclRefType = CaptureType.getNonReferenceType();
10426     else {
10427       // C++ [expr.prim.lambda]p5:
10428       //   The closure type for a lambda-expression has a public inline 
10429       //   function call operator [...]. This function call operator is 
10430       //   declared const (9.3.1) if and only if the lambda-expression’s 
10431       //   parameter-declaration-clause is not followed by mutable.
10432       DeclRefType = CaptureType.getNonReferenceType();
10433       if (!LSI->Mutable && !CaptureType->isReferenceType())
10434         DeclRefType.addConst();      
10435     }
10436     
10437     // Add the capture.
10438     if (BuildAndDiagnose)
10439       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10440                       EllipsisLoc, CaptureType, CopyExpr);
10441     Nested = true;
10442   }
10443 
10444   return false;
10445 }
10446 
10447 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10448                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
10449   QualType CaptureType;
10450   QualType DeclRefType;
10451   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10452                             /*BuildAndDiagnose=*/true, CaptureType,
10453                             DeclRefType);
10454 }
10455 
10456 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10457   QualType CaptureType;
10458   QualType DeclRefType;
10459   
10460   // Determine whether we can capture this variable.
10461   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10462                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10463     return QualType();
10464 
10465   return DeclRefType;
10466 }
10467 
10468 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10469                                SourceLocation Loc) {
10470   // Keep track of used but undefined variables.
10471   // FIXME: We shouldn't suppress this warning for static data members.
10472   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10473       Var->getLinkage() != ExternalLinkage &&
10474       !(Var->isStaticDataMember() && Var->hasInit())) {
10475     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10476     if (old.isInvalid()) old = Loc;
10477   }
10478 
10479   SemaRef.tryCaptureVariable(Var, Loc);
10480 
10481   Var->setUsed(true);
10482 }
10483 
10484 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10485   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
10486   // an object that satisfies the requirements for appearing in a
10487   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10488   // is immediately applied."  This function handles the lvalue-to-rvalue
10489   // conversion part.
10490   MaybeODRUseExprs.erase(E->IgnoreParens());
10491 }
10492 
10493 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10494   if (!Res.isUsable())
10495     return Res;
10496 
10497   // If a constant-expression is a reference to a variable where we delay
10498   // deciding whether it is an odr-use, just assume we will apply the
10499   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10500   // (a non-type template argument), we have special handling anyway.
10501   UpdateMarkingForLValueToRValue(Res.get());
10502   return Res;
10503 }
10504 
10505 void Sema::CleanupVarDeclMarking() {
10506   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10507                                         e = MaybeODRUseExprs.end();
10508        i != e; ++i) {
10509     VarDecl *Var;
10510     SourceLocation Loc;
10511     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10512       Var = cast<VarDecl>(DRE->getDecl());
10513       Loc = DRE->getLocation();
10514     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10515       Var = cast<VarDecl>(ME->getMemberDecl());
10516       Loc = ME->getMemberLoc();
10517     } else {
10518       llvm_unreachable("Unexpcted expression");
10519     }
10520 
10521     MarkVarDeclODRUsed(*this, Var, Loc);
10522   }
10523 
10524   MaybeODRUseExprs.clear();
10525 }
10526 
10527 // Mark a VarDecl referenced, and perform the necessary handling to compute
10528 // odr-uses.
10529 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10530                                     VarDecl *Var, Expr *E) {
10531   Var->setReferenced();
10532 
10533   if (!IsPotentiallyEvaluatedContext(SemaRef))
10534     return;
10535 
10536   // Implicit instantiation of static data members of class templates.
10537   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10538     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10539     assert(MSInfo && "Missing member specialization information?");
10540     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10541     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10542         (!AlreadyInstantiated ||
10543          Var->isUsableInConstantExpressions(SemaRef.Context))) {
10544       if (!AlreadyInstantiated) {
10545         // This is a modification of an existing AST node. Notify listeners.
10546         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10547           L->StaticDataMemberInstantiated(Var);
10548         MSInfo->setPointOfInstantiation(Loc);
10549       }
10550       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10551       if (Var->isUsableInConstantExpressions(SemaRef.Context))
10552         // Do not defer instantiations of variables which could be used in a
10553         // constant expression.
10554         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10555       else
10556         SemaRef.PendingInstantiations.push_back(
10557             std::make_pair(Var, PointOfInstantiation));
10558     }
10559   }
10560 
10561   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
10562   // an object that satisfies the requirements for appearing in a
10563   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10564   // is immediately applied."  We check the first part here, and
10565   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10566   // Note that we use the C++11 definition everywhere because nothing in
10567   // C++03 depends on whether we get the C++03 version correct. This does not
10568   // apply to references, since they are not objects.
10569   const VarDecl *DefVD;
10570   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10571       Var->isUsableInConstantExpressions(SemaRef.Context) &&
10572       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10573     SemaRef.MaybeODRUseExprs.insert(E);
10574   else
10575     MarkVarDeclODRUsed(SemaRef, Var, Loc);
10576 }
10577 
10578 /// \brief Mark a variable referenced, and check whether it is odr-used
10579 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10580 /// used directly for normal expressions referring to VarDecl.
10581 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10582   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10583 }
10584 
10585 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10586                                Decl *D, Expr *E) {
10587   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10588     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10589     return;
10590   }
10591 
10592   SemaRef.MarkAnyDeclReferenced(Loc, D);
10593 } 
10594 
10595 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10596 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10597   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10598 }
10599 
10600 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10601 void Sema::MarkMemberReferenced(MemberExpr *E) {
10602   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10603 }
10604 
10605 /// \brief Perform marking for a reference to an arbitrary declaration.  It
10606 /// marks the declaration referenced, and performs odr-use checking for functions
10607 /// and variables. This method should not be used when building an normal
10608 /// expression which refers to a variable.
10609 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10610   if (VarDecl *VD = dyn_cast<VarDecl>(D))
10611     MarkVariableReferenced(Loc, VD);
10612   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10613     MarkFunctionReferenced(Loc, FD);
10614   else
10615     D->setReferenced();
10616 }
10617 
10618 namespace {
10619   // Mark all of the declarations referenced
10620   // FIXME: Not fully implemented yet! We need to have a better understanding
10621   // of when we're entering
10622   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10623     Sema &S;
10624     SourceLocation Loc;
10625 
10626   public:
10627     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10628 
10629     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10630 
10631     bool TraverseTemplateArgument(const TemplateArgument &Arg);
10632     bool TraverseRecordType(RecordType *T);
10633   };
10634 }
10635 
10636 bool MarkReferencedDecls::TraverseTemplateArgument(
10637   const TemplateArgument &Arg) {
10638   if (Arg.getKind() == TemplateArgument::Declaration) {
10639     if (Decl *D = Arg.getAsDecl())
10640       S.MarkAnyDeclReferenced(Loc, D);
10641   }
10642 
10643   return Inherited::TraverseTemplateArgument(Arg);
10644 }
10645 
10646 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10647   if (ClassTemplateSpecializationDecl *Spec
10648                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10649     const TemplateArgumentList &Args = Spec->getTemplateArgs();
10650     return TraverseTemplateArguments(Args.data(), Args.size());
10651   }
10652 
10653   return true;
10654 }
10655 
10656 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10657   MarkReferencedDecls Marker(*this, Loc);
10658   Marker.TraverseType(Context.getCanonicalType(T));
10659 }
10660 
10661 namespace {
10662   /// \brief Helper class that marks all of the declarations referenced by
10663   /// potentially-evaluated subexpressions as "referenced".
10664   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10665     Sema &S;
10666     bool SkipLocalVariables;
10667     
10668   public:
10669     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10670     
10671     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
10672       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
10673     
10674     void VisitDeclRefExpr(DeclRefExpr *E) {
10675       // If we were asked not to visit local variables, don't.
10676       if (SkipLocalVariables) {
10677         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10678           if (VD->hasLocalStorage())
10679             return;
10680       }
10681       
10682       S.MarkDeclRefReferenced(E);
10683     }
10684     
10685     void VisitMemberExpr(MemberExpr *E) {
10686       S.MarkMemberReferenced(E);
10687       Inherited::VisitMemberExpr(E);
10688     }
10689     
10690     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10691       S.MarkFunctionReferenced(E->getLocStart(),
10692             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10693       Visit(E->getSubExpr());
10694     }
10695     
10696     void VisitCXXNewExpr(CXXNewExpr *E) {
10697       if (E->getOperatorNew())
10698         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
10699       if (E->getOperatorDelete())
10700         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
10701       Inherited::VisitCXXNewExpr(E);
10702     }
10703 
10704     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10705       if (E->getOperatorDelete())
10706         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
10707       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10708       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10709         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10710         S.MarkFunctionReferenced(E->getLocStart(), 
10711                                     S.LookupDestructor(Record));
10712       }
10713       
10714       Inherited::VisitCXXDeleteExpr(E);
10715     }
10716     
10717     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10718       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
10719       Inherited::VisitCXXConstructExpr(E);
10720     }
10721     
10722     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10723       Visit(E->getExpr());
10724     }
10725 
10726     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10727       Inherited::VisitImplicitCastExpr(E);
10728 
10729       if (E->getCastKind() == CK_LValueToRValue)
10730         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10731     }
10732   };
10733 }
10734 
10735 /// \brief Mark any declarations that appear within this expression or any
10736 /// potentially-evaluated subexpressions as "referenced".
10737 ///
10738 /// \param SkipLocalVariables If true, don't mark local variables as 
10739 /// 'referenced'.
10740 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
10741                                             bool SkipLocalVariables) {
10742   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
10743 }
10744 
10745 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
10746 /// of the program being compiled.
10747 ///
10748 /// This routine emits the given diagnostic when the code currently being
10749 /// type-checked is "potentially evaluated", meaning that there is a
10750 /// possibility that the code will actually be executable. Code in sizeof()
10751 /// expressions, code used only during overload resolution, etc., are not
10752 /// potentially evaluated. This routine will suppress such diagnostics or,
10753 /// in the absolutely nutty case of potentially potentially evaluated
10754 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
10755 /// later.
10756 ///
10757 /// This routine should be used for all diagnostics that describe the run-time
10758 /// behavior of a program, such as passing a non-POD value through an ellipsis.
10759 /// Failure to do so will likely result in spurious diagnostics or failures
10760 /// during overload resolution or within sizeof/alignof/typeof/typeid.
10761 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
10762                                const PartialDiagnostic &PD) {
10763   switch (ExprEvalContexts.back().Context) {
10764   case Unevaluated:
10765     // The argument will never be evaluated, so don't complain.
10766     break;
10767 
10768   case ConstantEvaluated:
10769     // Relevant diagnostics should be produced by constant evaluation.
10770     break;
10771 
10772   case PotentiallyEvaluated:
10773   case PotentiallyEvaluatedIfUsed:
10774     if (Statement && getCurFunctionOrMethodDecl()) {
10775       FunctionScopes.back()->PossiblyUnreachableDiags.
10776         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
10777     }
10778     else
10779       Diag(Loc, PD);
10780       
10781     return true;
10782   }
10783 
10784   return false;
10785 }
10786 
10787 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10788                                CallExpr *CE, FunctionDecl *FD) {
10789   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10790     return false;
10791 
10792   // If we're inside a decltype's expression, don't check for a valid return
10793   // type or construct temporaries until we know whether this is the last call.
10794   if (ExprEvalContexts.back().IsDecltype) {
10795     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10796     return false;
10797   }
10798 
10799   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
10800     FunctionDecl *FD;
10801     CallExpr *CE;
10802     
10803   public:
10804     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
10805       : FD(FD), CE(CE) { }
10806     
10807     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
10808       if (!FD) {
10809         S.Diag(Loc, diag::err_call_incomplete_return)
10810           << T << CE->getSourceRange();
10811         return;
10812       }
10813       
10814       S.Diag(Loc, diag::err_call_function_incomplete_return)
10815         << CE->getSourceRange() << FD->getDeclName() << T;
10816       S.Diag(FD->getLocation(),
10817              diag::note_function_with_incomplete_return_type_declared_here)
10818         << FD->getDeclName();
10819     }
10820   } Diagnoser(FD, CE);
10821   
10822   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
10823     return true;
10824 
10825   return false;
10826 }
10827 
10828 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
10829 // will prevent this condition from triggering, which is what we want.
10830 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10831   SourceLocation Loc;
10832 
10833   unsigned diagnostic = diag::warn_condition_is_assignment;
10834   bool IsOrAssign = false;
10835 
10836   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
10837     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
10838       return;
10839 
10840     IsOrAssign = Op->getOpcode() == BO_OrAssign;
10841 
10842     // Greylist some idioms by putting them into a warning subcategory.
10843     if (ObjCMessageExpr *ME
10844           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10845       Selector Sel = ME->getSelector();
10846 
10847       // self = [<foo> init...]
10848       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
10849         diagnostic = diag::warn_condition_is_idiomatic_assignment;
10850 
10851       // <foo> = [<bar> nextObject]
10852       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
10853         diagnostic = diag::warn_condition_is_idiomatic_assignment;
10854     }
10855 
10856     Loc = Op->getOperatorLoc();
10857   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
10858     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
10859       return;
10860 
10861     IsOrAssign = Op->getOperator() == OO_PipeEqual;
10862     Loc = Op->getOperatorLoc();
10863   } else {
10864     // Not an assignment.
10865     return;
10866   }
10867 
10868   Diag(Loc, diagnostic) << E->getSourceRange();
10869 
10870   SourceLocation Open = E->getLocStart();
10871   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10872   Diag(Loc, diag::note_condition_assign_silence)
10873         << FixItHint::CreateInsertion(Open, "(")
10874         << FixItHint::CreateInsertion(Close, ")");
10875 
10876   if (IsOrAssign)
10877     Diag(Loc, diag::note_condition_or_assign_to_comparison)
10878       << FixItHint::CreateReplacement(Loc, "!=");
10879   else
10880     Diag(Loc, diag::note_condition_assign_to_comparison)
10881       << FixItHint::CreateReplacement(Loc, "==");
10882 }
10883 
10884 /// \brief Redundant parentheses over an equality comparison can indicate
10885 /// that the user intended an assignment used as condition.
10886 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
10887   // Don't warn if the parens came from a macro.
10888   SourceLocation parenLoc = ParenE->getLocStart();
10889   if (parenLoc.isInvalid() || parenLoc.isMacroID())
10890     return;
10891   // Don't warn for dependent expressions.
10892   if (ParenE->isTypeDependent())
10893     return;
10894 
10895   Expr *E = ParenE->IgnoreParens();
10896 
10897   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
10898     if (opE->getOpcode() == BO_EQ &&
10899         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10900                                                            == Expr::MLV_Valid) {
10901       SourceLocation Loc = opE->getOperatorLoc();
10902       
10903       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
10904       SourceRange ParenERange = ParenE->getSourceRange();
10905       Diag(Loc, diag::note_equality_comparison_silence)
10906         << FixItHint::CreateRemoval(ParenERange.getBegin())
10907         << FixItHint::CreateRemoval(ParenERange.getEnd());
10908       Diag(Loc, diag::note_equality_comparison_to_assign)
10909         << FixItHint::CreateReplacement(Loc, "=");
10910     }
10911 }
10912 
10913 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
10914   DiagnoseAssignmentAsCondition(E);
10915   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10916     DiagnoseEqualityWithExtraParens(parenE);
10917 
10918   ExprResult result = CheckPlaceholderExpr(E);
10919   if (result.isInvalid()) return ExprError();
10920   E = result.take();
10921 
10922   if (!E->isTypeDependent()) {
10923     if (getLangOpts().CPlusPlus)
10924       return CheckCXXBooleanCondition(E); // C++ 6.4p4
10925 
10926     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10927     if (ERes.isInvalid())
10928       return ExprError();
10929     E = ERes.take();
10930 
10931     QualType T = E->getType();
10932     if (!T->isScalarType()) { // C99 6.8.4.1p1
10933       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10934         << T << E->getSourceRange();
10935       return ExprError();
10936     }
10937   }
10938 
10939   return Owned(E);
10940 }
10941 
10942 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10943                                        Expr *SubExpr) {
10944   if (!SubExpr)
10945     return ExprError();
10946 
10947   return CheckBooleanCondition(SubExpr, Loc);
10948 }
10949 
10950 namespace {
10951   /// A visitor for rebuilding a call to an __unknown_any expression
10952   /// to have an appropriate type.
10953   struct RebuildUnknownAnyFunction
10954     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10955 
10956     Sema &S;
10957 
10958     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10959 
10960     ExprResult VisitStmt(Stmt *S) {
10961       llvm_unreachable("unexpected statement!");
10962     }
10963 
10964     ExprResult VisitExpr(Expr *E) {
10965       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10966         << E->getSourceRange();
10967       return ExprError();
10968     }
10969 
10970     /// Rebuild an expression which simply semantically wraps another
10971     /// expression which it shares the type and value kind of.
10972     template <class T> ExprResult rebuildSugarExpr(T *E) {
10973       ExprResult SubResult = Visit(E->getSubExpr());
10974       if (SubResult.isInvalid()) return ExprError();
10975 
10976       Expr *SubExpr = SubResult.take();
10977       E->setSubExpr(SubExpr);
10978       E->setType(SubExpr->getType());
10979       E->setValueKind(SubExpr->getValueKind());
10980       assert(E->getObjectKind() == OK_Ordinary);
10981       return E;
10982     }
10983 
10984     ExprResult VisitParenExpr(ParenExpr *E) {
10985       return rebuildSugarExpr(E);
10986     }
10987 
10988     ExprResult VisitUnaryExtension(UnaryOperator *E) {
10989       return rebuildSugarExpr(E);
10990     }
10991 
10992     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10993       ExprResult SubResult = Visit(E->getSubExpr());
10994       if (SubResult.isInvalid()) return ExprError();
10995 
10996       Expr *SubExpr = SubResult.take();
10997       E->setSubExpr(SubExpr);
10998       E->setType(S.Context.getPointerType(SubExpr->getType()));
10999       assert(E->getValueKind() == VK_RValue);
11000       assert(E->getObjectKind() == OK_Ordinary);
11001       return E;
11002     }
11003 
11004     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11005       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11006 
11007       E->setType(VD->getType());
11008 
11009       assert(E->getValueKind() == VK_RValue);
11010       if (S.getLangOpts().CPlusPlus &&
11011           !(isa<CXXMethodDecl>(VD) &&
11012             cast<CXXMethodDecl>(VD)->isInstance()))
11013         E->setValueKind(VK_LValue);
11014 
11015       return E;
11016     }
11017 
11018     ExprResult VisitMemberExpr(MemberExpr *E) {
11019       return resolveDecl(E, E->getMemberDecl());
11020     }
11021 
11022     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11023       return resolveDecl(E, E->getDecl());
11024     }
11025   };
11026 }
11027 
11028 /// Given a function expression of unknown-any type, try to rebuild it
11029 /// to have a function type.
11030 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11031   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11032   if (Result.isInvalid()) return ExprError();
11033   return S.DefaultFunctionArrayConversion(Result.take());
11034 }
11035 
11036 namespace {
11037   /// A visitor for rebuilding an expression of type __unknown_anytype
11038   /// into one which resolves the type directly on the referring
11039   /// expression.  Strict preservation of the original source
11040   /// structure is not a goal.
11041   struct RebuildUnknownAnyExpr
11042     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11043 
11044     Sema &S;
11045 
11046     /// The current destination type.
11047     QualType DestType;
11048 
11049     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11050       : S(S), DestType(CastType) {}
11051 
11052     ExprResult VisitStmt(Stmt *S) {
11053       llvm_unreachable("unexpected statement!");
11054     }
11055 
11056     ExprResult VisitExpr(Expr *E) {
11057       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11058         << E->getSourceRange();
11059       return ExprError();
11060     }
11061 
11062     ExprResult VisitCallExpr(CallExpr *E);
11063     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11064 
11065     /// Rebuild an expression which simply semantically wraps another
11066     /// expression which it shares the type and value kind of.
11067     template <class T> ExprResult rebuildSugarExpr(T *E) {
11068       ExprResult SubResult = Visit(E->getSubExpr());
11069       if (SubResult.isInvalid()) return ExprError();
11070       Expr *SubExpr = SubResult.take();
11071       E->setSubExpr(SubExpr);
11072       E->setType(SubExpr->getType());
11073       E->setValueKind(SubExpr->getValueKind());
11074       assert(E->getObjectKind() == OK_Ordinary);
11075       return E;
11076     }
11077 
11078     ExprResult VisitParenExpr(ParenExpr *E) {
11079       return rebuildSugarExpr(E);
11080     }
11081 
11082     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11083       return rebuildSugarExpr(E);
11084     }
11085 
11086     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11087       const PointerType *Ptr = DestType->getAs<PointerType>();
11088       if (!Ptr) {
11089         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11090           << E->getSourceRange();
11091         return ExprError();
11092       }
11093       assert(E->getValueKind() == VK_RValue);
11094       assert(E->getObjectKind() == OK_Ordinary);
11095       E->setType(DestType);
11096 
11097       // Build the sub-expression as if it were an object of the pointee type.
11098       DestType = Ptr->getPointeeType();
11099       ExprResult SubResult = Visit(E->getSubExpr());
11100       if (SubResult.isInvalid()) return ExprError();
11101       E->setSubExpr(SubResult.take());
11102       return E;
11103     }
11104 
11105     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11106 
11107     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11108 
11109     ExprResult VisitMemberExpr(MemberExpr *E) {
11110       return resolveDecl(E, E->getMemberDecl());
11111     }
11112 
11113     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11114       return resolveDecl(E, E->getDecl());
11115     }
11116   };
11117 }
11118 
11119 /// Rebuilds a call expression which yielded __unknown_anytype.
11120 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11121   Expr *CalleeExpr = E->getCallee();
11122 
11123   enum FnKind {
11124     FK_MemberFunction,
11125     FK_FunctionPointer,
11126     FK_BlockPointer
11127   };
11128 
11129   FnKind Kind;
11130   QualType CalleeType = CalleeExpr->getType();
11131   if (CalleeType == S.Context.BoundMemberTy) {
11132     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11133     Kind = FK_MemberFunction;
11134     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11135   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11136     CalleeType = Ptr->getPointeeType();
11137     Kind = FK_FunctionPointer;
11138   } else {
11139     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11140     Kind = FK_BlockPointer;
11141   }
11142   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11143 
11144   // Verify that this is a legal result type of a function.
11145   if (DestType->isArrayType() || DestType->isFunctionType()) {
11146     unsigned diagID = diag::err_func_returning_array_function;
11147     if (Kind == FK_BlockPointer)
11148       diagID = diag::err_block_returning_array_function;
11149 
11150     S.Diag(E->getExprLoc(), diagID)
11151       << DestType->isFunctionType() << DestType;
11152     return ExprError();
11153   }
11154 
11155   // Otherwise, go ahead and set DestType as the call's result.
11156   E->setType(DestType.getNonLValueExprType(S.Context));
11157   E->setValueKind(Expr::getValueKindForType(DestType));
11158   assert(E->getObjectKind() == OK_Ordinary);
11159 
11160   // Rebuild the function type, replacing the result type with DestType.
11161   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11162     DestType = S.Context.getFunctionType(DestType,
11163                                          Proto->arg_type_begin(),
11164                                          Proto->getNumArgs(),
11165                                          Proto->getExtProtoInfo());
11166   else
11167     DestType = S.Context.getFunctionNoProtoType(DestType,
11168                                                 FnType->getExtInfo());
11169 
11170   // Rebuild the appropriate pointer-to-function type.
11171   switch (Kind) { 
11172   case FK_MemberFunction:
11173     // Nothing to do.
11174     break;
11175 
11176   case FK_FunctionPointer:
11177     DestType = S.Context.getPointerType(DestType);
11178     break;
11179 
11180   case FK_BlockPointer:
11181     DestType = S.Context.getBlockPointerType(DestType);
11182     break;
11183   }
11184 
11185   // Finally, we can recurse.
11186   ExprResult CalleeResult = Visit(CalleeExpr);
11187   if (!CalleeResult.isUsable()) return ExprError();
11188   E->setCallee(CalleeResult.take());
11189 
11190   // Bind a temporary if necessary.
11191   return S.MaybeBindToTemporary(E);
11192 }
11193 
11194 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11195   // Verify that this is a legal result type of a call.
11196   if (DestType->isArrayType() || DestType->isFunctionType()) {
11197     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11198       << DestType->isFunctionType() << DestType;
11199     return ExprError();
11200   }
11201 
11202   // Rewrite the method result type if available.
11203   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11204     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11205     Method->setResultType(DestType);
11206   }
11207 
11208   // Change the type of the message.
11209   E->setType(DestType.getNonReferenceType());
11210   E->setValueKind(Expr::getValueKindForType(DestType));
11211 
11212   return S.MaybeBindToTemporary(E);
11213 }
11214 
11215 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11216   // The only case we should ever see here is a function-to-pointer decay.
11217   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11218     assert(E->getValueKind() == VK_RValue);
11219     assert(E->getObjectKind() == OK_Ordinary);
11220   
11221     E->setType(DestType);
11222   
11223     // Rebuild the sub-expression as the pointee (function) type.
11224     DestType = DestType->castAs<PointerType>()->getPointeeType();
11225   
11226     ExprResult Result = Visit(E->getSubExpr());
11227     if (!Result.isUsable()) return ExprError();
11228   
11229     E->setSubExpr(Result.take());
11230     return S.Owned(E);
11231   } else if (E->getCastKind() == CK_LValueToRValue) {
11232     assert(E->getValueKind() == VK_RValue);
11233     assert(E->getObjectKind() == OK_Ordinary);
11234 
11235     assert(isa<BlockPointerType>(E->getType()));
11236 
11237     E->setType(DestType);
11238 
11239     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11240     DestType = S.Context.getLValueReferenceType(DestType);
11241 
11242     ExprResult Result = Visit(E->getSubExpr());
11243     if (!Result.isUsable()) return ExprError();
11244 
11245     E->setSubExpr(Result.take());
11246     return S.Owned(E);
11247   } else {
11248     llvm_unreachable("Unhandled cast type!");
11249   }
11250 }
11251 
11252 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11253   ExprValueKind ValueKind = VK_LValue;
11254   QualType Type = DestType;
11255 
11256   // We know how to make this work for certain kinds of decls:
11257 
11258   //  - functions
11259   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11260     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11261       DestType = Ptr->getPointeeType();
11262       ExprResult Result = resolveDecl(E, VD);
11263       if (Result.isInvalid()) return ExprError();
11264       return S.ImpCastExprToType(Result.take(), Type,
11265                                  CK_FunctionToPointerDecay, VK_RValue);
11266     }
11267 
11268     if (!Type->isFunctionType()) {
11269       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11270         << VD << E->getSourceRange();
11271       return ExprError();
11272     }
11273 
11274     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11275       if (MD->isInstance()) {
11276         ValueKind = VK_RValue;
11277         Type = S.Context.BoundMemberTy;
11278       }
11279 
11280     // Function references aren't l-values in C.
11281     if (!S.getLangOpts().CPlusPlus)
11282       ValueKind = VK_RValue;
11283 
11284   //  - variables
11285   } else if (isa<VarDecl>(VD)) {
11286     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11287       Type = RefTy->getPointeeType();
11288     } else if (Type->isFunctionType()) {
11289       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11290         << VD << E->getSourceRange();
11291       return ExprError();
11292     }
11293 
11294   //  - nothing else
11295   } else {
11296     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11297       << VD << E->getSourceRange();
11298     return ExprError();
11299   }
11300 
11301   VD->setType(DestType);
11302   E->setType(Type);
11303   E->setValueKind(ValueKind);
11304   return S.Owned(E);
11305 }
11306 
11307 /// Check a cast of an unknown-any type.  We intentionally only
11308 /// trigger this for C-style casts.
11309 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11310                                      Expr *CastExpr, CastKind &CastKind,
11311                                      ExprValueKind &VK, CXXCastPath &Path) {
11312   // Rewrite the casted expression from scratch.
11313   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11314   if (!result.isUsable()) return ExprError();
11315 
11316   CastExpr = result.take();
11317   VK = CastExpr->getValueKind();
11318   CastKind = CK_NoOp;
11319 
11320   return CastExpr;
11321 }
11322 
11323 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11324   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11325 }
11326 
11327 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11328   Expr *orig = E;
11329   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11330   while (true) {
11331     E = E->IgnoreParenImpCasts();
11332     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11333       E = call->getCallee();
11334       diagID = diag::err_uncasted_call_of_unknown_any;
11335     } else {
11336       break;
11337     }
11338   }
11339 
11340   SourceLocation loc;
11341   NamedDecl *d;
11342   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11343     loc = ref->getLocation();
11344     d = ref->getDecl();
11345   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11346     loc = mem->getMemberLoc();
11347     d = mem->getMemberDecl();
11348   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11349     diagID = diag::err_uncasted_call_of_unknown_any;
11350     loc = msg->getSelectorStartLoc();
11351     d = msg->getMethodDecl();
11352     if (!d) {
11353       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11354         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11355         << orig->getSourceRange();
11356       return ExprError();
11357     }
11358   } else {
11359     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11360       << E->getSourceRange();
11361     return ExprError();
11362   }
11363 
11364   S.Diag(loc, diagID) << d << orig->getSourceRange();
11365 
11366   // Never recoverable.
11367   return ExprError();
11368 }
11369 
11370 /// Check for operands with placeholder types and complain if found.
11371 /// Returns true if there was an error and no recovery was possible.
11372 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11373   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11374   if (!placeholderType) return Owned(E);
11375 
11376   switch (placeholderType->getKind()) {
11377 
11378   // Overloaded expressions.
11379   case BuiltinType::Overload: {
11380     // Try to resolve a single function template specialization.
11381     // This is obligatory.
11382     ExprResult result = Owned(E);
11383     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11384       return result;
11385 
11386     // If that failed, try to recover with a call.
11387     } else {
11388       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11389                            /*complain*/ true);
11390       return result;
11391     }
11392   }
11393 
11394   // Bound member functions.
11395   case BuiltinType::BoundMember: {
11396     ExprResult result = Owned(E);
11397     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11398                          /*complain*/ true);
11399     return result;
11400   }
11401 
11402   // ARC unbridged casts.
11403   case BuiltinType::ARCUnbridgedCast: {
11404     Expr *realCast = stripARCUnbridgedCast(E);
11405     diagnoseARCUnbridgedCast(realCast);
11406     return Owned(realCast);
11407   }
11408 
11409   // Expressions of unknown type.
11410   case BuiltinType::UnknownAny:
11411     return diagnoseUnknownAnyExpr(*this, E);
11412 
11413   // Pseudo-objects.
11414   case BuiltinType::PseudoObject:
11415     return checkPseudoObjectRValue(E);
11416 
11417   // Everything else should be impossible.
11418 #define BUILTIN_TYPE(Id, SingletonId) \
11419   case BuiltinType::Id:
11420 #define PLACEHOLDER_TYPE(Id, SingletonId)
11421 #include "clang/AST/BuiltinTypes.def"
11422     break;
11423   }
11424 
11425   llvm_unreachable("invalid placeholder type!");
11426 }
11427 
11428 bool Sema::CheckCaseExpression(Expr *E) {
11429   if (E->isTypeDependent())
11430     return true;
11431   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11432     return E->getType()->isIntegralOrEnumerationType();
11433   return false;
11434 }
11435 
11436 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11437 ExprResult
11438 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11439   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11440          "Unknown Objective-C Boolean value!");
11441   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11442                                         Context.ObjCBuiltinBoolTy, OpLoc));
11443 }