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 "Sema.h"
00015 #include "SemaInit.h"
00016 #include "Lookup.h"
00017 #include "clang/Analysis/AnalysisContext.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "clang/AST/DeclTemplate.h"
00021 #include "clang/AST/ExprCXX.h"
00022 #include "clang/AST/ExprObjC.h"
00023 #include "clang/Basic/PartialDiagnostic.h"
00024 #include "clang/Basic/SourceManager.h"
00025 #include "clang/Basic/TargetInfo.h"
00026 #include "clang/Lex/LiteralSupport.h"
00027 #include "clang/Lex/Preprocessor.h"
00028 #include "clang/Parse/DeclSpec.h"
00029 #include "clang/Parse/Designator.h"
00030 #include "clang/Parse/Scope.h"
00031 #include "clang/Parse/Template.h"
00032 using namespace clang;
00033 
00034 
00035 /// \brief Determine whether the use of this declaration is valid, and
00036 /// emit any corresponding diagnostics.
00037 ///
00038 /// This routine diagnoses various problems with referencing
00039 /// declarations that can occur when using a declaration. For example,
00040 /// it might warn if a deprecated or unavailable declaration is being
00041 /// used, or produce an error (and return true) if a C++0x deleted
00042 /// function is being used.
00043 ///
00044 /// If IgnoreDeprecated is set to true, this should not want about deprecated
00045 /// decls.
00046 ///
00047 /// \returns true if there was an error (this declaration cannot be
00048 /// referenced), false otherwise.
00049 ///
00050 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
00051   // See if the decl is deprecated.
00052   if (D->getAttr<DeprecatedAttr>()) {
00053     EmitDeprecationWarning(D, Loc);
00054   }
00055 
00056   // See if the decl is unavailable
00057   if (D->getAttr<UnavailableAttr>()) {
00058     Diag(Loc, diag::warn_unavailable) << D->getDeclName();
00059     Diag(D->getLocation(), diag::note_unavailable_here) << 0;
00060   }
00061 
00062   // See if this is a deleted function.
00063   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00064     if (FD->isDeleted()) {
00065       Diag(Loc, diag::err_deleted_function_use);
00066       Diag(D->getLocation(), diag::note_unavailable_here) << true;
00067       return true;
00068     }
00069   }
00070 
00071   return false;
00072 }
00073 
00074 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
00075 /// (and other functions in future), which have been declared with sentinel
00076 /// attribute. It warns if call does not have the sentinel argument.
00077 ///
00078 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
00079                                  Expr **Args, unsigned NumArgs) {
00080   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
00081   if (!attr)
00082     return;
00083   int sentinelPos = attr->getSentinel();
00084   int nullPos = attr->getNullPos();
00085 
00086   // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
00087   // base class. Then we won't be needing two versions of the same code.
00088   unsigned int i = 0;
00089   bool warnNotEnoughArgs = false;
00090   int isMethod = 0;
00091   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
00092     // skip over named parameters.
00093     ObjCMethodDecl::param_iterator P, E = MD->param_end();
00094     for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
00095       if (nullPos)
00096         --nullPos;
00097       else
00098         ++i;
00099     }
00100     warnNotEnoughArgs = (P != E || i >= NumArgs);
00101     isMethod = 1;
00102   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00103     // skip over named parameters.
00104     ObjCMethodDecl::param_iterator P, E = FD->param_end();
00105     for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
00106       if (nullPos)
00107         --nullPos;
00108       else
00109         ++i;
00110     }
00111     warnNotEnoughArgs = (P != E || i >= NumArgs);
00112   } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
00113     // block or function pointer call.
00114     QualType Ty = V->getType();
00115     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
00116       const FunctionType *FT = Ty->isFunctionPointerType()
00117       ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
00118       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
00119       if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
00120         unsigned NumArgsInProto = Proto->getNumArgs();
00121         unsigned k;
00122         for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
00123           if (nullPos)
00124             --nullPos;
00125           else
00126             ++i;
00127         }
00128         warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
00129       }
00130       if (Ty->isBlockPointerType())
00131         isMethod = 2;
00132     } else
00133       return;
00134   } else
00135     return;
00136 
00137   if (warnNotEnoughArgs) {
00138     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00139     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00140     return;
00141   }
00142   int sentinel = i;
00143   while (sentinelPos > 0 && i < NumArgs-1) {
00144     --sentinelPos;
00145     ++i;
00146   }
00147   if (sentinelPos > 0) {
00148     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
00149     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00150     return;
00151   }
00152   while (i < NumArgs-1) {
00153     ++i;
00154     ++sentinel;
00155   }
00156   Expr *sentinelExpr = Args[sentinel];
00157   if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
00158                        (!sentinelExpr->getType()->isPointerType() ||
00159                         !sentinelExpr->isNullPointerConstant(Context,
00160                                             Expr::NPC_ValueDependentIsNull)))) {
00161     Diag(Loc, diag::warn_missing_sentinel) << isMethod;
00162     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
00163   }
00164   return;
00165 }
00166 
00167 SourceRange Sema::getExprRange(ExprTy *E) const {
00168   Expr *Ex = (Expr *)E;
00169   return Ex? Ex->getSourceRange() : SourceRange();
00170 }
00171 
00172 //===----------------------------------------------------------------------===//
00173 //  Standard Promotions and Conversions
00174 //===----------------------------------------------------------------------===//
00175 
00176 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
00177 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
00178   QualType Ty = E->getType();
00179   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
00180 
00181   if (Ty->isFunctionType())
00182     ImpCastExprToType(E, Context.getPointerType(Ty),
00183                       CastExpr::CK_FunctionToPointerDecay);
00184   else if (Ty->isArrayType()) {
00185     // In C90 mode, arrays only promote to pointers if the array expression is
00186     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
00187     // type 'array of type' is converted to an expression that has type 'pointer
00188     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
00189     // that has type 'array of type' ...".  The relevant change is "an lvalue"
00190     // (C90) to "an expression" (C99).
00191     //
00192     // C++ 4.2p1:
00193     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
00194     // T" can be converted to an rvalue of type "pointer to T".
00195     //
00196     if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
00197         E->isLvalue(Context) == Expr::LV_Valid)
00198       ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
00199                         CastExpr::CK_ArrayToPointerDecay);
00200   }
00201 }
00202 
00203 void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
00204   DefaultFunctionArrayConversion(E);
00205 
00206   QualType Ty = E->getType();
00207   assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
00208   if (!Ty->isDependentType() && Ty.hasQualifiers() &&
00209       (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
00210       E->isLvalue(Context) == Expr::LV_Valid) {
00211     // C++ [conv.lval]p1:
00212     //   [...] If T is a non-class type, the type of the rvalue is the
00213     //   cv-unqualified version of T. Otherwise, the type of the
00214     //   rvalue is T
00215     //
00216     // C99 6.3.2.1p2:
00217     //   If the lvalue has qualified type, the value has the unqualified
00218     //   version of the type of the lvalue; otherwise, the value has the
00219     //   type of the lvalue.
00220     ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
00221   }
00222 }
00223 
00224 
00225 /// UsualUnaryConversions - Performs various conversions that are common to most
00226 /// operators (C99 6.3). The conversions of array and function types are
00227 /// sometimes surpressed. For example, the array->pointer conversion doesn't
00228 /// apply if the array is an argument to the sizeof or address (&) operators.
00229 /// In these instances, this routine should *not* be called.
00230 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
00231   QualType Ty = Expr->getType();
00232   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
00233 
00234   // C99 6.3.1.1p2:
00235   //
00236   //   The following may be used in an expression wherever an int or
00237   //   unsigned int may be used:
00238   //     - an object or expression with an integer type whose integer
00239   //       conversion rank is less than or equal to the rank of int
00240   //       and unsigned int.
00241   //     - A bit-field of type _Bool, int, signed int, or unsigned int.
00242   //
00243   //   If an int can represent all values of the original type, the
00244   //   value is converted to an int; otherwise, it is converted to an
00245   //   unsigned int. These are called the integer promotions. All
00246   //   other types are unchanged by the integer promotions.
00247   QualType PTy = Context.isPromotableBitField(Expr);
00248   if (!PTy.isNull()) {
00249     ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
00250     return Expr;
00251   }
00252   if (Ty->isPromotableIntegerType()) {
00253     QualType PT = Context.getPromotedIntegerType(Ty);
00254     ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
00255     return Expr;
00256   }
00257 
00258   DefaultFunctionArrayLvalueConversion(Expr);
00259   return Expr;
00260 }
00261 
00262 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
00263 /// do not have a prototype. Arguments that have type float are promoted to
00264 /// double. All other argument types are converted by UsualUnaryConversions().
00265 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
00266   QualType Ty = Expr->getType();
00267   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
00268 
00269   // If this is a 'float' (CVR qualified or typedef) promote to double.
00270   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
00271     if (BT->getKind() == BuiltinType::Float)
00272       return ImpCastExprToType(Expr, Context.DoubleTy,
00273                                CastExpr::CK_FloatingCast);
00274 
00275   UsualUnaryConversions(Expr);
00276 }
00277 
00278 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
00279 /// will warn if the resulting type is not a POD type, and rejects ObjC
00280 /// interfaces passed by value.  This returns true if the argument type is
00281 /// completely illegal.
00282 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
00283   DefaultArgumentPromotion(Expr);
00284 
00285   if (Expr->getType()->isObjCInterfaceType() &&
00286       DiagRuntimeBehavior(Expr->getLocStart(),
00287         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
00288           << Expr->getType() << CT))
00289     return true;
00290 
00291   if (!Expr->getType()->isPODType() &&
00292       DiagRuntimeBehavior(Expr->getLocStart(),
00293                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
00294                             << Expr->getType() << CT))
00295     return true;
00296 
00297   return false;
00298 }
00299 
00300 
00301 /// UsualArithmeticConversions - Performs various conversions that are common to
00302 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
00303 /// routine returns the first non-arithmetic type found. The client is
00304 /// responsible for emitting appropriate error diagnostics.
00305 /// FIXME: verify the conversion rules for "complex int" are consistent with
00306 /// GCC.
00307 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
00308                                           bool isCompAssign) {
00309   if (!isCompAssign)
00310     UsualUnaryConversions(lhsExpr);
00311 
00312   UsualUnaryConversions(rhsExpr);
00313 
00314   // For conversion purposes, we ignore any qualifiers.
00315   // For example, "const float" and "float" are equivalent.
00316   QualType lhs =
00317     Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
00318   QualType rhs =
00319     Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
00320 
00321   // If both types are identical, no conversion is needed.
00322   if (lhs == rhs)
00323     return lhs;
00324 
00325   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
00326   // The caller can deal with this (e.g. pointer + int).
00327   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
00328     return lhs;
00329 
00330   // Perform bitfield promotions.
00331   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
00332   if (!LHSBitfieldPromoteTy.isNull())
00333     lhs = LHSBitfieldPromoteTy;
00334   QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
00335   if (!RHSBitfieldPromoteTy.isNull())
00336     rhs = RHSBitfieldPromoteTy;
00337 
00338   QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
00339   if (!isCompAssign)
00340     ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
00341   ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
00342   return destType;
00343 }
00344 
00345 //===----------------------------------------------------------------------===//
00346 //  Semantic Analysis for various Expression Types
00347 //===----------------------------------------------------------------------===//
00348 
00349 
00350 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
00351 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
00352 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
00353 /// multiple tokens.  However, the common case is that StringToks points to one
00354 /// string.
00355 ///
00356 Action::OwningExprResult
00357 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
00358   assert(NumStringToks && "Must have at least one string!");
00359 
00360   StringLiteralParser Literal(StringToks, NumStringToks, PP);
00361   if (Literal.hadError)
00362     return ExprError();
00363 
00364   llvm::SmallVector<SourceLocation, 4> StringTokLocs;
00365   for (unsigned i = 0; i != NumStringToks; ++i)
00366     StringTokLocs.push_back(StringToks[i].getLocation());
00367 
00368   QualType StrTy = Context.CharTy;
00369   if (Literal.AnyWide) StrTy = Context.getWCharType();
00370   if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
00371 
00372   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
00373   if (getLangOptions().CPlusPlus)
00374     StrTy.addConst();
00375 
00376   // Get an array type for the string, according to C99 6.4.5.  This includes
00377   // the nul terminator character as well as the string length for pascal
00378   // strings.
00379   StrTy = Context.getConstantArrayType(StrTy,
00380                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
00381                                        ArrayType::Normal, 0);
00382 
00383   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
00384   return Owned(StringLiteral::Create(Context, Literal.GetString(),
00385                                      Literal.GetStringLength(),
00386                                      Literal.AnyWide, StrTy,
00387                                      &StringTokLocs[0],
00388                                      StringTokLocs.size()));
00389 }
00390 
00391 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
00392 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
00393 /// variables defined outside the block) or false if this is not needed (e.g.
00394 /// for values inside the block or for globals).
00395 ///
00396 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
00397 /// up-to-date.
00398 ///
00399 static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
00400                                               ValueDecl *VD) {
00401   // If the value is defined inside the block, we couldn't snapshot it even if
00402   // we wanted to.
00403   if (CurBlock->TheDecl == VD->getDeclContext())
00404     return false;
00405 
00406   // If this is an enum constant or function, it is constant, don't snapshot.
00407   if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
00408     return false;
00409 
00410   // If this is a reference to an extern, static, or global variable, no need to
00411   // snapshot it.
00412   // FIXME: What about 'const' variables in C++?
00413   if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
00414     if (!Var->hasLocalStorage())
00415       return false;
00416 
00417   // Blocks that have these can't be constant.
00418   CurBlock->hasBlockDeclRefExprs = true;
00419 
00420   // If we have nested blocks, the decl may be declared in an outer block (in
00421   // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
00422   // be defined outside all of the current blocks (in which case the blocks do
00423   // all get the bit).  Walk the nesting chain.
00424   for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
00425     BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
00426 
00427     if (!NextBlock)
00428       continue;
00429 
00430     // If we found the defining block for the variable, don't mark the block as
00431     // having a reference outside it.
00432     if (NextBlock->TheDecl == VD->getDeclContext())
00433       break;
00434 
00435     // Otherwise, the DeclRef from the inner block causes the outer one to need
00436     // a snapshot as well.
00437     NextBlock->hasBlockDeclRefExprs = true;
00438   }
00439 
00440   return true;
00441 }
00442 
00443 
00444 
00445 /// BuildDeclRefExpr - Build a DeclRefExpr.
00446 Sema::OwningExprResult
00447 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
00448                        const CXXScopeSpec *SS) {
00449   if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
00450     Diag(Loc,
00451          diag::err_auto_variable_cannot_appear_in_own_initializer)
00452       << D->getDeclName();
00453     return ExprError();
00454   }
00455 
00456   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00457     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
00458       if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
00459         if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
00460           Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
00461             << D->getIdentifier() << FD->getDeclName();
00462           Diag(D->getLocation(), diag::note_local_variable_declared_here)
00463             << D->getIdentifier();
00464           return ExprError();
00465         }
00466       }
00467     }
00468   }
00469 
00470   MarkDeclarationReferenced(Loc, D);
00471 
00472   return Owned(DeclRefExpr::Create(Context,
00473                               SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
00474                                    SS? SS->getRange() : SourceRange(),
00475                                    D, Loc, Ty));
00476 }
00477 
00478 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
00479 /// variable corresponding to the anonymous union or struct whose type
00480 /// is Record.
00481 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
00482                                              RecordDecl *Record) {
00483   assert(Record->isAnonymousStructOrUnion() &&
00484          "Record must be an anonymous struct or union!");
00485 
00486   // FIXME: Once Decls are directly linked together, this will be an O(1)
00487   // operation rather than a slow walk through DeclContext's vector (which
00488   // itself will be eliminated). DeclGroups might make this even better.
00489   DeclContext *Ctx = Record->getDeclContext();
00490   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
00491                                DEnd = Ctx->decls_end();
00492        D != DEnd; ++D) {
00493     if (*D == Record) {
00494       // The object for the anonymous struct/union directly
00495       // follows its type in the list of declarations.
00496       ++D;
00497       assert(D != DEnd && "Missing object for anonymous record");
00498       assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
00499       return *D;
00500     }
00501   }
00502 
00503   assert(false && "Missing object for anonymous record");
00504   return 0;
00505 }
00506 
00507 /// \brief Given a field that represents a member of an anonymous
00508 /// struct/union, build the path from that field's context to the
00509 /// actual member.
00510 ///
00511 /// Construct the sequence of field member references we'll have to
00512 /// perform to get to the field in the anonymous union/struct. The
00513 /// list of members is built from the field outward, so traverse it
00514 /// backwards to go from an object in the current context to the field
00515 /// we found.
00516 ///
00517 /// \returns The variable from which the field access should begin,
00518 /// for an anonymous struct/union that is not a member of another
00519 /// class. Otherwise, returns NULL.
00520 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
00521                                    llvm::SmallVectorImpl<FieldDecl *> &Path) {
00522   assert(Field->getDeclContext()->isRecord() &&
00523          cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
00524          && "Field must be stored inside an anonymous struct or union");
00525 
00526   Path.push_back(Field);
00527   VarDecl *BaseObject = 0;
00528   DeclContext *Ctx = Field->getDeclContext();
00529   do {
00530     RecordDecl *Record = cast<RecordDecl>(Ctx);
00531     Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
00532     if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
00533       Path.push_back(AnonField);
00534     else {
00535       BaseObject = cast<VarDecl>(AnonObject);
00536       break;
00537     }
00538     Ctx = Ctx->getParent();
00539   } while (Ctx->isRecord() &&
00540            cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
00541 
00542   return BaseObject;
00543 }
00544 
00545 Sema::OwningExprResult
00546 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
00547                                                FieldDecl *Field,
00548                                                Expr *BaseObjectExpr,
00549                                                SourceLocation OpLoc) {
00550   llvm::SmallVector<FieldDecl *, 4> AnonFields;
00551   VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
00552                                                             AnonFields);
00553 
00554   // Build the expression that refers to the base object, from
00555   // which we will build a sequence of member references to each
00556   // of the anonymous union objects and, eventually, the field we
00557   // found via name lookup.
00558   bool BaseObjectIsPointer = false;
00559   Qualifiers BaseQuals;
00560   if (BaseObject) {
00561     // BaseObject is an anonymous struct/union variable (and is,
00562     // therefore, not part of another non-anonymous record).
00563     if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
00564     MarkDeclarationReferenced(Loc, BaseObject);
00565     BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
00566                                                SourceLocation());
00567     BaseQuals
00568       = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
00569   } else if (BaseObjectExpr) {
00570     // The caller provided the base object expression. Determine
00571     // whether its a pointer and whether it adds any qualifiers to the
00572     // anonymous struct/union fields we're looking into.
00573     QualType ObjectType = BaseObjectExpr->getType();
00574     if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
00575       BaseObjectIsPointer = true;
00576       ObjectType = ObjectPtr->getPointeeType();
00577     }
00578     BaseQuals
00579       = Context.getCanonicalType(ObjectType).getQualifiers();
00580   } else {
00581     // We've found a member of an anonymous struct/union that is
00582     // inside a non-anonymous struct/union, so in a well-formed
00583     // program our base object expression is "this".
00584     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
00585       if (!MD->isStatic()) {
00586         QualType AnonFieldType
00587           = Context.getTagDeclType(
00588                      cast<RecordDecl>(AnonFields.back()->getDeclContext()));
00589         QualType ThisType = Context.getTagDeclType(MD->getParent());
00590         if ((Context.getCanonicalType(AnonFieldType)
00591                == Context.getCanonicalType(ThisType)) ||
00592             IsDerivedFrom(ThisType, AnonFieldType)) {
00593           // Our base object expression is "this".
00594           BaseObjectExpr = new (Context) CXXThisExpr(Loc,
00595                                                      MD->getThisType(Context),
00596                                                      /*isImplicit=*/true);
00597           BaseObjectIsPointer = true;
00598         }
00599       } else {
00600         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
00601           << Field->getDeclName());
00602       }
00603       BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
00604     }
00605 
00606     if (!BaseObjectExpr)
00607       return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
00608         << Field->getDeclName());
00609   }
00610 
00611   // Build the implicit member references to the field of the
00612   // anonymous struct/union.
00613   Expr *Result = BaseObjectExpr;
00614   Qualifiers ResultQuals = BaseQuals;
00615   for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
00616          FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
00617        FI != FIEnd; ++FI) {
00618     QualType MemberType = (*FI)->getType();
00619     Qualifiers MemberTypeQuals =
00620       Context.getCanonicalType(MemberType).getQualifiers();
00621 
00622     // CVR attributes from the base are picked up by members,
00623     // except that 'mutable' members don't pick up 'const'.
00624     if ((*FI)->isMutable())
00625       ResultQuals.removeConst();
00626 
00627     // GC attributes are never picked up by members.
00628     ResultQuals.removeObjCGCAttr();
00629 
00630     // TR 18037 does not allow fields to be declared with address spaces.
00631     assert(!MemberTypeQuals.hasAddressSpace());
00632 
00633     Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
00634     if (NewQuals != MemberTypeQuals)
00635       MemberType = Context.getQualifiedType(MemberType, NewQuals);
00636 
00637     MarkDeclarationReferenced(Loc, *FI);
00638     PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI);
00639     // FIXME: Might this end up being a qualified name?
00640     Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
00641                                       OpLoc, MemberType);
00642     BaseObjectIsPointer = false;
00643     ResultQuals = NewQuals;
00644   }
00645 
00646   return Owned(Result);
00647 }
00648 
00649 /// Decomposes the given name into a DeclarationName, its location, and
00650 /// possibly a list of template arguments.
00651 ///
00652 /// If this produces template arguments, it is permitted to call
00653 /// DecomposeTemplateName.
00654 ///
00655 /// This actually loses a lot of source location information for
00656 /// non-standard name kinds; we should consider preserving that in
00657 /// some way.
00658 static void DecomposeUnqualifiedId(Sema &SemaRef,
00659                                    const UnqualifiedId &Id,
00660                                    TemplateArgumentListInfo &Buffer,
00661                                    DeclarationName &Name,
00662                                    SourceLocation &NameLoc,
00663                              const TemplateArgumentListInfo *&TemplateArgs) {
00664   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
00665     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
00666     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
00667 
00668     ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
00669                                        Id.TemplateId->getTemplateArgs(),
00670                                        Id.TemplateId->NumArgs);
00671     SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
00672     TemplateArgsPtr.release();
00673 
00674     TemplateName TName =
00675       Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
00676 
00677     Name = SemaRef.Context.getNameForTemplate(TName);
00678     NameLoc = Id.TemplateId->TemplateNameLoc;
00679     TemplateArgs = &Buffer;
00680   } else {
00681     Name = SemaRef.GetNameFromUnqualifiedId(Id);
00682     NameLoc = Id.StartLocation;
00683     TemplateArgs = 0;
00684   }
00685 }
00686 
00687 /// Decompose the given template name into a list of lookup results.
00688 ///
00689 /// The unqualified ID must name a non-dependent template, which can
00690 /// be more easily tested by checking whether DecomposeUnqualifiedId
00691 /// found template arguments.
00692 static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
00693   assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
00694   TemplateName TName =
00695     Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
00696 
00697   if (TemplateDecl *TD = TName.getAsTemplateDecl())
00698     R.addDecl(TD);
00699   else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
00700     for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
00701            I != E; ++I)
00702       R.addDecl(*I);
00703 
00704   R.resolveKind();
00705 }
00706 
00707 /// Determines whether the given record is "fully-formed" at the given
00708 /// location, i.e. whether a qualified lookup into it is assured of
00709 /// getting consistent results already.
00710 static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
00711   if (!Record->hasDefinition())
00712     return false;
00713 
00714   for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
00715          E = Record->bases_end(); I != E; ++I) {
00716     CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
00717     CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
00718     if (!BaseRT) return false;
00719 
00720     CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
00721     if (!BaseRecord->hasDefinition() ||
00722         !IsFullyFormedScope(SemaRef, BaseRecord))
00723       return false;
00724   }
00725 
00726   return true;
00727 }
00728 
00729 /// Determines whether we can lookup this id-expression now or whether
00730 /// we have to wait until template instantiation is complete.
00731 static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
00732   DeclContext *DC = SemaRef.computeDeclContext(SS, false);
00733 
00734   // If the qualifier scope isn't computable, it's definitely dependent.
00735   if (!DC) return true;
00736 
00737   // If the qualifier scope doesn't name a record, we can always look into it.
00738   if (!isa<CXXRecordDecl>(DC)) return false;
00739 
00740   // We can't look into record types unless they're fully-formed.
00741   if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
00742 
00743   return false;
00744 }
00745 
00746 /// Determines if the given class is provably not derived from all of
00747 /// the prospective base classes.
00748 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
00749                                      CXXRecordDecl *Record,
00750                             const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
00751   if (Bases.count(Record->getCanonicalDecl()))
00752     return false;
00753 
00754   RecordDecl *RD = Record->getDefinition();
00755   if (!RD) return false;
00756   Record = cast<CXXRecordDecl>(RD);
00757 
00758   for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
00759          E = Record->bases_end(); I != E; ++I) {
00760     CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
00761     CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
00762     if (!BaseRT) return false;
00763 
00764     CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
00765     if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
00766       return false;
00767   }
00768 
00769   return true;
00770 }
00771 
00772 /// Determines if this is an instance member of a class.
00773 static bool IsInstanceMember(NamedDecl *D) {
00774   assert(D->isCXXClassMember() &&
00775          "checking whether non-member is instance member");
00776 
00777   if (isa<FieldDecl>(D)) return true;
00778 
00779   if (isa<CXXMethodDecl>(D))
00780     return !cast<CXXMethodDecl>(D)->isStatic();
00781 
00782   if (isa<FunctionTemplateDecl>(D)) {
00783     D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
00784     return !cast<CXXMethodDecl>(D)->isStatic();
00785   }
00786 
00787   return false;
00788 }
00789 
00790 enum IMAKind {
00791   /// The reference is definitely not an instance member access.
00792   IMA_Static,
00793 
00794   /// The reference may be an implicit instance member access.
00795   IMA_Mixed,
00796 
00797   /// The reference may be to an instance member, but it is invalid if
00798   /// so, because the context is not an instance method.
00799   IMA_Mixed_StaticContext,
00800 
00801   /// The reference may be to an instance member, but it is invalid if
00802   /// so, because the context is from an unrelated class.
00803   IMA_Mixed_Unrelated,
00804 
00805   /// The reference is definitely an implicit instance member access.
00806   IMA_Instance,
00807 
00808   /// The reference may be to an unresolved using declaration.
00809   IMA_Unresolved,
00810 
00811   /// The reference may be to an unresolved using declaration and the
00812   /// context is not an instance method.
00813   IMA_Unresolved_StaticContext,
00814 
00815   /// The reference is to a member of an anonymous structure in a
00816   /// non-class context.
00817   IMA_AnonymousMember,
00818 
00819   /// All possible referrents are instance members and the current
00820   /// context is not an instance method.
00821   IMA_Error_StaticContext,
00822 
00823   /// All possible referrents are instance members of an unrelated
00824   /// class.
00825   IMA_Error_Unrelated
00826 };
00827 
00828 /// The given lookup names class member(s) and is not being used for
00829 /// an address-of-member expression.  Classify the type of access
00830 /// according to whether it's possible that this reference names an
00831 /// instance member.  This is best-effort; it is okay to
00832 /// conservatively answer "yes", in which case some errors will simply
00833 /// not be caught until template-instantiation.
00834 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
00835                                             const LookupResult &R) {
00836   assert(!R.empty() && (*R.begin())->isCXXClassMember());
00837 
00838   bool isStaticContext =
00839     (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
00840      cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
00841 
00842   if (R.isUnresolvableResult())
00843     return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
00844 
00845   // Collect all the declaring classes of instance members we find.
00846   bool hasNonInstance = false;
00847   llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
00848   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
00849     NamedDecl *D = (*I)->getUnderlyingDecl();
00850     if (IsInstanceMember(D)) {
00851       CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
00852 
00853       // If this is a member of an anonymous record, move out to the
00854       // innermost non-anonymous struct or union.  If there isn't one,
00855       // that's a special case.
00856       while (R->isAnonymousStructOrUnion()) {
00857         R = dyn_cast<CXXRecordDecl>(R->getParent());
00858         if (!R) return IMA_AnonymousMember;
00859       }
00860       Classes.insert(R->getCanonicalDecl());
00861     }
00862     else
00863       hasNonInstance = true;
00864   }
00865 
00866   // If we didn't find any instance members, it can't be an implicit
00867   // member reference.
00868   if (Classes.empty())
00869     return IMA_Static;
00870 
00871   // If the current context is not an instance method, it can't be
00872   // an implicit member reference.
00873   if (isStaticContext)
00874     return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
00875 
00876   // If we can prove that the current context is unrelated to all the
00877   // declaring classes, it can't be an implicit member reference (in
00878   // which case it's an error if any of those members are selected).
00879   if (IsProvablyNotDerivedFrom(SemaRef,
00880                         cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
00881                                Classes))
00882     return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
00883 
00884   return (hasNonInstance ? IMA_Mixed : IMA_Instance);
00885 }
00886 
00887 /// Diagnose a reference to a field with no object available.
00888 static void DiagnoseInstanceReference(Sema &SemaRef,
00889                                       const CXXScopeSpec &SS,
00890                                       const LookupResult &R) {
00891   SourceLocation Loc = R.getNameLoc();
00892   SourceRange Range(Loc);
00893   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
00894 
00895   if (R.getAsSingle<FieldDecl>()) {
00896     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
00897       if (MD->isStatic()) {
00898         // "invalid use of member 'x' in static member function"
00899         SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
00900           << Range << R.getLookupName();
00901         return;
00902       }
00903     }
00904 
00905     SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
00906       << R.getLookupName() << Range;
00907     return;
00908   }
00909 
00910   SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
00911 }
00912 
00913 /// Diagnose an empty lookup.
00914 ///
00915 /// \return false if new lookup candidates were found
00916 bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
00917                                LookupResult &R) {
00918   DeclarationName Name = R.getLookupName();
00919 
00920   unsigned diagnostic = diag::err_undeclared_var_use;
00921   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
00922   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
00923       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
00924       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
00925     diagnostic = diag::err_undeclared_use;
00926     diagnostic_suggest = diag::err_undeclared_use_suggest;
00927   }
00928 
00929   // If the original lookup was an unqualified lookup, fake an
00930   // unqualified lookup.  This is useful when (for example) the
00931   // original lookup would not have found something because it was a
00932   // dependent name.
00933   for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
00934        DC; DC = DC->getParent()) {
00935     if (isa<CXXRecordDecl>(DC)) {
00936       LookupQualifiedName(R, DC);
00937 
00938       if (!R.empty()) {
00939         // Don't give errors about ambiguities in this lookup.
00940         R.suppressDiagnostics();
00941 
00942         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
00943         bool isInstance = CurMethod &&
00944                           CurMethod->isInstance() &&
00945                           DC == CurMethod->getParent();
00946 
00947         // Give a code modification hint to insert 'this->'.
00948         // TODO: fixit for inserting 'Base<T>::' in the other cases.
00949         // Actually quite difficult!
00950         if (isInstance)
00951           Diag(R.getNameLoc(), diagnostic) << Name
00952             << CodeModificationHint::CreateInsertion(R.getNameLoc(),
00953                                                      "this->");
00954         else
00955           Diag(R.getNameLoc(), diagnostic) << Name;
00956 
00957         // Do we really want to note all of these?
00958         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
00959           Diag((*I)->getLocation(), diag::note_dependent_var_use);
00960 
00961         // Tell the callee to try to recover.
00962         return false;
00963       }
00964     }
00965   }
00966 
00967   // We didn't find anything, so try to correct for a typo.
00968   if (S && CorrectTypo(R, S, &SS)) {
00969     if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
00970       if (SS.isEmpty())
00971         Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
00972           << CodeModificationHint::CreateReplacement(R.getNameLoc(),
00973                                               R.getLookupName().getAsString());
00974       else
00975         Diag(R.getNameLoc(), diag::err_no_member_suggest)
00976           << Name << computeDeclContext(SS, false) << R.getLookupName()
00977           << SS.getRange()
00978           << CodeModificationHint::CreateReplacement(R.getNameLoc(),
00979                                               R.getLookupName().getAsString());
00980       if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
00981         Diag(ND->getLocation(), diag::note_previous_decl)
00982           << ND->getDeclName();
00983 
00984       // Tell the callee to try to recover.
00985       return false;
00986     }
00987 
00988     if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
00989       // FIXME: If we ended up with a typo for a type name or
00990       // Objective-C class name, we're in trouble because the parser
00991       // is in the wrong place to recover. Suggest the typo
00992       // correction, but don't make it a fix-it since we're not going
00993       // to recover well anyway.
00994       if (SS.isEmpty())
00995         Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
00996       else
00997         Diag(R.getNameLoc(), diag::err_no_member_suggest)
00998           << Name << computeDeclContext(SS, false) << R.getLookupName()
00999           << SS.getRange();
01000 
01001       // Don't try to recover; it won't work.
01002       return true;
01003     }
01004 
01005     R.clear();
01006   }
01007 
01008   // Emit a special diagnostic for failed member lookups.
01009   // FIXME: computing the declaration context might fail here (?)
01010   if (!SS.isEmpty()) {
01011     Diag(R.getNameLoc(), diag::err_no_member)
01012       << Name << computeDeclContext(SS, false)
01013       << SS.getRange();
01014     return true;
01015   }
01016 
01017   // Give up, we can't recover.
01018   Diag(R.getNameLoc(), diagnostic) << Name;
01019   return true;
01020 }
01021 
01022 Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
01023                                                const CXXScopeSpec &SS,
01024                                                UnqualifiedId &Id,
01025                                                bool HasTrailingLParen,
01026                                                bool isAddressOfOperand) {
01027   assert(!(isAddressOfOperand && HasTrailingLParen) &&
01028          "cannot be direct & operand and have a trailing lparen");
01029 
01030   if (SS.isInvalid())
01031     return ExprError();
01032 
01033   TemplateArgumentListInfo TemplateArgsBuffer;
01034 
01035   // Decompose the UnqualifiedId into the following data.
01036   DeclarationName Name;
01037   SourceLocation NameLoc;
01038   const TemplateArgumentListInfo *TemplateArgs;
01039   DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
01040                          Name, NameLoc, TemplateArgs);
01041 
01042   IdentifierInfo *II = Name.getAsIdentifierInfo();
01043 
01044   // C++ [temp.dep.expr]p3:
01045   //   An id-expression is type-dependent if it contains:
01046   //     -- an identifier that was declared with a dependent type,
01047   //        (note: handled after lookup)
01048   //     -- a template-id that is dependent,
01049   //        (note: handled in BuildTemplateIdExpr)
01050   //     -- a conversion-function-id that specifies a dependent type,
01051   //     -- a nested-name-specifier that contains a class-name that
01052   //        names a dependent type.
01053   // Determine whether this is a member of an unknown specialization;
01054   // we need to handle these differently.
01055   if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
01056        Name.getCXXNameType()->isDependentType()) ||
01057       (SS.isSet() && IsDependentIdExpression(*this, SS))) {
01058     return ActOnDependentIdExpression(SS, Name, NameLoc,
01059                                       isAddressOfOperand,
01060                                       TemplateArgs);
01061   }
01062 
01063   // Perform the required lookup.
01064   LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
01065   if (TemplateArgs) {
01066     // Just re-use the lookup done by isTemplateName.
01067     DecomposeTemplateName(R, Id);
01068   } else {
01069     bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
01070     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
01071 
01072     // If this reference is in an Objective-C method, then we need to do
01073     // some special Objective-C lookup, too.
01074     if (IvarLookupFollowUp) {
01075       OwningExprResult E(LookupInObjCMethod(R, S, II, true));
01076       if (E.isInvalid())
01077         return ExprError();
01078 
01079       Expr *Ex = E.takeAs<Expr>();
01080       if (Ex) return Owned(Ex);
01081     }
01082   }
01083 
01084   if (R.isAmbiguous())
01085     return ExprError();
01086 
01087   // Determine whether this name might be a candidate for
01088   // argument-dependent lookup.
01089   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
01090 
01091   if (R.empty() && !ADL) {
01092     // Otherwise, this could be an implicitly declared function reference (legal
01093     // in C90, extension in C99, forbidden in C++).
01094     if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
01095       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
01096       if (D) R.addDecl(D);
01097     }
01098 
01099     // If this name wasn't predeclared and if this is not a function
01100     // call, diagnose the problem.
01101     if (R.empty()) {
01102       if (DiagnoseEmptyLookup(S, SS, R))
01103         return ExprError();
01104 
01105       assert(!R.empty() &&
01106              "DiagnoseEmptyLookup returned false but added no results");
01107 
01108       // If we found an Objective-C instance variable, let
01109       // LookupInObjCMethod build the appropriate expression to
01110       // reference the ivar.
01111       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
01112         R.clear();
01113         OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
01114         assert(E.isInvalid() || E.get());
01115         return move(E);
01116       }
01117     }
01118   }
01119 
01120   // This is guaranteed from this point on.
01121   assert(!R.empty() || ADL);
01122 
01123   if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
01124     // Warn about constructs like:
01125     //   if (void *X = foo()) { ... } else { X }.
01126     // In the else block, the pointer is always false.
01127 
01128     if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
01129       Scope *CheckS = S;
01130       while (CheckS && CheckS->getControlParent()) {
01131         if (CheckS->isWithinElse() &&
01132             CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
01133           ExprError(Diag(NameLoc, diag::warn_value_always_zero)
01134             << Var->getDeclName()
01135             << (Var->getType()->isPointerType()? 2 :
01136                 Var->getType()->isBooleanType()? 1 : 0));
01137           break;
01138         }
01139 
01140         // Move to the parent of this scope.
01141         CheckS = CheckS->getParent();
01142       }
01143     }
01144   } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
01145     if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
01146       // C99 DR 316 says that, if a function type comes from a
01147       // function definition (without a prototype), that type is only
01148       // used for checking compatibility. Therefore, when referencing
01149       // the function, we pretend that we don't have the full function
01150       // type.
01151       if (DiagnoseUseOfDecl(Func, NameLoc))
01152         return ExprError();
01153 
01154       QualType T = Func->getType();
01155       QualType NoProtoType = T;
01156       if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
01157         NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
01158       return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
01159     }
01160   }
01161 
01162   // Check whether this might be a C++ implicit instance member access.
01163   // C++ [expr.prim.general]p6:
01164   //   Within the definition of a non-static member function, an
01165   //   identifier that names a non-static member is transformed to a
01166   //   class member access expression.
01167   // But note that &SomeClass::foo is grammatically distinct, even
01168   // though we don't parse it that way.
01169   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
01170     bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
01171     if (!isAbstractMemberPointer)
01172       return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
01173   }
01174 
01175   if (TemplateArgs)
01176     return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
01177 
01178   return BuildDeclarationNameExpr(SS, R, ADL);
01179 }
01180 
01181 /// Builds an expression which might be an implicit member expression.
01182 Sema::OwningExprResult
01183 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
01184                                       LookupResult &R,
01185                                 const TemplateArgumentListInfo *TemplateArgs) {
01186   switch (ClassifyImplicitMemberAccess(*this, R)) {
01187   case IMA_Instance:
01188     return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
01189 
01190   case IMA_AnonymousMember:
01191     assert(R.isSingleResult());
01192     return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
01193                                                     R.getAsSingle<FieldDecl>());
01194 
01195   case IMA_Mixed:
01196   case IMA_Mixed_Unrelated:
01197   case IMA_Unresolved:
01198     return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
01199 
01200   case IMA_Static:
01201   case IMA_Mixed_StaticContext:
01202   case IMA_Unresolved_StaticContext:
01203     if (TemplateArgs)
01204       return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
01205     return BuildDeclarationNameExpr(SS, R, false);
01206 
01207   case IMA_Error_StaticContext:
01208   case IMA_Error_Unrelated:
01209     DiagnoseInstanceReference(*this, SS, R);
01210     return ExprError();
01211   }
01212 
01213   llvm_unreachable("unexpected instance member access kind");
01214   return ExprError();
01215 }
01216 
01217 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
01218 /// declaration name, generally during template instantiation.
01219 /// There's a large number of things which don't need to be done along
01220 /// this path.
01221 Sema::OwningExprResult
01222 Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
01223                                         DeclarationName Name,
01224                                         SourceLocation NameLoc) {
01225   DeclContext *DC;
01226   if (!(DC = computeDeclContext(SS, false)) ||
01227       DC->isDependentContext() ||
01228       RequireCompleteDeclContext(SS))
01229     return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
01230 
01231   LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
01232   LookupQualifiedName(R, DC);
01233 
01234   if (R.isAmbiguous())
01235     return ExprError();
01236 
01237   if (R.empty()) {
01238     Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
01239     return ExprError();
01240   }
01241 
01242   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
01243 }
01244 
01245 /// LookupInObjCMethod - The parser has read a name in, and Sema has
01246 /// detected that we're currently inside an ObjC method.  Perform some
01247 /// additional lookup.
01248 ///
01249 /// Ideally, most of this would be done by lookup, but there's
01250 /// actually quite a lot of extra work involved.
01251 ///
01252 /// Returns a null sentinel to indicate trivial success.
01253 Sema::OwningExprResult
01254 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
01255                          IdentifierInfo *II,
01256                          bool AllowBuiltinCreation) {
01257   SourceLocation Loc = Lookup.getNameLoc();
01258 
01259   // There are two cases to handle here.  1) scoped lookup could have failed,
01260   // in which case we should look for an ivar.  2) scoped lookup could have
01261   // found a decl, but that decl is outside the current instance method (i.e.
01262   // a global variable).  In these two cases, we do a lookup for an ivar with
01263   // this name, if the lookup sucedes, we replace it our current decl.
01264 
01265   // If we're in a class method, we don't normally want to look for
01266   // ivars.  But if we don't find anything else, and there's an
01267   // ivar, that's an error.
01268   bool IsClassMethod = getCurMethodDecl()->isClassMethod();
01269 
01270   bool LookForIvars;
01271   if (Lookup.empty())
01272     LookForIvars = true;
01273   else if (IsClassMethod)
01274     LookForIvars = false;
01275   else
01276     LookForIvars = (Lookup.isSingleResult() &&
01277                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
01278   ObjCInterfaceDecl *IFace = 0;
01279   if (LookForIvars) {
01280     IFace = getCurMethodDecl()->getClassInterface();
01281     ObjCInterfaceDecl *ClassDeclared;
01282     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
01283       // Diagnose using an ivar in a class method.
01284       if (IsClassMethod)
01285         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
01286                          << IV->getDeclName());
01287 
01288       // If we're referencing an invalid decl, just return this as a silent
01289       // error node.  The error diagnostic was already emitted on the decl.
01290       if (IV->isInvalidDecl())
01291         return ExprError();
01292 
01293       // Check if referencing a field with __attribute__((deprecated)).
01294       if (DiagnoseUseOfDecl(IV, Loc))
01295         return ExprError();
01296 
01297       // Diagnose the use of an ivar outside of the declaring class.
01298       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
01299           ClassDeclared != IFace)
01300         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
01301 
01302       // FIXME: This should use a new expr for a direct reference, don't
01303       // turn this into Self->ivar, just return a BareIVarExpr or something.
01304       IdentifierInfo &II = Context.Idents.get("self");
01305       UnqualifiedId SelfName;
01306       SelfName.setIdentifier(&II, SourceLocation());
01307       CXXScopeSpec SelfScopeSpec;
01308       OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
01309                                                     SelfName, false, false);
01310       MarkDeclarationReferenced(Loc, IV);
01311       return Owned(new (Context)
01312                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
01313                                    SelfExpr.takeAs<Expr>(), true, true));
01314     }
01315   } else if (getCurMethodDecl()->isInstanceMethod()) {
01316     // We should warn if a local variable hides an ivar.
01317     ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
01318     ObjCInterfaceDecl *ClassDeclared;
01319     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
01320       if (IV->getAccessControl() != ObjCIvarDecl::Private ||
01321           IFace == ClassDeclared)
01322         Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
01323     }
01324   }
01325 
01326   // Needed to implement property "super.method" notation.
01327   if (Lookup.empty() && II->isStr("super")) {
01328     QualType T;
01329 
01330     if (getCurMethodDecl()->isInstanceMethod())
01331       T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
01332                                     getCurMethodDecl()->getClassInterface()));
01333     else
01334       T = Context.getObjCClassType();
01335     return Owned(new (Context) ObjCSuperExpr(Loc, T));
01336   }
01337   if (Lookup.empty() && II && AllowBuiltinCreation) {
01338     // FIXME. Consolidate this with similar code in LookupName.
01339     if (unsigned BuiltinID = II->getBuiltinID()) {
01340       if (!(getLangOptions().CPlusPlus &&
01341             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
01342         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
01343                                            S, Lookup.isForRedeclaration(),
01344                                            Lookup.getNameLoc());
01345         if (D) Lookup.addDecl(D);
01346       }
01347     }
01348   }
01349   if (LangOpts.ObjCNonFragileABI2 && LookForIvars && Lookup.empty()) {
01350     ObjCIvarDecl *Ivar = SynthesizeNewPropertyIvar(IFace, II);
01351     if (Ivar)
01352       return LookupInObjCMethod(Lookup, S, II, AllowBuiltinCreation);
01353   }
01354   // Sentinel value saying that we didn't do anything special.
01355   return Owned((Expr*) 0);
01356 }
01357 
01358 /// \brief Cast member's object to its own class if necessary.
01359 bool
01360 Sema::PerformObjectMemberConversion(Expr *&From,
01361                                     NestedNameSpecifier *Qualifier,
01362                                     NamedDecl *Member) {
01363   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
01364   if (!RD)
01365     return false;
01366 
01367   QualType DestRecordType;
01368   QualType DestType;
01369   QualType FromRecordType;
01370   QualType FromType = From->getType();
01371   bool PointerConversions = false;
01372   if (isa<FieldDecl>(Member)) {
01373     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
01374 
01375     if (FromType->getAs<PointerType>()) {
01376       DestType = Context.getPointerType(DestRecordType);
01377       FromRecordType = FromType->getPointeeType();
01378       PointerConversions = true;
01379     } else {
01380       DestType = DestRecordType;
01381       FromRecordType = FromType;
01382     }
01383   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
01384     if (Method->isStatic())
01385       return false;
01386 
01387     DestType = Method->getThisType(Context);
01388     DestRecordType = DestType->getPointeeType();
01389 
01390     if (FromType->getAs<PointerType>()) {
01391       FromRecordType = FromType->getPointeeType();
01392       PointerConversions = true;
01393     } else {
01394       FromRecordType = FromType;
01395       DestType = DestRecordType;
01396     }
01397   } else {
01398     // No conversion necessary.
01399     return false;
01400   }
01401 
01402   if (DestType->isDependentType() || FromType->isDependentType())
01403     return false;
01404 
01405   // If the unqualified types are the same, no conversion is necessary.
01406   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
01407     return false;
01408 
01409   // C++ [class.member.lookup]p8:
01410   //   [...] Ambiguities can often be resolved by qualifying a name with its
01411   //   class name.
01412   //
01413   // If the member was a qualified name and the qualified referred to a
01414   // specific base subobject type, we'll cast to that intermediate type
01415   // first and then to the object in which the member is declared. That allows
01416   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
01417   //
01418   //   class Base { public: int x; };
01419   //   class Derived1 : public Base { };
01420   //   class Derived2 : public Base { };
01421   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
01422   //
01423   //   void VeryDerived::f() {
01424   //     x = 17; // error: ambiguous base subobjects
01425   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
01426   //   }
01427   QualType IntermediateRecordType;
01428   QualType IntermediateType;
01429   if (Qualifier) {
01430     if (const RecordType *IntermediateRecord
01431                            = Qualifier->getAsType()->getAs<RecordType>()) {
01432       IntermediateRecordType = QualType(IntermediateRecord, 0);
01433       IntermediateType = IntermediateRecordType;
01434       if (PointerConversions)
01435         IntermediateType = Context.getPointerType(IntermediateType);
01436     }
01437   }
01438 
01439   if (!IntermediateType.isNull() &&
01440       IsDerivedFrom(FromRecordType, IntermediateRecordType) &&
01441       IsDerivedFrom(IntermediateRecordType, DestRecordType)) {
01442     if (CheckDerivedToBaseConversion(FromRecordType, IntermediateRecordType,
01443                                      From->getSourceRange().getBegin(),
01444                                      From->getSourceRange()) ||
01445         CheckDerivedToBaseConversion(IntermediateRecordType, DestRecordType,
01446                                      From->getSourceRange().getBegin(),
01447                                      From->getSourceRange()))
01448       return true;
01449 
01450     ImpCastExprToType(From, IntermediateType, CastExpr::CK_DerivedToBase,
01451                       /*isLvalue=*/!PointerConversions);
01452     ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
01453                       /*isLvalue=*/!PointerConversions);
01454     return false;
01455   }
01456 
01457   if (CheckDerivedToBaseConversion(FromRecordType,
01458                                    DestRecordType,
01459                                    From->getSourceRange().getBegin(),
01460                                    From->getSourceRange()))
01461     return true;
01462 
01463   ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
01464                     /*isLvalue=*/true);
01465   return false;
01466 }
01467 
01468 /// \brief Build a MemberExpr AST node.
01469 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
01470                                    const CXXScopeSpec &SS, ValueDecl *Member,
01471                                    SourceLocation Loc, QualType Ty,
01472                           const TemplateArgumentListInfo *TemplateArgs = 0) {
01473   NestedNameSpecifier *Qualifier = 0;
01474   SourceRange QualifierRange;
01475   if (SS.isSet()) {
01476     Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
01477     QualifierRange = SS.getRange();
01478   }
01479 
01480   return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
01481                             Member, Loc, TemplateArgs, Ty);
01482 }
01483 
01484 /// Builds an implicit member access expression.  The current context
01485 /// is known to be an instance method, and the given unqualified lookup
01486 /// set is known to contain only instance members, at least one of which
01487 /// is from an appropriate type.
01488 Sema::OwningExprResult
01489 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
01490                               LookupResult &R,
01491                               const TemplateArgumentListInfo *TemplateArgs,
01492                               bool IsKnownInstance) {
01493   assert(!R.empty() && !R.isAmbiguous());
01494 
01495   SourceLocation Loc = R.getNameLoc();
01496 
01497   // We may have found a field within an anonymous union or struct
01498   // (C++ [class.union]).
01499   // FIXME: This needs to happen post-isImplicitMemberReference?
01500   // FIXME: template-ids inside anonymous structs?
01501   if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
01502     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
01503       return BuildAnonymousStructUnionMemberReference(Loc, FD);
01504 
01505   // If this is known to be an instance access, go ahead and build a
01506   // 'this' expression now.
01507   QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
01508   Expr *This = 0; // null signifies implicit access
01509   if (IsKnownInstance) {
01510     SourceLocation Loc = R.getNameLoc();
01511     if (SS.getRange().isValid())
01512       Loc = SS.getRange().getBegin();
01513     This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
01514   }
01515 
01516   return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
01517                                   /*OpLoc*/ SourceLocation(),
01518                                   /*IsArrow*/ true,
01519                                   SS,
01520                                   /*FirstQualifierInScope*/ 0,
01521                                   R, TemplateArgs);
01522 }
01523 
01524 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
01525                                       const LookupResult &R,
01526                                       bool HasTrailingLParen) {
01527   // Only when used directly as the postfix-expression of a call.
01528   if (!HasTrailingLParen)
01529     return false;
01530 
01531   // Never if a scope specifier was provided.
01532   if (SS.isSet())
01533     return false;
01534 
01535   // Only in C++ or ObjC++.
01536   if (!getLangOptions().CPlusPlus)
01537     return false;
01538 
01539   // Turn off ADL when we find certain kinds of declarations during
01540   // normal lookup:
01541   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
01542     NamedDecl *D = *I;
01543 
01544     // C++0x [basic.lookup.argdep]p3:
01545     //     -- a declaration of a class member
01546     // Since using decls preserve this property, we check this on the
01547     // original decl.
01548     if (D->isCXXClassMember())
01549       return false;
01550 
01551     // C++0x [basic.lookup.argdep]p3:
01552     //     -- a block-scope function declaration that is not a
01553     //        using-declaration
01554     // NOTE: we also trigger this for function templates (in fact, we
01555     // don't check the decl type at all, since all other decl types
01556     // turn off ADL anyway).
01557     if (isa<UsingShadowDecl>(D))
01558       D = cast<UsingShadowDecl>(D)->getTargetDecl();
01559     else if (D->getDeclContext()->isFunctionOrMethod())
01560       return false;
01561 
01562     // C++0x [basic.lookup.argdep]p3:
01563     //     -- a declaration that is neither a function or a function
01564     //        template
01565     // And also for builtin functions.
01566     if (isa<FunctionDecl>(D)) {
01567       FunctionDecl *FDecl = cast<FunctionDecl>(D);
01568 
01569       // But also builtin functions.
01570       if (FDecl->getBuiltinID() && FDecl->isImplicit())
01571         return false;
01572     } else if (!isa<FunctionTemplateDecl>(D))
01573       return false;
01574   }
01575 
01576   return true;
01577 }
01578 
01579 
01580 /// Diagnoses obvious problems with the use of the given declaration
01581 /// as an expression.  This is only actually called for lookups that
01582 /// were not overloaded, and it doesn't promise that the declaration
01583 /// will in fact be used.
01584 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
01585   if (isa<TypedefDecl>(D)) {
01586     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
01587     return true;
01588   }
01589 
01590   if (isa<ObjCInterfaceDecl>(D)) {
01591     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
01592     return true;
01593   }
01594 
01595   if (isa<NamespaceDecl>(D)) {
01596     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
01597     return true;
01598   }
01599 
01600   return false;
01601 }
01602 
01603 Sema::OwningExprResult
01604 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
01605                                LookupResult &R,
01606                                bool NeedsADL) {
01607   // If this is a single, fully-resolved result and we don't need ADL,
01608   // just build an ordinary singleton decl ref.
01609   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
01610     return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
01611 
01612   // We only need to check the declaration if there's exactly one
01613   // result, because in the overloaded case the results can only be
01614   // functions and function templates.
01615   if (R.isSingleResult() &&
01616       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
01617     return ExprError();
01618 
01619   // Otherwise, just build an unresolved lookup expression.  Suppress
01620   // any lookup-related diagnostics; we'll hash these out later, when
01621   // we've picked a target.
01622   R.suppressDiagnostics();
01623 
01624   bool Dependent
01625     = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
01626   UnresolvedLookupExpr *ULE
01627     = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
01628                                    (NestedNameSpecifier*) SS.getScopeRep(),
01629                                    SS.getRange(),
01630                                    R.getLookupName(), R.getNameLoc(),
01631                                    NeedsADL, R.isOverloadedResult());
01632   ULE->addDecls(R.begin(), R.end());
01633 
01634   return Owned(ULE);
01635 }
01636 
01637 
01638 /// \brief Complete semantic analysis for a reference to the given declaration.
01639 Sema::OwningExprResult
01640 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
01641                                SourceLocation Loc, NamedDecl *D) {
01642   assert(D && "Cannot refer to a NULL declaration");
01643   assert(!isa<FunctionTemplateDecl>(D) &&
01644          "Cannot refer unambiguously to a function template");
01645 
01646   if (CheckDeclInExpr(*this, Loc, D))
01647     return ExprError();
01648 
01649   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
01650     // Specifically diagnose references to class templates that are missing
01651     // a template argument list.
01652     Diag(Loc, diag::err_template_decl_ref)
01653       << Template << SS.getRange();
01654     Diag(Template->getLocation(), diag::note_template_decl_here);
01655     return ExprError();
01656   }
01657 
01658   // Make sure that we're referring to a value.
01659   ValueDecl *VD = dyn_cast<ValueDecl>(D);
01660   if (!VD) {
01661     Diag(Loc, diag::err_ref_non_value)
01662       << D << SS.getRange();
01663     Diag(D->getLocation(), diag::note_declared_at);
01664     return ExprError();
01665   }
01666 
01667   // Check whether this declaration can be used. Note that we suppress
01668   // this check when we're going to perform argument-dependent lookup
01669   // on this function name, because this might not be the function
01670   // that overload resolution actually selects.
01671   if (DiagnoseUseOfDecl(VD, Loc))
01672     return ExprError();
01673 
01674   // Only create DeclRefExpr's for valid Decl's.
01675   if (VD->isInvalidDecl())
01676     return ExprError();
01677 
01678   // If the identifier reference is inside a block, and it refers to a value
01679   // that is outside the block, create a BlockDeclRefExpr instead of a
01680   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
01681   // the block is formed.
01682   //
01683   // We do not do this for things like enum constants, global variables, etc,
01684   // as they do not get snapshotted.
01685   //
01686   if (getCurBlock() &&
01687       ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
01688     if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
01689       Diag(Loc, diag::err_ref_vm_type);
01690       Diag(D->getLocation(), diag::note_declared_at);
01691       return ExprError();
01692     }
01693 
01694     if (VD->getType()->isArrayType() && !VD->hasAttr<BlocksAttr>()) {
01695       Diag(Loc, diag::err_ref_array_type);
01696       Diag(D->getLocation(), diag::note_declared_at);
01697       return ExprError();
01698     }
01699 
01700     MarkDeclarationReferenced(Loc, VD);
01701     QualType ExprTy = VD->getType().getNonReferenceType();
01702     // The BlocksAttr indicates the variable is bound by-reference.
01703     if (VD->getAttr<BlocksAttr>())
01704       return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
01705     // This is to record that a 'const' was actually synthesize and added.
01706     bool constAdded = !ExprTy.isConstQualified();
01707     // Variable will be bound by-copy, make it const within the closure.
01708 
01709     ExprTy.addConst();
01710     return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
01711                                                 constAdded));
01712   }
01713   // If this reference is not in a block or if the referenced variable is
01714   // within the block, create a normal DeclRefExpr.
01715 
01716   return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
01717 }
01718 
01719 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
01720                                                  tok::TokenKind Kind) {
01721   PredefinedExpr::IdentType IT;
01722 
01723   switch (Kind) {
01724   default: assert(0 && "Unknown simple primary expr!");
01725   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
01726   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
01727   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
01728   }
01729 
01730   // Pre-defined identifiers are of type char[x], where x is the length of the
01731   // string.
01732 
01733   Decl *currentDecl = getCurFunctionOrMethodDecl();
01734   if (!currentDecl) {
01735     Diag(Loc, diag::ext_predef_outside_function);
01736     currentDecl = Context.getTranslationUnitDecl();
01737   }
01738 
01739   QualType ResTy;
01740   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
01741     ResTy = Context.DependentTy;
01742   } else {
01743     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
01744 
01745     llvm::APInt LengthI(32, Length + 1);
01746     ResTy = Context.CharTy.withConst();
01747     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
01748   }
01749   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
01750 }
01751 
01752 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
01753   llvm::SmallString<16> CharBuffer;
01754   llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer);
01755 
01756   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
01757                             PP);
01758   if (Literal.hadError())
01759     return ExprError();
01760 
01761   QualType Ty;
01762   if (!getLangOptions().CPlusPlus)
01763     Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
01764   else if (Literal.isWide())
01765     Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
01766   else if (Literal.isMultiChar())
01767     Ty = Context.IntTy;   // 'wxyz' -> int in C++.
01768   else
01769     Ty = Context.CharTy;  // 'x' -> char in C++
01770 
01771   return Owned(new (Context) CharacterLiteral(Literal.getValue(),
01772                                               Literal.isWide(),
01773                                               Ty, Tok.getLocation()));
01774 }
01775 
01776 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
01777   // Fast path for a single digit (which is quite common).  A single digit
01778   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
01779   if (Tok.getLength() == 1) {
01780     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
01781     unsigned IntSize = Context.Target.getIntWidth();
01782     return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
01783                     Context.IntTy, Tok.getLocation()));
01784   }
01785 
01786   llvm::SmallString<512> IntegerBuffer;
01787   // Add padding so that NumericLiteralParser can overread by one character.
01788   IntegerBuffer.resize(Tok.getLength()+1);
01789   const char *ThisTokBegin = &IntegerBuffer[0];
01790 
01791   // Get the spelling of the token, which eliminates trigraphs, etc.
01792   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
01793 
01794   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
01795                                Tok.getLocation(), PP);
01796   if (Literal.hadError)
01797     return ExprError();
01798 
01799   Expr *Res;
01800 
01801   if (Literal.isFloatingLiteral()) {
01802     QualType Ty;
01803     if (Literal.isFloat)
01804       Ty = Context.FloatTy;
01805     else if (!Literal.isLong)
01806       Ty = Context.DoubleTy;
01807     else
01808       Ty = Context.LongDoubleTy;
01809 
01810     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
01811 
01812     using llvm::APFloat;
01813     APFloat Val(Format);
01814 
01815     APFloat::opStatus result = Literal.GetFloatValue(Val);
01816 
01817     // Overflow is always an error, but underflow is only an error if
01818     // we underflowed to zero (APFloat reports denormals as underflow).
01819     if ((result & APFloat::opOverflow) ||
01820         ((result & APFloat::opUnderflow) && Val.isZero())) {
01821       unsigned diagnostic;
01822       llvm::SmallString<20> buffer;
01823       if (result & APFloat::opOverflow) {
01824         diagnostic = diag::warn_float_overflow;
01825         APFloat::getLargest(Format).toString(buffer);
01826       } else {
01827         diagnostic = diag::warn_float_underflow;
01828         APFloat::getSmallest(Format).toString(buffer);
01829       }
01830 
01831       Diag(Tok.getLocation(), diagnostic)
01832         << Ty
01833         << llvm::StringRef(buffer.data(), buffer.size());
01834     }
01835 
01836     bool isExact = (result == APFloat::opOK);
01837     Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
01838 
01839   } else if (!Literal.isIntegerLiteral()) {
01840     return ExprError();
01841   } else {
01842     QualType Ty;
01843 
01844     // long long is a C99 feature.
01845     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
01846         Literal.isLongLong)
01847       Diag(Tok.getLocation(), diag::ext_longlong);
01848 
01849     // Get the value in the widest-possible width.
01850     llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
01851 
01852     if (Literal.GetIntegerValue(ResultVal)) {
01853       // If this value didn't fit into uintmax_t, warn and force to ull.
01854       Diag(Tok.getLocation(), diag::warn_integer_too_large);
01855       Ty = Context.UnsignedLongLongTy;
01856       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
01857              "long long is not intmax_t?");
01858     } else {
01859       // If this value fits into a ULL, try to figure out what else it fits into
01860       // according to the rules of C99 6.4.4.1p5.
01861 
01862       // Octal, Hexadecimal, and integers with a U suffix are allowed to
01863       // be an unsigned int.
01864       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
01865 
01866       // Check from smallest to largest, picking the smallest type we can.
01867       unsigned Width = 0;
01868       if (!Literal.isLong && !Literal.isLongLong) {
01869         // Are int/unsigned possibilities?
01870         unsigned IntSize = Context.Target.getIntWidth();
01871 
01872         // Does it fit in a unsigned int?
01873         if (ResultVal.isIntN(IntSize)) {
01874           // Does it fit in a signed int?
01875           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
01876             Ty = Context.IntTy;
01877           else if (AllowUnsigned)
01878             Ty = Context.UnsignedIntTy;
01879           Width = IntSize;
01880         }
01881       }
01882 
01883       // Are long/unsigned long possibilities?
01884       if (Ty.isNull() && !Literal.isLongLong) {
01885         unsigned LongSize = Context.Target.getLongWidth();
01886 
01887         // Does it fit in a unsigned long?
01888         if (ResultVal.isIntN(LongSize)) {
01889           // Does it fit in a signed long?
01890           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
01891             Ty = Context.LongTy;
01892           else if (AllowUnsigned)
01893             Ty = Context.UnsignedLongTy;
01894           Width = LongSize;
01895         }
01896       }
01897 
01898       // Finally, check long long if needed.
01899       if (Ty.isNull()) {
01900         unsigned LongLongSize = Context.Target.getLongLongWidth();
01901 
01902         // Does it fit in a unsigned long long?
01903         if (ResultVal.isIntN(LongLongSize)) {
01904           // Does it fit in a signed long long?
01905           if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
01906             Ty = Context.LongLongTy;
01907           else if (AllowUnsigned)
01908             Ty = Context.UnsignedLongLongTy;
01909           Width = LongLongSize;
01910         }
01911       }
01912 
01913       // If we still couldn't decide a type, we probably have something that
01914       // does not fit in a signed long long, but has no U suffix.
01915       if (Ty.isNull()) {
01916         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
01917         Ty = Context.UnsignedLongLongTy;
01918         Width = Context.Target.getLongLongWidth();
01919       }
01920 
01921       if (ResultVal.getBitWidth() != Width)
01922         ResultVal.trunc(Width);
01923     }
01924     Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
01925   }
01926 
01927   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
01928   if (Literal.isImaginary)
01929     Res = new (Context) ImaginaryLiteral(Res,
01930                                         Context.getComplexType(Res->getType()));
01931 
01932   return Owned(Res);
01933 }
01934 
01935 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
01936                                               SourceLocation R, ExprArg Val) {
01937   Expr *E = Val.takeAs<Expr>();
01938   assert((E != 0) && "ActOnParenExpr() missing expr");
01939   return Owned(new (Context) ParenExpr(L, R, E));
01940 }
01941 
01942 /// The UsualUnaryConversions() function is *not* called by this routine.
01943 /// See C99 6.3.2.1p[2-4] for more details.
01944 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
01945                                      SourceLocation OpLoc,
01946                                      const SourceRange &ExprRange,
01947                                      bool isSizeof) {
01948   if (exprType->isDependentType())
01949     return false;
01950 
01951   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
01952   //   the result is the size of the referenced type."
01953   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
01954   //   result shall be the alignment of the referenced type."
01955   if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
01956     exprType = Ref->getPointeeType();
01957 
01958   // C99 6.5.3.4p1:
01959   if (exprType->isFunctionType()) {
01960     // alignof(function) is allowed as an extension.
01961     if (isSizeof)
01962       Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
01963     return false;
01964   }
01965 
01966   // Allow sizeof(void)/alignof(void) as an extension.
01967   if (exprType->isVoidType()) {
01968     Diag(OpLoc, diag::ext_sizeof_void_type)
01969       << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
01970     return false;
01971   }
01972 
01973   if (RequireCompleteType(OpLoc, exprType,
01974                           PDiag(diag::err_sizeof_alignof_incomplete_type)
01975                           << int(!isSizeof) << ExprRange))
01976     return true;
01977 
01978   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
01979   if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
01980     Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
01981       << exprType << isSizeof << ExprRange;
01982     return true;
01983   }
01984 
01985   return false;
01986 }
01987 
01988 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
01989                             const SourceRange &ExprRange) {
01990   E = E->IgnoreParens();
01991 
01992   // alignof decl is always ok.
01993   if (isa<DeclRefExpr>(E))
01994     return false;
01995 
01996   // Cannot know anything else if the expression is dependent.
01997   if (E->isTypeDependent())
01998     return false;
01999 
02000   if (E->getBitField()) {
02001     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
02002     return true;
02003   }
02004 
02005   // Alignment of a field access is always okay, so long as it isn't a
02006   // bit-field.
02007   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
02008     if (isa<FieldDecl>(ME->getMemberDecl()))
02009       return false;
02010 
02011   return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
02012 }
02013 
02014 /// \brief Build a sizeof or alignof expression given a type operand.
02015 Action::OwningExprResult
02016 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
02017                               SourceLocation OpLoc,
02018                               bool isSizeOf, SourceRange R) {
02019   if (!TInfo)
02020     return ExprError();
02021 
02022   QualType T = TInfo->getType();
02023 
02024   if (!T->isDependentType() &&
02025       CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
02026     return ExprError();
02027 
02028   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
02029   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
02030                                                Context.getSizeType(), OpLoc,
02031                                                R.getEnd()));
02032 }
02033 
02034 /// \brief Build a sizeof or alignof expression given an expression
02035 /// operand.
02036 Action::OwningExprResult
02037 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
02038                               bool isSizeOf, SourceRange R) {
02039   // Verify that the operand is valid.
02040   bool isInvalid = false;
02041   if (E->isTypeDependent()) {
02042     // Delay type-checking for type-dependent expressions.
02043   } else if (!isSizeOf) {
02044     isInvalid = CheckAlignOfExpr(E, OpLoc, R);
02045   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
02046     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
02047     isInvalid = true;
02048   } else {
02049     isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
02050   }
02051 
02052   if (isInvalid)
02053     return ExprError();
02054 
02055   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
02056   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
02057                                                Context.getSizeType(), OpLoc,
02058                                                R.getEnd()));
02059 }
02060 
02061 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
02062 /// the same for @c alignof and @c __alignof
02063 /// Note that the ArgRange is invalid if isType is false.
02064 Action::OwningExprResult
02065 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
02066                              void *TyOrEx, const SourceRange &ArgRange) {
02067   // If error parsing type, ignore.
02068   if (TyOrEx == 0) return ExprError();
02069 
02070   if (isType) {
02071     TypeSourceInfo *TInfo;
02072     (void) GetTypeFromParser(TyOrEx, &TInfo);
02073     return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
02074   }
02075 
02076   Expr *ArgEx = (Expr *)TyOrEx;
02077   Action::OwningExprResult Result
02078     = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
02079 
02080   if (Result.isInvalid())
02081     DeleteExpr(ArgEx);
02082 
02083   return move(Result);
02084 }
02085 
02086 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
02087   if (V->isTypeDependent())
02088     return Context.DependentTy;
02089 
02090   // These operators return the element type of a complex type.
02091   if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
02092     return CT->getElementType();
02093 
02094   // Otherwise they pass through real integer and floating point types here.
02095   if (V->getType()->isArithmeticType())
02096     return V->getType();
02097 
02098   // Reject anything else.
02099   Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
02100     << (isReal ? "__real" : "__imag");
02101   return QualType();
02102 }
02103 
02104 
02105 
02106 Action::OwningExprResult
02107 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
02108                           tok::TokenKind Kind, ExprArg Input) {
02109   UnaryOperator::Opcode Opc;
02110   switch (Kind) {
02111   default: assert(0 && "Unknown unary op!");
02112   case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
02113   case tok::minusminus: Opc = UnaryOperator::PostDec; break;
02114   }
02115 
02116   return BuildUnaryOp(S, OpLoc, Opc, move(Input));
02117 }
02118 
02119 Action::OwningExprResult
02120 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
02121                               ExprArg Idx, SourceLocation RLoc) {
02122   // Since this might be a postfix expression, get rid of ParenListExprs.
02123   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
02124 
02125   Expr *LHSExp = static_cast<Expr*>(Base.get()),
02126        *RHSExp = static_cast<Expr*>(Idx.get());
02127 
02128   if (getLangOptions().CPlusPlus &&
02129       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
02130     Base.release();
02131     Idx.release();
02132     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
02133                                                   Context.DependentTy, RLoc));
02134   }
02135 
02136   if (getLangOptions().CPlusPlus &&
02137       (LHSExp->getType()->isRecordType() ||
02138        LHSExp->getType()->isEnumeralType() ||
02139        RHSExp->getType()->isRecordType() ||
02140        RHSExp->getType()->isEnumeralType())) {
02141     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
02142   }
02143 
02144   return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
02145 }
02146 
02147 
02148 Action::OwningExprResult
02149 Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
02150                                      ExprArg Idx, SourceLocation RLoc) {
02151   Expr *LHSExp = static_cast<Expr*>(Base.get());
02152   Expr *RHSExp = static_cast<Expr*>(Idx.get());
02153 
02154   // Perform default conversions.
02155   if (!LHSExp->getType()->getAs<VectorType>())
02156       DefaultFunctionArrayLvalueConversion(LHSExp);
02157   DefaultFunctionArrayLvalueConversion(RHSExp);
02158 
02159   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
02160 
02161   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
02162   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
02163   // in the subscript position. As a result, we need to derive the array base
02164   // and index from the expression types.
02165   Expr *BaseExpr, *IndexExpr;
02166   QualType ResultType;
02167   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
02168     BaseExpr = LHSExp;
02169     IndexExpr = RHSExp;
02170     ResultType = Context.DependentTy;
02171   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
02172     BaseExpr = LHSExp;
02173     IndexExpr = RHSExp;
02174     ResultType = PTy->getPointeeType();
02175   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
02176      // Handle the uncommon case of "123[Ptr]".
02177     BaseExpr = RHSExp;
02178     IndexExpr = LHSExp;
02179     ResultType = PTy->getPointeeType();
02180   } else if (const ObjCObjectPointerType *PTy =
02181                LHSTy->getAs<ObjCObjectPointerType>()) {
02182     BaseExpr = LHSExp;
02183     IndexExpr = RHSExp;
02184     ResultType = PTy->getPointeeType();
02185   } else if (const ObjCObjectPointerType *PTy =
02186                RHSTy->getAs<ObjCObjectPointerType>()) {
02187      // Handle the uncommon case of "123[Ptr]".
02188     BaseExpr = RHSExp;
02189     IndexExpr = LHSExp;
02190     ResultType = PTy->getPointeeType();
02191   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
02192     BaseExpr = LHSExp;    // vectors: V[123]
02193     IndexExpr = RHSExp;
02194 
02195     // FIXME: need to deal with const...
02196     ResultType = VTy->getElementType();
02197   } else if (LHSTy->isArrayType()) {
02198     // If we see an array that wasn't promoted by
02199     // DefaultFunctionArrayLvalueConversion, it must be an array that
02200     // wasn't promoted because of the C90 rule that doesn't
02201     // allow promoting non-lvalue arrays.  Warn, then
02202     // force the promotion here.
02203     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
02204         LHSExp->getSourceRange();
02205     ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
02206                       CastExpr::CK_ArrayToPointerDecay);
02207     LHSTy = LHSExp->getType();
02208 
02209     BaseExpr = LHSExp;
02210     IndexExpr = RHSExp;
02211     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
02212   } else if (RHSTy->isArrayType()) {
02213     // Same as previous, except for 123[f().a] case
02214     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
02215         RHSExp->getSourceRange();
02216     ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
02217                       CastExpr::CK_ArrayToPointerDecay);
02218     RHSTy = RHSExp->getType();
02219 
02220     BaseExpr = RHSExp;
02221     IndexExpr = LHSExp;
02222     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
02223   } else {
02224     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
02225        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
02226   }
02227   // C99 6.5.2.1p1
02228   if (!(IndexExpr->getType()->isIntegerType() &&
02229         IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
02230     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
02231                      << IndexExpr->getSourceRange());
02232 
02233   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
02234        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
02235          && !IndexExpr->isTypeDependent())
02236     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
02237 
02238   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
02239   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
02240   // type. Note that Functions are not objects, and that (in C99 parlance)
02241   // incomplete types are not object types.
02242   if (ResultType->isFunctionType()) {
02243     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
02244       << ResultType << BaseExpr->getSourceRange();
02245     return ExprError();
02246   }
02247 
02248   if (!ResultType->isDependentType() &&
02249       RequireCompleteType(LLoc, ResultType,
02250                           PDiag(diag::err_subscript_incomplete_type)
02251                             << BaseExpr->getSourceRange()))
02252     return ExprError();
02253 
02254   // Diagnose bad cases where we step over interface counts.
02255   if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
02256     Diag(LLoc, diag::err_subscript_nonfragile_interface)
02257       << ResultType << BaseExpr->getSourceRange();
02258     return ExprError();
02259   }
02260 
02261   Base.release();
02262   Idx.release();
02263   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
02264                                                 ResultType, RLoc));
02265 }
02266 
02267 QualType Sema::
02268 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
02269                         const IdentifierInfo *CompName,
02270                         SourceLocation CompLoc) {
02271   // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
02272   // see FIXME there.
02273   //
02274   // FIXME: This logic can be greatly simplified by splitting it along
02275   // halving/not halving and reworking the component checking.
02276   const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
02277 
02278   // The vector accessor can't exceed the number of elements.
02279   const char *compStr = CompName->getNameStart();
02280 
02281   // This flag determines whether or not the component is one of the four
02282   // special names that indicate a subset of exactly half the elements are
02283   // to be selected.
02284   bool HalvingSwizzle = false;
02285 
02286   // This flag determines whether or not CompName has an 's' char prefix,
02287   // indicating that it is a string of hex values to be used as vector indices.
02288   bool HexSwizzle = *compStr == 's' || *compStr == 'S';
02289 
02290   // Check that we've found one of the special components, or that the component
02291   // names must come from the same set.
02292   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
02293       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
02294     HalvingSwizzle = true;
02295   } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
02296     do
02297       compStr++;
02298     while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
02299   } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
02300     do
02301       compStr++;
02302     while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
02303   }
02304 
02305   if (!HalvingSwizzle && *compStr) {
02306     // We didn't get to the end of the string. This means the component names
02307     // didn't come from the same set *or* we encountered an illegal name.
02308     Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
02309       << std::string(compStr,compStr+1) << SourceRange(CompLoc);
02310     return QualType();
02311   }
02312 
02313   // Ensure no component accessor exceeds the width of the vector type it
02314   // operates on.
02315   if (!HalvingSwizzle) {
02316     compStr = CompName->getNameStart();
02317 
02318     if (HexSwizzle)
02319       compStr++;
02320 
02321     while (*compStr) {
02322       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
02323         Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
02324           << baseType << SourceRange(CompLoc);
02325         return QualType();
02326       }
02327     }
02328   }
02329 
02330   // The component accessor looks fine - now we need to compute the actual type.
02331   // The vector type is implied by the component accessor. For example,
02332   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
02333   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
02334   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
02335   unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
02336                                      : CompName->getLength();
02337   if (HexSwizzle)
02338     CompSize--;
02339 
02340   if (CompSize == 1)
02341     return vecType->getElementType();
02342 
02343   QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
02344   // Now look up the TypeDefDecl from the vector type. Without this,
02345   // diagostics look bad. We want extended vector types to appear built-in.
02346   for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
02347     if (ExtVectorDecls[i]->getUnderlyingType() == VT)
02348       return Context.getTypedefType(ExtVectorDecls[i]);
02349   }
02350   return VT; // should never get here (a typedef type should always be found).
02351 }
02352 
02353 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
02354                                                 IdentifierInfo *Member,
02355                                                 const Selector &Sel,
02356                                                 ASTContext &Context) {
02357 
02358   if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
02359     return PD;
02360   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
02361     return OMD;
02362 
02363   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
02364        E = PDecl->protocol_end(); I != E; ++I) {
02365     if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
02366                                                      Context))
02367       return D;
02368   }
02369   return 0;
02370 }
02371 
02372 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
02373                                 IdentifierInfo *Member,
02374                                 const Selector &Sel,
02375                                 ASTContext &Context) {
02376   // Check protocols on qualified interfaces.
02377   Decl *GDecl = 0;
02378   for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
02379        E = QIdTy->qual_end(); I != E; ++I) {
02380     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
02381       GDecl = PD;
02382       break;
02383     }
02384     // Also must look for a getter name which uses property syntax.
02385     if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
02386       GDecl = OMD;
02387       break;
02388     }
02389   }
02390   if (!GDecl) {
02391     for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
02392          E = QIdTy->qual_end(); I != E; ++I) {
02393       // Search in the protocol-qualifier list of current protocol.
02394       GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
02395       if (GDecl)
02396         return GDecl;
02397     }
02398   }
02399   return GDecl;
02400 }
02401 
02402 Sema::OwningExprResult
02403 Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
02404                                bool IsArrow, SourceLocation OpLoc,
02405                                const CXXScopeSpec &SS,
02406                                NamedDecl *FirstQualifierInScope,
02407                                DeclarationName Name, SourceLocation NameLoc,
02408                                const TemplateArgumentListInfo *TemplateArgs) {
02409   Expr *BaseExpr = Base.takeAs<Expr>();
02410 
02411   // Even in dependent contexts, try to diagnose base expressions with
02412   // obviously wrong types, e.g.:
02413   //
02414   // T* t;
02415   // t.f;
02416   //
02417   // In Obj-C++, however, the above expression is valid, since it could be
02418   // accessing the 'f' property if T is an Obj-C interface. The extra check
02419   // allows this, while still reporting an error if T is a struct pointer.
02420   if (!IsArrow) {
02421     const PointerType *PT = BaseType->getAs<PointerType>();
02422     if (PT && (!getLangOptions().ObjC1 ||
02423                PT->getPointeeType()->isRecordType())) {
02424       assert(BaseExpr && "cannot happen with implicit member accesses");
02425       Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
02426         << BaseType << BaseExpr->getSourceRange();
02427       return ExprError();
02428     }
02429   }
02430 
02431   assert(BaseType->isDependentType() || Name.isDependentName());
02432 
02433   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
02434   // must have pointer type, and the accessed type is the pointee.
02435   return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
02436                                                    IsArrow, OpLoc,
02437                  static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
02438                                                    SS.getRange(),
02439                                                    FirstQualifierInScope,
02440                                                    Name, NameLoc,
02441                                                    TemplateArgs));
02442 }
02443 
02444 /// We know that the given qualified member reference points only to
02445 /// declarations which do not belong to the static type of the base
02446 /// expression.  Diagnose the problem.
02447 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
02448                                              Expr *BaseExpr,
02449                                              QualType BaseType,
02450                                              const CXXScopeSpec &SS,
02451                                              const LookupResult &R) {
02452   // If this is an implicit member access, use a different set of
02453   // diagnostics.
02454   if (!BaseExpr)
02455     return DiagnoseInstanceReference(SemaRef, SS, R);
02456 
02457   // FIXME: this is an exceedingly lame diagnostic for some of the more
02458   // complicated cases here.
02459   DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
02460   SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
02461     << SS.getRange() << DC << BaseType;
02462 }
02463 
02464 // Check whether the declarations we found through a nested-name
02465 // specifier in a member expression are actually members of the base
02466 // type.  The restriction here is:
02467 //
02468 //   C++ [expr.ref]p2:
02469 //     ... In these cases, the id-expression shall name a
02470 //     member of the class or of one of its base classes.
02471 //
02472 // So it's perfectly legitimate for the nested-name specifier to name
02473 // an unrelated class, and for us to find an overload set including
02474 // decls from classes which are not superclasses, as long as the decl
02475 // we actually pick through overload resolution is from a superclass.
02476 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
02477                                          QualType BaseType,
02478                                          const CXXScopeSpec &SS,
02479                                          const LookupResult &R) {
02480   const RecordType *BaseRT = BaseType->getAs<RecordType>();
02481   if (!BaseRT) {
02482     // We can't check this yet because the base type is still
02483     // dependent.
02484     assert(BaseType->isDependentType());
02485     return false;
02486   }
02487   CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
02488 
02489   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
02490     // If this is an implicit member reference and we find a
02491     // non-instance member, it's not an error.
02492     if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
02493       return false;
02494 
02495     // Note that we use the DC of the decl, not the underlying decl.
02496     CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
02497     while (RecordD->isAnonymousStructOrUnion())
02498       RecordD = cast<CXXRecordDecl>(RecordD->getParent());
02499 
02500     llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
02501     MemberRecord.insert(RecordD->getCanonicalDecl());
02502 
02503     if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
02504       return false;
02505   }
02506 
02507   DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
02508   return true;
02509 }
02510 
02511 static bool
02512 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
02513                          SourceRange BaseRange, const RecordType *RTy,
02514                          SourceLocation OpLoc, const CXXScopeSpec &SS) {
02515   RecordDecl *RDecl = RTy->getDecl();
02516   if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
02517                                   PDiag(diag::err_typecheck_incomplete_tag)
02518                                     << BaseRange))
02519     return true;
02520 
02521   DeclContext *DC = RDecl;
02522   if (SS.isSet()) {
02523     // If the member name was a qualified-id, look into the
02524     // nested-name-specifier.
02525     DC = SemaRef.computeDeclContext(SS, false);
02526 
02527     if (SemaRef.RequireCompleteDeclContext(SS)) {
02528       SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
02529         << SS.getRange() << DC;
02530       return true;
02531     }
02532 
02533     assert(DC && "Cannot handle non-computable dependent contexts in lookup");
02534 
02535     if (!isa<TypeDecl>(DC)) {
02536       SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
02537         << DC << SS.getRange();
02538       return true;
02539     }
02540   }
02541 
02542   // The record definition is complete, now look up the member.
02543   SemaRef.LookupQualifiedName(R, DC);
02544 
02545   if (!R.empty())
02546     return false;
02547 
02548   // We didn't find anything with the given name, so try to correct
02549   // for typos.
02550   DeclarationName Name = R.getLookupName();
02551   if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
02552       (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
02553     SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
02554       << Name << DC << R.getLookupName() << SS.getRange()
02555       << CodeModificationHint::CreateReplacement(R.getNameLoc(),
02556                                          R.getLookupName().getAsString());
02557     if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
02558       SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
02559         << ND->getDeclName();
02560     return false;
02561   } else {
02562     R.clear();
02563   }
02564 
02565   return false;
02566 }
02567 
02568 Sema::OwningExprResult
02569 Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
02570                                SourceLocation OpLoc, bool IsArrow,
02571                                const CXXScopeSpec &SS,
02572                                NamedDecl *FirstQualifierInScope,
02573                                DeclarationName Name, SourceLocation NameLoc,
02574                                const TemplateArgumentListInfo *TemplateArgs) {
02575   Expr *Base = BaseArg.takeAs<Expr>();
02576 
02577   if (BaseType->isDependentType() ||
02578       (SS.isSet() && isDependentScopeSpecifier(SS)))
02579     return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
02580                                     IsArrow, OpLoc,
02581                                     SS, FirstQualifierInScope,
02582                                     Name, NameLoc,
02583                                     TemplateArgs);
02584 
02585   LookupResult R(*this, Name, NameLoc, LookupMemberName);
02586 
02587   // Implicit member accesses.
02588   if (!Base) {
02589     QualType RecordTy = BaseType;
02590     if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
02591     if (LookupMemberExprInRecord(*this, R, SourceRange(),
02592                                  RecordTy->getAs<RecordType>(),
02593                                  OpLoc, SS))
02594       return ExprError();
02595 
02596   // Explicit member accesses.
02597   } else {
02598     OwningExprResult Result =
02599       LookupMemberExpr(R, Base, IsArrow, OpLoc,
02600                        SS, /*ObjCImpDecl*/ DeclPtrTy());
02601 
02602     if (Result.isInvalid()) {
02603       Owned(Base);
02604       return ExprError();
02605     }
02606 
02607     if (Result.get())
02608       return move(Result);
02609   }
02610 
02611   return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
02612                                   OpLoc, IsArrow, SS, FirstQualifierInScope,
02613                                   R, TemplateArgs);
02614 }
02615 
02616 Sema::OwningExprResult
02617 Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
02618                                SourceLocation OpLoc, bool IsArrow,
02619                                const CXXScopeSpec &SS,
02620                                NamedDecl *FirstQualifierInScope,
02621                                LookupResult &R,
02622                          const TemplateArgumentListInfo *TemplateArgs) {
02623   Expr *BaseExpr = Base.takeAs<Expr>();
02624   QualType BaseType = BaseExprType;
02625   if (IsArrow) {
02626     assert(BaseType->isPointerType());
02627     BaseType = BaseType->getAs<PointerType>()->getPointeeType();
02628   }
02629 
02630   NestedNameSpecifier *Qualifier =
02631     static_cast<NestedNameSpecifier*>(SS.getScopeRep());
02632   DeclarationName MemberName = R.getLookupName();
02633   SourceLocation MemberLoc = R.getNameLoc();
02634 
02635   if (R.isAmbiguous())
02636     return ExprError();
02637 
02638   if (R.empty()) {
02639     // Rederive where we looked up.
02640     DeclContext *DC = (SS.isSet()
02641                        ? computeDeclContext(SS, false)
02642                        : BaseType->getAs<RecordType>()->getDecl());
02643 
02644     Diag(R.getNameLoc(), diag::err_no_member)
02645       << MemberName << DC
02646       << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
02647     return ExprError();
02648   }
02649 
02650   // Diagnose lookups that find only declarations from a non-base
02651   // type.  This is possible for either qualified lookups (which may
02652   // have been qualified with an unrelated type) or implicit member
02653   // expressions (which were found with unqualified lookup and thus
02654   // may have come from an enclosing scope).  Note that it's okay for
02655   // lookup to find declarations from a non-base type as long as those
02656   // aren't the ones picked by overload resolution.
02657   if ((SS.isSet() || !BaseExpr ||
02658        (isa<CXXThisExpr>(BaseExpr) &&
02659         cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
02660       CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
02661     return ExprError();
02662 
02663   // Construct an unresolved result if we in fact got an unresolved
02664   // result.
02665   if (R.isOverloadedResult() || R.isUnresolvableResult()) {
02666     bool Dependent =
02667       BaseExprType->isDependentType() ||
02668       R.isUnresolvableResult() ||
02669       OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
02670 
02671     // Suppress any lookup-related diagnostics; we'll do these when we
02672     // pick a member.
02673     R.suppressDiagnostics();
02674 
02675     UnresolvedMemberExpr *MemExpr
02676       = UnresolvedMemberExpr::Create(Context, Dependent,
02677                                      R.isUnresolvableResult(),
02678                                      BaseExpr, BaseExprType,
02679                                      IsArrow, OpLoc,
02680                                      Qualifier, SS.getRange(),
02681                                      MemberName, MemberLoc,
02682                                      TemplateArgs);
02683     MemExpr->addDecls(R.begin(), R.end());
02684 
02685     return Owned(MemExpr);
02686   }
02687 
02688   assert(R.isSingleResult());
02689   NamedDecl *MemberDecl = R.getFoundDecl();
02690 
02691   // FIXME: diagnose the presence of template arguments now.
02692 
02693   // If the decl being referenced had an error, return an error for this
02694   // sub-expr without emitting another error, in order to avoid cascading
02695   // error cases.
02696   if (MemberDecl->isInvalidDecl())
02697     return ExprError();
02698 
02699   // Handle the implicit-member-access case.
02700   if (!BaseExpr) {
02701     // If this is not an instance member, convert to a non-member access.
02702     if (!IsInstanceMember(MemberDecl))
02703       return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
02704 
02705     SourceLocation Loc = R.getNameLoc();
02706     if (SS.getRange().isValid())
02707       Loc = SS.getRange().getBegin();
02708     BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
02709   }
02710 
02711   bool ShouldCheckUse = true;
02712   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
02713     // Don't diagnose the use of a virtual member function unless it's
02714     // explicitly qualified.
02715     if (MD->isVirtual() && !SS.isSet())
02716       ShouldCheckUse = false;
02717   }
02718 
02719   // Check the use of this member.
02720   if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
02721     Owned(BaseExpr);
02722     return ExprError();
02723   }
02724 
02725   if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
02726     // We may have found a field within an anonymous union or struct
02727     // (C++ [class.union]).
02728     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
02729         !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
02730       return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
02731                                                       BaseExpr, OpLoc);
02732 
02733     // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
02734     QualType MemberType = FD->getType();
02735     if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
02736       MemberType = Ref->getPointeeType();
02737     else {
02738       Qualifiers BaseQuals = BaseType.getQualifiers();
02739       BaseQuals.removeObjCGCAttr();
02740       if (FD->isMutable()) BaseQuals.removeConst();
02741 
02742       Qualifiers MemberQuals
02743         = Context.getCanonicalType(MemberType).getQualifiers();
02744 
02745       Qualifiers Combined = BaseQuals + MemberQuals;
02746       if (Combined != MemberQuals)
02747         MemberType = Context.getQualifiedType(MemberType, Combined);
02748     }
02749 
02750     MarkDeclarationReferenced(MemberLoc, FD);
02751     if (PerformObjectMemberConversion(BaseExpr, Qualifier, FD))
02752       return ExprError();
02753     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02754                                  FD, MemberLoc, MemberType));
02755   }
02756 
02757   if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
02758     MarkDeclarationReferenced(MemberLoc, Var);
02759     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02760                                  Var, MemberLoc,
02761                                  Var->getType().getNonReferenceType()));
02762   }
02763 
02764   if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
02765     MarkDeclarationReferenced(MemberLoc, MemberDecl);
02766     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02767                                  MemberFn, MemberLoc,
02768                                  MemberFn->getType()));
02769   }
02770 
02771   if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
02772     MarkDeclarationReferenced(MemberLoc, MemberDecl);
02773     return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
02774                                  Enum, MemberLoc, Enum->getType()));
02775   }
02776 
02777   Owned(BaseExpr);
02778 
02779   if (isa<TypeDecl>(MemberDecl))
02780     return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
02781                      << MemberName << int(IsArrow));
02782 
02783   // We found a declaration kind that we didn't expect. This is a
02784   // generic error message that tells the user that she can't refer
02785   // to this member with '.' or '->'.
02786   return ExprError(Diag(MemberLoc,
02787                         diag::err_typecheck_member_reference_unknown)
02788       << MemberName << int(IsArrow));
02789 }
02790 
02791 /// Look up the given member of the given non-type-dependent
02792 /// expression.  This can return in one of two ways:
02793 ///  * If it returns a sentinel null-but-valid result, the caller will
02794 ///    assume that lookup was performed and the results written into
02795 ///    the provided structure.  It will take over from there.
02796 ///  * Otherwise, the returned expression will be produced in place of
02797 ///    an ordinary member expression.
02798 ///
02799 /// The ObjCImpDecl bit is a gross hack that will need to be properly
02800 /// fixed for ObjC++.
02801 Sema::OwningExprResult
02802 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
02803                        bool &IsArrow, SourceLocation OpLoc,
02804                        const CXXScopeSpec &SS,
02805                        DeclPtrTy ObjCImpDecl) {
02806   assert(BaseExpr && "no base expression");
02807 
02808   // Perform default conversions.
02809   DefaultFunctionArrayConversion(BaseExpr);
02810 
02811   QualType BaseType = BaseExpr->getType();
02812   assert(!BaseType->isDependentType());
02813 
02814   DeclarationName MemberName = R.getLookupName();
02815   SourceLocation MemberLoc = R.getNameLoc();
02816 
02817   // If the user is trying to apply -> or . to a function pointer
02818   // type, it's probably because they forgot parentheses to call that
02819   // function. Suggest the addition of those parentheses, build the
02820   // call, and continue on.
02821   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
02822     if (const FunctionProtoType *Fun
02823           = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
02824       QualType ResultTy = Fun->getResultType();
02825       if (Fun->getNumArgs() == 0 &&
02826           ((!IsArrow && ResultTy->isRecordType()) ||
02827            (IsArrow && ResultTy->isPointerType() &&
02828             ResultTy->getAs<PointerType>()->getPointeeType()
02829                                                           ->isRecordType()))) {
02830         SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
02831         Diag(Loc, diag::err_member_reference_needs_call)
02832           << QualType(Fun, 0)
02833           << CodeModificationHint::CreateInsertion(Loc, "()");
02834 
02835         OwningExprResult NewBase
02836           = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
02837                           MultiExprArg(*this, 0, 0), 0, Loc);
02838         if (NewBase.isInvalid())
02839           return ExprError();
02840 
02841         BaseExpr = NewBase.takeAs<Expr>();
02842         DefaultFunctionArrayConversion(BaseExpr);
02843         BaseType = BaseExpr->getType();
02844       }
02845     }
02846   }
02847 
02848   // If this is an Objective-C pseudo-builtin and a definition is provided then
02849   // use that.
02850   if (BaseType->isObjCIdType()) {
02851     if (IsArrow) {
02852       // Handle the following exceptional case PObj->isa.
02853       if (const ObjCObjectPointerType *OPT =
02854           BaseType->getAs<ObjCObjectPointerType>()) {
02855         if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
02856             MemberName.getAsIdentifierInfo()->isStr("isa"))
02857           return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
02858                                                  Context.getObjCClassType()));
02859       }
02860     }
02861     // We have an 'id' type. Rather than fall through, we check if this
02862     // is a reference to 'isa'.
02863     if (BaseType != Context.ObjCIdRedefinitionType) {
02864       BaseType = Context.ObjCIdRedefinitionType;
02865       ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
02866     }
02867   }
02868 
02869   // If this is an Objective-C pseudo-builtin and a definition is provided then
02870   // use that.
02871   if (Context.isObjCSelType(BaseType)) {
02872     // We have an 'SEL' type. Rather than fall through, we check if this
02873     // is a reference to 'sel_id'.
02874     if (BaseType != Context.ObjCSelRedefinitionType) {
02875       BaseType = Context.ObjCSelRedefinitionType;
02876       ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
02877     }
02878   }
02879 
02880   assert(!BaseType.isNull() && "no type for member expression");
02881 
02882   // Handle properties on ObjC 'Class' types.
02883   if (!IsArrow && BaseType->isObjCClassType()) {
02884     // Also must look for a getter name which uses property syntax.
02885     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
02886     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
02887     if (ObjCMethodDecl *MD = getCurMethodDecl()) {
02888       ObjCInterfaceDecl *IFace = MD->getClassInterface();
02889       ObjCMethodDecl *Getter;
02890       // FIXME: need to also look locally in the implementation.
02891       if ((Getter = IFace->lookupClassMethod(Sel))) {
02892         // Check the use of this method.
02893         if (DiagnoseUseOfDecl(Getter, MemberLoc))
02894           return ExprError();
02895       }
02896       // If we found a getter then this may be a valid dot-reference, we
02897       // will look for the matching setter, in case it is needed.
02898       Selector SetterSel =
02899       SelectorTable::constructSetterName(PP.getIdentifierTable(),
02900                                          PP.getSelectorTable(), Member);
02901       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
02902       if (!Setter) {
02903         // If this reference is in an @implementation, also check for 'private'
02904         // methods.
02905         Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
02906       }
02907       // Look through local category implementations associated with the class.
02908       if (!Setter)
02909         Setter = IFace->getCategoryClassMethod(SetterSel);
02910 
02911       if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
02912         return ExprError();
02913 
02914       if (Getter || Setter) {
02915         QualType PType;
02916 
02917         if (Getter)
02918           PType = Getter->getResultType();
02919         else
02920           // Get the expression type from Setter's incoming parameter.
02921           PType = (*(Setter->param_end() -1))->getType();
02922         // FIXME: we must check that the setter has property type.
02923         return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
02924                                                   PType,
02925                                                   Setter, MemberLoc, BaseExpr));
02926       }
02927       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
02928                        << MemberName << BaseType);
02929     }
02930   }
02931 
02932   if (BaseType->isObjCClassType() &&
02933       BaseType != Context.ObjCClassRedefinitionType) {
02934     BaseType = Context.ObjCClassRedefinitionType;
02935     ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
02936   }
02937 
02938   if (IsArrow) {
02939     if (const PointerType *PT = BaseType->getAs<PointerType>())
02940       BaseType = PT->getPointeeType();
02941     else if (BaseType->isObjCObjectPointerType())
02942       ;
02943     else if (BaseType->isRecordType()) {
02944       // Recover from arrow accesses to records, e.g.:
02945       //   struct MyRecord foo;
02946       //   foo->bar
02947       // This is actually well-formed in C++ if MyRecord has an
02948       // overloaded operator->, but that should have been dealt with
02949       // by now.
02950       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02951         << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
02952         << CodeModificationHint::CreateReplacement(OpLoc, ".");
02953       IsArrow = false;
02954     } else {
02955       Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
02956         << BaseType << BaseExpr->getSourceRange();
02957       return ExprError();
02958     }
02959   } else {
02960     // Recover from dot accesses to pointers, e.g.:
02961     //   type *foo;
02962     //   foo.bar
02963     // This is actually well-formed in two cases:
02964     //   - 'type' is an Objective C type
02965     //   - 'bar' is a pseudo-destructor name which happens to refer to
02966     //     the appropriate pointer type
02967     if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
02968       const PointerType *PT = BaseType->getAs<PointerType>();
02969       if (PT && PT->getPointeeType()->isRecordType()) {
02970         Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02971           << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
02972           << CodeModificationHint::CreateReplacement(OpLoc, "->");
02973         BaseType = PT->getPointeeType();
02974         IsArrow = true;
02975       }
02976     }
02977   }
02978 
02979   // Handle field access to simple records.  This also handles access
02980   // to fields of the ObjC 'id' struct.
02981   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
02982     if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
02983                                  RTy, OpLoc, SS))
02984       return ExprError();
02985     return Owned((Expr*) 0);
02986   }
02987 
02988   // Handle access to Objective-C instance variables, such as "Obj->ivar" and
02989   // (*Obj).ivar.
02990   if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
02991       (!IsArrow && BaseType->isObjCInterfaceType())) {
02992     const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
02993     const ObjCInterfaceType *IFaceT =
02994       OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
02995     if (IFaceT) {
02996       IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
02997 
02998       ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
02999       ObjCInterfaceDecl *ClassDeclared;
03000       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
03001 
03002       if (!IV) {
03003         // Attempt to correct for typos in ivar names.
03004         LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
03005                          LookupMemberName);
03006         if (CorrectTypo(Res, 0, 0, IDecl) &&
03007             (IV = Res.getAsSingle<ObjCIvarDecl>())) {
03008           Diag(R.getNameLoc(),
03009                diag::err_typecheck_member_reference_ivar_suggest)
03010             << IDecl->getDeclName() << MemberName << IV->getDeclName()
03011             << CodeModificationHint::CreateReplacement(R.getNameLoc(),
03012                                                        IV->getNameAsString());
03013           Diag(IV->getLocation(), diag::note_previous_decl)
03014             << IV->getDeclName();
03015         }
03016       }
03017 
03018       if (IV) {
03019         // If the decl being referenced had an error, return an error for this
03020         // sub-expr without emitting another error, in order to avoid cascading
03021         // error cases.
03022         if (IV->isInvalidDecl())
03023           return ExprError();
03024 
03025         // Check whether we can reference this field.
03026         if (DiagnoseUseOfDecl(IV, MemberLoc))
03027           return ExprError();
03028         if (IV->getAccessControl() != ObjCIvarDecl::Public &&
03029             IV->getAccessControl() != ObjCIvarDecl::Package) {
03030           ObjCInterfaceDecl *ClassOfMethodDecl = 0;
03031           if (ObjCMethodDecl *MD = getCurMethodDecl())
03032             ClassOfMethodDecl =  MD->getClassInterface();
03033           else if (ObjCImpDecl && getCurFunctionDecl()) {
03034             // Case of a c-function declared inside an objc implementation.
03035             // FIXME: For a c-style function nested inside an objc implementation
03036             // class, there is no implementation context available, so we pass
03037             // down the context as argument to this routine. Ideally, this context
03038             // need be passed down in the AST node and somehow calculated from the
03039             // AST for a function decl.
03040             Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
03041             if (ObjCImplementationDecl *IMPD =
03042                 dyn_cast<ObjCImplementationDecl>(ImplDecl))
03043               ClassOfMethodDecl = IMPD->getClassInterface();
03044             else if (ObjCCategoryImplDecl* CatImplClass =
03045                         dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
03046               ClassOfMethodDecl = CatImplClass->getClassInterface();
03047           }
03048 
03049           if (IV->getAccessControl() == ObjCIvarDecl::Private) {
03050             if (ClassDeclared != IDecl ||
03051                 ClassOfMethodDecl != ClassDeclared)
03052               Diag(MemberLoc, diag::error_private_ivar_access)
03053                 << IV->getDeclName();
03054           } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
03055             // @protected
03056             Diag(MemberLoc, diag::error_protected_ivar_access)
03057               << IV->getDeclName();
03058         }
03059 
03060         return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
03061                                                    MemberLoc, BaseExpr,
03062                                                    IsArrow));
03063       }
03064       return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
03065                          << IDecl->getDeclName() << MemberName
03066                          << BaseExpr->getSourceRange());
03067     }
03068   }
03069   // Handle properties on 'id' and qualified "id".
03070   if (!IsArrow && (BaseType->isObjCIdType() ||
03071                    BaseType->isObjCQualifiedIdType())) {
03072     const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
03073     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03074 
03075     // Check protocols on qualified interfaces.
03076     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
03077     if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
03078       if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
03079         // Check the use of this declaration
03080         if (DiagnoseUseOfDecl(PD, MemberLoc))
03081           return ExprError();
03082 
03083         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
03084                                                        MemberLoc, BaseExpr));
03085       }
03086       if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
03087         // Check the use of this method.
03088         if (DiagnoseUseOfDecl(OMD, MemberLoc))
03089           return ExprError();
03090 
03091         return Owned(new (Context) ObjCMessageExpr(Context, BaseExpr, Sel,
03092                                                    OMD->getResultType(),
03093                                                    OMD, OpLoc, MemberLoc,
03094                                                    NULL, 0));
03095       }
03096     }
03097 
03098     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
03099                        << MemberName << BaseType);
03100   }
03101   // Handle Objective-C property access, which is "Obj.property" where Obj is a
03102   // pointer to a (potentially qualified) interface type.
03103   const ObjCObjectPointerType *OPT;
03104   if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
03105     const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
03106     ObjCInterfaceDecl *IFace = IFaceT->getDecl();
03107     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03108 
03109     // Search for a declared property first.
03110     if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
03111       // Check whether we can reference this property.
03112       if (DiagnoseUseOfDecl(PD, MemberLoc))
03113         return ExprError();
03114       QualType ResTy = PD->getType();
03115       Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
03116       ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
03117       if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
03118         ResTy = Getter->getResultType();
03119       return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
03120                                                      MemberLoc, BaseExpr));
03121     }
03122     // Check protocols on qualified interfaces.
03123     for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
03124          E = OPT->qual_end(); I != E; ++I)
03125       if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
03126         // Check whether we can reference this property.
03127         if (DiagnoseUseOfDecl(PD, MemberLoc))
03128           return ExprError();
03129 
03130         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
03131                                                        MemberLoc, BaseExpr));
03132       }
03133     // If that failed, look for an "implicit" property by seeing if the nullary
03134     // selector is implemented.
03135 
03136     // FIXME: The logic for looking up nullary and unary selectors should be
03137     // shared with the code in ActOnInstanceMessage.
03138 
03139     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
03140     ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
03141 
03142     // If this reference is in an @implementation, check for 'private' methods.
03143     if (!Getter)
03144       Getter = IFace->lookupPrivateInstanceMethod(Sel);
03145 
03146     // Look through local category implementations associated with the class.
03147     if (!Getter)
03148       Getter = IFace->getCategoryInstanceMethod(Sel);
03149     if (Getter) {
03150       // Check if we can reference this property.
03151       if (DiagnoseUseOfDecl(Getter, MemberLoc))
03152         return ExprError();
03153     }
03154     // If we found a getter then this may be a valid dot-reference, we
03155     // will look for the matching setter, in case it is needed.
03156     Selector SetterSel =
03157       SelectorTable::constructSetterName(PP.getIdentifierTable(),
03158                                          PP.getSelectorTable(), Member);
03159     ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
03160     if (!Setter) {
03161       // If this reference is in an @implementation, also check for 'private'
03162       // methods.
03163       Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
03164     }
03165     // Look through local category implementations associated with the class.
03166     if (!Setter)
03167       Setter = IFace->getCategoryInstanceMethod(SetterSel);
03168 
03169     if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
03170       return ExprError();
03171 
03172     if (Getter) {
03173       QualType PType;
03174       PType = Getter->getResultType();
03175       return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
03176                                       Setter, MemberLoc, BaseExpr));
03177     }
03178 
03179     // Attempt to correct for typos in property names.
03180     LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
03181                      LookupOrdinaryName);
03182     if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
03183         Res.getAsSingle<ObjCPropertyDecl>()) {
03184       Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
03185         << MemberName << BaseType << Res.getLookupName()
03186         << CodeModificationHint::CreateReplacement(R.getNameLoc(),
03187                                            Res.getLookupName().getAsString());
03188       ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
03189       Diag(Property->getLocation(), diag::note_previous_decl)
03190         << Property->getDeclName();
03191 
03192       return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
03193                               ObjCImpDecl);
03194     }
03195     Diag(MemberLoc, diag::err_property_not_found)
03196       << MemberName << BaseType;
03197     if (Setter && !Getter)
03198       Diag(Setter->getLocation(), diag::note_getter_unavailable)
03199         << MemberName << BaseExpr->getSourceRange();
03200     return ExprError();
03201   }
03202 
03203   // Handle the following exceptional case (*Obj).isa.
03204   if (!IsArrow &&
03205       BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
03206       MemberName.getAsIdentifierInfo()->isStr("isa"))
03207     return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
03208                                            Context.getObjCClassType()));
03209 
03210   // Handle 'field access' to vectors, such as 'V.xx'.
03211   if (BaseType->isExtVectorType()) {
03212     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
03213     QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
03214     if (ret.isNull())
03215       return ExprError();
03216     return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
03217                                                     MemberLoc));
03218   }
03219 
03220   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
03221     << BaseType << BaseExpr->getSourceRange();
03222 
03223   return ExprError();
03224 }
03225 
03226 /// The main callback when the parser finds something like
03227 ///   expression . [nested-name-specifier] identifier
03228 ///   expression -> [nested-name-specifier] identifier
03229 /// where 'identifier' encompasses a fairly broad spectrum of
03230 /// possibilities, including destructor and operator references.
03231 ///
03232 /// \param OpKind either tok::arrow or tok::period
03233 /// \param HasTrailingLParen whether the next token is '(', which
03234 ///   is used to diagnose mis-uses of special members that can
03235 ///   only be called
03236 /// \param ObjCImpDecl the current ObjC @implementation decl;
03237 ///   this is an ugly hack around the fact that ObjC @implementations
03238 ///   aren't properly put in the context chain
03239 Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
03240                                                    SourceLocation OpLoc,
03241                                                    tok::TokenKind OpKind,
03242                                                    const CXXScopeSpec &SS,
03243                                                    UnqualifiedId &Id,
03244                                                    DeclPtrTy ObjCImpDecl,
03245                                                    bool HasTrailingLParen) {
03246   if (SS.isSet() && SS.isInvalid())
03247     return ExprError();
03248 
03249   TemplateArgumentListInfo TemplateArgsBuffer;
03250 
03251   // Decompose the name into its component parts.
03252   DeclarationName Name;
03253   SourceLocation NameLoc;
03254   const TemplateArgumentListInfo *TemplateArgs;
03255   DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
03256                          Name, NameLoc, TemplateArgs);
03257 
03258   bool IsArrow = (OpKind == tok::arrow);
03259 
03260   NamedDecl *FirstQualifierInScope
03261     = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
03262                        static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
03263 
03264   // This is a postfix expression, so get rid of ParenListExprs.
03265   BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
03266 
03267   Expr *Base = BaseArg.takeAs<Expr>();
03268   OwningExprResult Result(*this);
03269   if (Base->getType()->isDependentType() || Name.isDependentName()) {
03270     Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
03271                                       IsArrow, OpLoc,
03272                                       SS, FirstQualifierInScope,
03273                                       Name, NameLoc,
03274                                       TemplateArgs);
03275   } else {
03276     LookupResult R(*this, Name, NameLoc, LookupMemberName);
03277     if (TemplateArgs) {
03278       // Re-use the lookup done for the template name.
03279       DecomposeTemplateName(R, Id);
03280     } else {
03281       Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
03282                                 SS, ObjCImpDecl);
03283 
03284       if (Result.isInvalid()) {
03285         Owned(Base);
03286         return ExprError();
03287       }
03288 
03289       if (Result.get()) {
03290         // The only way a reference to a destructor can be used is to
03291         // immediately call it, which falls into this case.  If the
03292         // next token is not a '(', produce a diagnostic and build the
03293         // call now.
03294         if (!HasTrailingLParen &&
03295             Id.getKind() == UnqualifiedId::IK_DestructorName)
03296           return DiagnoseDtorReference(NameLoc, move(Result));
03297 
03298         return move(Result);
03299       }
03300     }
03301 
03302     Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
03303                                       OpLoc, IsArrow, SS, FirstQualifierInScope,
03304                                       R, TemplateArgs);
03305   }
03306 
03307   return move(Result);
03308 }
03309 
03310 Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
03311                                                     FunctionDecl *FD,
03312                                                     ParmVarDecl *Param) {
03313   if (Param->hasUnparsedDefaultArg()) {
03314     Diag (CallLoc,
03315           diag::err_use_of_default_argument_to_function_declared_later) <<
03316       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
03317     Diag(UnparsedDefaultArgLocs[Param],
03318           diag::note_default_argument_declared_here);
03319   } else {
03320     if (Param->hasUninstantiatedDefaultArg()) {
03321       Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
03322 
03323       // Instantiate the expression.
03324       MultiLevelTemplateArgumentList ArgList
03325         = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
03326 
03327       InstantiatingTemplate Inst(*this, CallLoc, Param,
03328                                  ArgList.getInnermost().getFlatArgumentList(),
03329                                  ArgList.getInnermost().flat_size());
03330 
03331       OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
03332       if (Result.isInvalid())
03333         return ExprError();
03334 
03335       // Check the expression as an initializer for the parameter.
03336       InitializedEntity Entity
03337         = InitializedEntity::InitializeParameter(Param);
03338       InitializationKind Kind
03339         = InitializationKind::CreateCopy(Param->getLocation(),
03340                /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
03341       Expr *ResultE = Result.takeAs<Expr>();
03342 
03343       InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
03344       Result = InitSeq.Perform(*this, Entity, Kind,
03345                                MultiExprArg(*this, (void**)&ResultE, 1));
03346       if (Result.isInvalid())
03347         return ExprError();
03348 
03349       // Build the default argument expression.
03350       return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
03351                                              Result.takeAs<Expr>()));
03352     }
03353 
03354     // If the default expression creates temporaries, we need to
03355     // push them to the current stack of expression temporaries so they'll
03356     // be properly destroyed.
03357     // FIXME: We should really be rebuilding the default argument with new
03358     // bound temporaries; see the comment in PR5810.
03359     for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
03360       ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
03361   }
03362 
03363   // We already type-checked the argument, so we know it works.
03364   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
03365 }
03366 
03367 /// ConvertArgumentsForCall - Converts the arguments specified in
03368 /// Args/NumArgs to the parameter types of the function FDecl with
03369 /// function prototype Proto. Call is the call expression itself, and
03370 /// Fn is the function expression. For a C++ member function, this
03371 /// routine does not attempt to convert the object argument. Returns
03372 /// true if the call is ill-formed.
03373 bool
03374 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
03375                               FunctionDecl *FDecl,
03376                               const FunctionProtoType *Proto,
03377                               Expr **Args, unsigned NumArgs,
03378                               SourceLocation RParenLoc) {
03379   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
03380   // assignment, to the types of the corresponding parameter, ...
03381   unsigned NumArgsInProto = Proto->getNumArgs();
03382   bool Invalid = false;
03383 
03384   // If too few arguments are available (and we don't have default
03385   // arguments for the remaining parameters), don't make the call.
03386   if (NumArgs < NumArgsInProto) {
03387     if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
03388       return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
03389         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
03390     Call->setNumArgs(Context, NumArgsInProto);
03391   }
03392 
03393   // If too many are passed and not variadic, error on the extras and drop
03394   // them.
03395   if (NumArgs > NumArgsInProto) {
03396     if (!Proto->isVariadic()) {
03397       Diag(Args[NumArgsInProto]->getLocStart(),
03398            diag::err_typecheck_call_too_many_args)
03399         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
03400         << SourceRange(Args[NumArgsInProto]->getLocStart(),
03401                        Args[NumArgs-1]->getLocEnd());
03402       // This deletes the extra arguments.
03403       Call->setNumArgs(Context, NumArgsInProto);
03404       return true;
03405     }
03406   }
03407   llvm::SmallVector<Expr *, 8> AllArgs;
03408   VariadicCallType CallType =
03409     Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
03410   if (Fn->getType()->isBlockPointerType())
03411     CallType = VariadicBlock; // Block
03412   else if (isa<MemberExpr>(Fn))
03413     CallType = VariadicMethod;
03414   Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
03415                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
03416   if (Invalid)
03417     return true;
03418   unsigned TotalNumArgs = AllArgs.size();
03419   for (unsigned i = 0; i < TotalNumArgs; ++i)
03420     Call->setArg(i, AllArgs[i]);
03421 
03422   return false;
03423 }
03424 
03425 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
03426                                   FunctionDecl *FDecl,
03427                                   const FunctionProtoType *Proto,
03428                                   unsigned FirstProtoArg,
03429                                   Expr **Args, unsigned NumArgs,
03430                                   llvm::SmallVector<Expr *, 8> &AllArgs,
03431                                   VariadicCallType CallType) {
03432   unsigned NumArgsInProto = Proto->getNumArgs();
03433   unsigned NumArgsToCheck = NumArgs;
03434   bool Invalid = false;
03435   if (NumArgs != NumArgsInProto)
03436     // Use default arguments for missing arguments
03437     NumArgsToCheck = NumArgsInProto;
03438   unsigned ArgIx = 0;
03439   // Continue to check argument types (even if we have too few/many args).
03440   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
03441     QualType ProtoArgType = Proto->getArgType(i);
03442 
03443     Expr *Arg;
03444     if (ArgIx < NumArgs) {
03445       Arg = Args[ArgIx++];
03446 
03447       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
03448                               ProtoArgType,
03449                               PDiag(diag::err_call_incomplete_argument)
03450                               << Arg->getSourceRange()))
03451         return true;
03452 
03453       // Pass the argument
03454       ParmVarDecl *Param = 0;
03455       if (FDecl && i < FDecl->getNumParams())
03456         Param = FDecl->getParamDecl(i);
03457 
03458 
03459       InitializedEntity Entity =
03460         Param? InitializedEntity::InitializeParameter(Param)
03461              : InitializedEntity::InitializeParameter(ProtoArgType);
03462       OwningExprResult ArgE = PerformCopyInitialization(Entity,
03463                                                         SourceLocation(),
03464                                                         Owned(Arg));
03465       if (ArgE.isInvalid())
03466         return true;
03467 
03468       Arg = ArgE.takeAs<Expr>();
03469     } else {
03470       ParmVarDecl *Param = FDecl->getParamDecl(i);
03471 
03472       OwningExprResult ArgExpr =
03473         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
03474       if (ArgExpr.isInvalid())
03475         return true;
03476 
03477       Arg = ArgExpr.takeAs<Expr>();
03478     }
03479     AllArgs.push_back(Arg);
03480   }
03481 
03482   // If this is a variadic call, handle args passed through "...".
03483   if (CallType != VariadicDoesNotApply) {
03484     // Promote the arguments (C99 6.5.2.2p7).
03485     for (unsigned i = ArgIx; i < NumArgs; i++) {
03486       Expr *Arg = Args[i];
03487       Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
03488       AllArgs.push_back(Arg);
03489     }
03490   }
03491   return Invalid;
03492 }
03493 
03494 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
03495 /// This provides the location of the left/right parens and a list of comma
03496 /// locations.
03497 Action::OwningExprResult
03498 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
03499                     MultiExprArg args,
03500                     SourceLocation *CommaLocs, SourceLocation RParenLoc) {
03501   unsigned NumArgs = args.size();
03502 
03503   // Since this might be a postfix expression, get rid of ParenListExprs.
03504   fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
03505 
03506   Expr *Fn = fn.takeAs<Expr>();
03507   Expr **Args = reinterpret_cast<Expr**>(args.release());
03508   assert(Fn && "no function call expression");
03509 
03510   if (getLangOptions().CPlusPlus) {
03511     // If this is a pseudo-destructor expression, build the call immediately.
03512     if (isa<CXXPseudoDestructorExpr>(Fn)) {
03513       if (NumArgs > 0) {
03514         // Pseudo-destructor calls should not have any arguments.
03515         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
03516           << CodeModificationHint::CreateRemoval(
03517                                     SourceRange(Args[0]->getLocStart(),
03518                                                 Args[NumArgs-1]->getLocEnd()));
03519 
03520         for (unsigned I = 0; I != NumArgs; ++I)
03521           Args[I]->Destroy(Context);
03522 
03523         NumArgs = 0;
03524       }
03525 
03526       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
03527                                           RParenLoc));
03528     }
03529 
03530     // Determine whether this is a dependent call inside a C++ template,
03531     // in which case we won't do any semantic analysis now.
03532     // FIXME: Will need to cache the results of name lookup (including ADL) in
03533     // Fn.
03534     bool Dependent = false;
03535     if (Fn->isTypeDependent())
03536       Dependent = true;
03537     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
03538       Dependent = true;
03539 
03540     if (Dependent)
03541       return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
03542                                           Context.DependentTy, RParenLoc));
03543 
03544     // Determine whether this is a call to an object (C++ [over.call.object]).
03545     if (Fn->getType()->isRecordType())
03546       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
03547                                                 CommaLocs, RParenLoc));
03548 
03549     Expr *NakedFn = Fn->IgnoreParens();
03550 
03551     // Determine whether this is a call to an unresolved member function.
03552     if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
03553       // If lookup was unresolved but not dependent (i.e. didn't find
03554       // an unresolved using declaration), it has to be an overloaded
03555       // function set, which means it must contain either multiple
03556       // declarations (all methods or method templates) or a single
03557       // method template.
03558       assert((MemE->getNumDecls() > 1) ||
03559              isa<FunctionTemplateDecl>(*MemE->decls_begin()));
03560       (void)MemE;
03561 
03562       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03563                                        CommaLocs, RParenLoc);
03564     }
03565 
03566     // Determine whether this is a call to a member function.
03567     if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
03568       NamedDecl *MemDecl = MemExpr->getMemberDecl();
03569       if (isa<CXXMethodDecl>(MemDecl))
03570         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
03571                                          CommaLocs, RParenLoc);
03572     }
03573 
03574     // Determine whether this is a call to a pointer-to-member function.
03575     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
03576       if (BO->getOpcode() == BinaryOperator::PtrMemD ||
03577           BO->getOpcode() == BinaryOperator::PtrMemI) {
03578         if (const FunctionProtoType *FPT =
03579               dyn_cast<FunctionProtoType>(BO->getType())) {
03580           QualType ResultTy = FPT->getResultType().getNonReferenceType();
03581 
03582           ExprOwningPtr<CXXMemberCallExpr>
03583             TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
03584                                                           NumArgs, ResultTy,
03585                                                           RParenLoc));
03586 
03587           if (CheckCallReturnType(FPT->getResultType(),
03588                                   BO->getRHS()->getSourceRange().getBegin(),
03589                                   TheCall.get(), 0))
03590             return ExprError();
03591 
03592           if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
03593                                       RParenLoc))
03594             return ExprError();
03595 
03596           return Owned(MaybeBindToTemporary(TheCall.release()).release());
03597         }
03598         return ExprError(Diag(Fn->getLocStart(),
03599                               diag::err_typecheck_call_not_function)
03600                               << Fn->getType() << Fn->getSourceRange());
03601       }
03602     }
03603   }
03604 
03605   // If we're directly calling a function, get the appropriate declaration.
03606   // Also, in C++, keep track of whether we should perform argument-dependent
03607   // lookup and whether there were any explicitly-specified template arguments.
03608 
03609   Expr *NakedFn = Fn->IgnoreParens();
03610   if (isa<UnresolvedLookupExpr>(NakedFn)) {
03611     UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
03612     return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
03613                                    CommaLocs, RParenLoc);
03614   }
03615 
03616   NamedDecl *NDecl = 0;
03617   if (isa<DeclRefExpr>(NakedFn))
03618     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
03619 
03620   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
03621 }
03622 
03623 /// BuildResolvedCallExpr - Build a call to a resolved expression,
03624 /// i.e. an expression not of \p OverloadTy.  The expression should
03625 /// unary-convert to an expression of function-pointer or
03626 /// block-pointer type.
03627 ///
03628 /// \param NDecl the declaration being called, if available
03629 Sema::OwningExprResult
03630 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
03631                             SourceLocation LParenLoc,
03632                             Expr **Args, unsigned NumArgs,
03633                             SourceLocation RParenLoc) {
03634   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
03635 
03636   // Promote the function operand.
03637   UsualUnaryConversions(Fn);
03638 
03639   // Make the call expr early, before semantic checks.  This guarantees cleanup
03640   // of arguments and function on error.
03641   ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
03642                                                                Args, NumArgs,
03643                                                                Context.BoolTy,
03644                                                                RParenLoc));
03645 
03646   const FunctionType *FuncT;
03647   if (!Fn->getType()->isBlockPointerType()) {
03648     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
03649     // have type pointer to function".
03650     const PointerType *PT = Fn->getType()->getAs<PointerType>();
03651     if (PT == 0)
03652       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03653         << Fn->getType() << Fn->getSourceRange());
03654     FuncT = PT->getPointeeType()->getAs<FunctionType>();
03655   } else { // This is a block call.
03656     FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
03657                 getAs<FunctionType>();
03658   }
03659   if (FuncT == 0)
03660     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
03661       << Fn->getType() << Fn->getSourceRange());
03662 
03663   // Check for a valid return type
03664   if (CheckCallReturnType(FuncT->getResultType(),
03665                           Fn->getSourceRange().getBegin(), TheCall.get(),
03666                           FDecl))
03667     return ExprError();
03668 
03669   // We know the result type of the call, set it.
03670   TheCall->setType(FuncT->getResultType().getNonReferenceType());
03671 
03672   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
03673     if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
03674                                 RParenLoc))
03675       return ExprError();
03676   } else {
03677     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
03678 
03679     if (FDecl) {
03680       // Check if we have too few/too many template arguments, based
03681       // on our knowledge of the function definition.
03682       const FunctionDecl *Def = 0;
03683       if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
03684         const FunctionProtoType *Proto =
03685             Def->getType()->getAs<FunctionProtoType>();
03686         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
03687           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
03688             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
03689         }
03690       }
03691     }
03692 
03693     // Promote the arguments (C99 6.5.2.2p6).
03694     for (unsigned i = 0; i != NumArgs; i++) {
03695       Expr *Arg = Args[i];
03696       DefaultArgumentPromotion(Arg);
03697       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
03698                               Arg->getType(),
03699                               PDiag(diag::err_call_incomplete_argument)
03700                                 << Arg->getSourceRange()))
03701         return ExprError();
03702       TheCall->setArg(i, Arg);
03703     }
03704   }
03705 
03706   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
03707     if (!Method->isStatic())
03708       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
03709         << Fn->getSourceRange());
03710 
03711   // Check for sentinels
03712   if (NDecl)
03713     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
03714 
03715   // Do special checking on direct calls to functions.
03716   if (FDecl) {
03717     if (CheckFunctionCall(FDecl, TheCall.get()))
03718       return ExprError();
03719 
03720     if (unsigned BuiltinID = FDecl->getBuiltinID())
03721       return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
03722   } else if (NDecl) {
03723     if (CheckBlockCall(NDecl, TheCall.get()))
03724       return ExprError();
03725   }
03726 
03727   return MaybeBindToTemporary(TheCall.take());
03728 }
03729 
03730 Action::OwningExprResult
03731 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
03732                            SourceLocation RParenLoc, ExprArg InitExpr) {
03733   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
03734   // FIXME: put back this assert when initializers are worked out.
03735   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
03736 
03737   TypeSourceInfo *TInfo;
03738   QualType literalType = GetTypeFromParser(Ty, &TInfo);
03739   if (!TInfo)
03740     TInfo = Context.getTrivialTypeSourceInfo(literalType);
03741 
03742   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
03743 }
03744 
03745 Action::OwningExprResult
03746 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
03747                                SourceLocation RParenLoc, ExprArg InitExpr) {
03748   QualType literalType = TInfo->getType();
03749   Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
03750 
03751   if (literalType->isArrayType()) {
03752     if (literalType->isVariableArrayType())
03753       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
03754         << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
03755   } else if (!literalType->isDependentType() &&
03756              RequireCompleteType(LParenLoc, literalType,
03757                       PDiag(diag::err_typecheck_decl_incomplete_type)
03758                         << SourceRange(LParenLoc,
03759                                        literalExpr->getSourceRange().getEnd())))
03760     return ExprError();
03761 
03762   InitializedEntity Entity
03763     = InitializedEntity::InitializeTemporary(literalType);
03764   InitializationKind Kind
03765     = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
03766                                      /*IsCStyleCast=*/true);
03767   InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
03768   OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
03769                                    MultiExprArg(*this, (void**)&literalExpr, 1),
03770                                             &literalType);
03771   if (Result.isInvalid())
03772     return ExprError();
03773   InitExpr.release();
03774   literalExpr = static_cast<Expr*>(Result.get());
03775 
03776   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
03777   if (isFileScope) { // 6.5.2.5p3
03778     if (CheckForConstantInitializer(literalExpr, literalType))
03779       return ExprError();
03780   }
03781 
03782   Result.release();
03783 
03784   return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
03785                                                  literalExpr, isFileScope));
03786 }
03787 
03788 Action::OwningExprResult
03789 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
03790                     SourceLocation RBraceLoc) {
03791   unsigned NumInit = initlist.size();
03792   Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
03793 
03794   // Semantic analysis for initializers is done by ActOnDeclarator() and
03795   // CheckInitializer() - it requires knowledge of the object being intialized.
03796 
03797   InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
03798                                                RBraceLoc);
03799   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
03800   return Owned(E);
03801 }
03802 
03803 static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
03804                                             QualType SrcTy, QualType DestTy) {
03805   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
03806     return CastExpr::CK_NoOp;
03807 
03808   if (SrcTy->hasPointerRepresentation()) {
03809     if (DestTy->hasPointerRepresentation())
03810       return DestTy->isObjCObjectPointerType() ?
03811                 CastExpr::CK_AnyPointerToObjCPointerCast :
03812                 CastExpr::CK_BitCast;
03813     if (DestTy->isIntegerType())
03814       return CastExpr::CK_PointerToIntegral;
03815   }
03816 
03817   if (SrcTy->isIntegerType()) {
03818     if (DestTy->isIntegerType())
03819       return CastExpr::CK_IntegralCast;
03820     if (DestTy->hasPointerRepresentation())
03821       return CastExpr::CK_IntegralToPointer;
03822     if (DestTy->isRealFloatingType())
03823       return CastExpr::CK_IntegralToFloating;
03824   }
03825 
03826   if (SrcTy->isRealFloatingType()) {
03827     if (DestTy->isRealFloatingType())
03828       return CastExpr::CK_FloatingCast;
03829     if (DestTy->isIntegerType())
03830       return CastExpr::CK_FloatingToIntegral;
03831   }
03832 
03833   // FIXME: Assert here.
03834   // assert(false && "Unhandled cast combination!");
03835   return CastExpr::CK_Unknown;
03836 }
03837 
03838 /// CheckCastTypes - Check type constraints for casting between types.
03839 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
03840                           CastExpr::CastKind& Kind,
03841                           CXXMethodDecl *& ConversionDecl,
03842                           bool FunctionalStyle) {
03843   if (getLangOptions().CPlusPlus)
03844     return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
03845                               ConversionDecl);
03846 
03847   DefaultFunctionArrayLvalueConversion(castExpr);
03848 
03849   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
03850   // type needs to be scalar.
03851   if (castType->isVoidType()) {
03852     // Cast to void allows any expr type.
03853     Kind = CastExpr::CK_ToVoid;
03854     return false;
03855   }
03856 
03857   if (!castType->isScalarType() && !castType->isVectorType()) {
03858     if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
03859         (castType->isStructureType() || castType->isUnionType())) {
03860       // GCC struct/union extension: allow cast to self.
03861       // FIXME: Check that the cast destination type is complete.
03862       Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
03863         << castType << castExpr->getSourceRange();
03864       Kind = CastExpr::CK_NoOp;
03865       return false;
03866     }
03867 
03868     if (castType->isUnionType()) {
03869       // GCC cast to union extension
03870       RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
03871       RecordDecl::field_iterator Field, FieldEnd;
03872       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
03873            Field != FieldEnd; ++Field) {
03874         if (Context.hasSameUnqualifiedType(Field->getType(),
03875                                            castExpr->getType())) {
03876           Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
03877             << castExpr->getSourceRange();
03878           break;
03879         }
03880       }
03881       if (Field == FieldEnd)
03882         return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
03883           << castExpr->getType() << castExpr->getSourceRange();
03884       Kind = CastExpr::CK_ToUnion;
03885       return false;
03886     }
03887 
03888     // Reject any other conversions to non-scalar types.
03889     return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
03890       << castType << castExpr->getSourceRange();
03891   }
03892 
03893   if (!castExpr->getType()->isScalarType() &&
03894       !castExpr->getType()->isVectorType()) {
03895     return Diag(castExpr->getLocStart(),
03896                 diag::err_typecheck_expect_scalar_operand)
03897       << castExpr->getType() << castExpr->getSourceRange();
03898   }
03899 
03900   if (castType->isExtVectorType())
03901     return CheckExtVectorCast(TyR, castType, castExpr, Kind);
03902 
03903   if (castType->isVectorType())
03904     return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
03905   if (castExpr->getType()->isVectorType())
03906     return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
03907 
03908   if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
03909     return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
03910 
03911   if (isa<ObjCSelectorExpr>(castExpr))
03912     return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
03913 
03914   if (!castType->isArithmeticType()) {
03915     QualType castExprType = castExpr->getType();
03916     if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
03917       return Diag(castExpr->getLocStart(),
03918                   diag::err_cast_pointer_from_non_pointer_int)
03919         << castExprType << castExpr->getSourceRange();
03920   } else if (!castExpr->getType()->isArithmeticType()) {
03921     if (!castType->isIntegralType() && castType->isArithmeticType())
03922       return Diag(castExpr->getLocStart(),
03923                   diag::err_cast_pointer_to_non_pointer_int)
03924         << castType << castExpr->getSourceRange();
03925   }
03926 
03927   Kind = getScalarCastKind(Context, castExpr->getType(), castType);
03928   return false;
03929 }
03930 
03931 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
03932                            CastExpr::CastKind &Kind) {
03933   assert(VectorTy->isVectorType() && "Not a vector type!");
03934 
03935   if (Ty->isVectorType() || Ty->isIntegerType()) {
03936     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
03937       return Diag(R.getBegin(),
03938                   Ty->isVectorType() ?
03939                   diag::err_invalid_conversion_between_vectors :
03940                   diag::err_invalid_conversion_between_vector_and_integer)
03941         << VectorTy << Ty << R;
03942   } else
03943     return Diag(R.getBegin(),
03944                 diag::err_invalid_conversion_between_vector_and_scalar)
03945       << VectorTy << Ty << R;
03946 
03947   Kind = CastExpr::CK_BitCast;
03948   return false;
03949 }
03950 
03951 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
03952                               CastExpr::CastKind &Kind) {
03953   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
03954 
03955   QualType SrcTy = CastExpr->getType();
03956 
03957   // If SrcTy is a VectorType, the total size must match to explicitly cast to
03958   // an ExtVectorType.
03959   if (SrcTy->isVectorType()) {
03960     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
03961       return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
03962         << DestTy << SrcTy << R;
03963     Kind = CastExpr::CK_BitCast;
03964     return false;
03965   }
03966 
03967   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
03968   // conversion will take place first from scalar to elt type, and then
03969   // splat from elt type to vector.
03970   if (SrcTy->isPointerType())
03971     return Diag(R.getBegin(),
03972                 diag::err_invalid_conversion_between_vector_and_scalar)
03973       << DestTy << SrcTy << R;
03974 
03975   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
03976   ImpCastExprToType(CastExpr, DestElemTy,
03977                     getScalarCastKind(Context, SrcTy, DestElemTy));
03978 
03979   Kind = CastExpr::CK_VectorSplat;
03980   return false;
03981 }
03982 
03983 Action::OwningExprResult
03984 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
03985                     SourceLocation RParenLoc, ExprArg Op) {
03986   assert((Ty != 0) && (Op.get() != 0) &&
03987          "ActOnCastExpr(): missing type or expr");
03988 
03989   TypeSourceInfo *castTInfo;
03990   QualType castType = GetTypeFromParser(Ty, &castTInfo);
03991   if (!castTInfo)
03992     castTInfo = Context.getTrivialTypeSourceInfo(castType);
03993 
03994   // If the Expr being casted is a ParenListExpr, handle it specially.
03995   Expr *castExpr = (Expr *)Op.get();
03996   if (isa<ParenListExpr>(castExpr))
03997     return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
03998                                     castTInfo);
03999 
04000   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
04001 }
04002 
04003 Action::OwningExprResult
04004 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
04005                           SourceLocation RParenLoc, ExprArg Op) {
04006   Expr *castExpr = static_cast<Expr*>(Op.get());
04007 
04008   CXXMethodDecl *Method = 0;
04009   CastExpr::CastKind Kind = CastExpr::CK_Unknown;
04010   if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
04011                      Kind, Method))
04012     return ExprError();
04013 
04014   if (Method) {
04015     // FIXME: preserve type source info here
04016     OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
04017                                                     Kind, Method, move(Op));
04018 
04019     if (CastArg.isInvalid())
04020       return ExprError();
04021 
04022     castExpr = CastArg.takeAs<Expr>();
04023   } else {
04024     Op.release();
04025   }
04026 
04027   return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
04028                                             Kind, castExpr, Ty,
04029                                             LParenLoc, RParenLoc));
04030 }
04031 
04032 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
04033 /// of comma binary operators.
04034 Action::OwningExprResult
04035 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
04036   Expr *expr = EA.takeAs<Expr>();
04037   ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
04038   if (!E)
04039     return Owned(expr);
04040 
04041   OwningExprResult Result(*this, E->getExpr(0));
04042 
04043   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
04044     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
04045                         Owned(E->getExpr(i)));
04046 
04047   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
04048 }
04049 
04050 Action::OwningExprResult
04051 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
04052                                SourceLocation RParenLoc, ExprArg Op,
04053                                TypeSourceInfo *TInfo) {
04054   ParenListExpr *PE = (ParenListExpr *)Op.get();
04055   QualType Ty = TInfo->getType();
04056 
04057   // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
04058   // then handle it as such.
04059   if (getLangOptions().AltiVec && Ty->isVectorType()) {
04060     if (PE->getNumExprs() == 0) {
04061       Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
04062       return ExprError();
04063     }
04064 
04065     llvm::SmallVector<Expr *, 8> initExprs;
04066     for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
04067       initExprs.push_back(PE->getExpr(i));
04068 
04069     // FIXME: This means that pretty-printing the final AST will produce curly
04070     // braces instead of the original commas.
04071     Op.release();
04072     InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
04073                                                  initExprs.size(), RParenLoc);
04074     E->setType(Ty);
04075     return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
04076   } else {
04077     // This is not an AltiVec-style cast, so turn the ParenListExpr into a
04078     // sequence of BinOp comma operators.
04079     Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
04080     return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
04081   }
04082 }
04083 
04084 Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
04085                                                   SourceLocation R,
04086                                                   MultiExprArg Val,
04087                                                   TypeTy *TypeOfCast) {
04088   unsigned nexprs = Val.size();
04089   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
04090   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
04091   Expr *expr;
04092   if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
04093     expr = new (Context) ParenExpr(L, R, exprs[0]);
04094   else
04095     expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
04096   return Owned(expr);
04097 }
04098 
04099 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
04100 /// In that case, lhs = cond.
04101 /// C99 6.5.15
04102 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
04103                                         SourceLocation QuestionLoc) {
04104   // C++ is sufficiently different to merit its own checker.
04105   if (getLangOptions().CPlusPlus)
04106     return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
04107 
04108   CheckSignCompare(LHS, RHS, QuestionLoc);
04109 
04110   UsualUnaryConversions(Cond);
04111   UsualUnaryConversions(LHS);
04112   UsualUnaryConversions(RHS);
04113   QualType CondTy = Cond->getType();
04114   QualType LHSTy = LHS->getType();
04115   QualType RHSTy = RHS->getType();
04116 
04117   // first, check the condition.
04118   if (!CondTy->isScalarType()) { // C99 6.5.15p2
04119     Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
04120       << CondTy;
04121     return QualType();
04122   }
04123 
04124   // Now check the two expressions.
04125   if (LHSTy->isVectorType() || RHSTy->isVectorType())
04126     return CheckVectorOperands(QuestionLoc, LHS, RHS);
04127 
04128   // If both operands have arithmetic type, do the usual arithmetic conversions
04129   // to find a common type: C99 6.5.15p3,5.
04130   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
04131     UsualArithmeticConversions(LHS, RHS);
04132     return LHS->getType();
04133   }
04134 
04135   // If both operands are the same structure or union type, the result is that
04136   // type.
04137   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
04138     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
04139       if (LHSRT->getDecl() == RHSRT->getDecl())
04140         // "If both the operands have structure or union type, the result has
04141         // that type."  This implies that CV qualifiers are dropped.
04142         return LHSTy.getUnqualifiedType();
04143     // FIXME: Type of conditional expression must be complete in C mode.
04144   }
04145 
04146   // C99 6.5.15p5: "If both operands have void type, the result has void type."
04147   // The following || allows only one side to be void (a GCC-ism).
04148   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
04149     if (!LHSTy->isVoidType())
04150       Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
04151         << RHS->getSourceRange();
04152     if (!RHSTy->isVoidType())
04153       Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
04154         << LHS->getSourceRange();
04155     ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
04156     ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
04157     return Context.VoidTy;
04158   }
04159   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
04160   // the type of the other operand."
04161   if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
04162       RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04163     // promote the null to a pointer.
04164     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
04165     return LHSTy;
04166   }
04167   if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
04168       LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04169     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
04170     return RHSTy;
04171   }
04172 
04173   // All objective-c pointer type analysis is done here.
04174   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
04175                                                         QuestionLoc);
04176   if (!compositeType.isNull())
04177     return compositeType;
04178 
04179 
04180   // Handle block pointer types.
04181   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
04182     if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
04183       if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
04184         QualType destType = Context.getPointerType(Context.VoidTy);
04185         ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04186         ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04187         return destType;
04188       }
04189       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04190       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04191       return QualType();
04192     }
04193     // We have 2 block pointer types.
04194     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04195       // Two identical block pointer types are always compatible.
04196       return LHSTy;
04197     }
04198     // The block pointer types aren't identical, continue checking.
04199     QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
04200     QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
04201 
04202     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
04203                                     rhptee.getUnqualifiedType())) {
04204       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
04205       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04206       // In this situation, we assume void* type. No especially good
04207       // reason, but this is what gcc does, and we do have to pick
04208       // to get a consistent AST.
04209       QualType incompatTy = Context.getPointerType(Context.VoidTy);
04210       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04211       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04212       return incompatTy;
04213     }
04214     // The block pointer types are compatible.
04215     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
04216     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04217     return LHSTy;
04218   }
04219 
04220   // Check constraints for C object pointers types (C99 6.5.15p3,6).
04221   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
04222     // get the "pointed to" types
04223     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04224     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04225 
04226     // ignore qualifiers on void (C99 6.5.15p3, clause 6)
04227     if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
04228       // Figure out necessary qualifiers (C99 6.5.15p6)
04229       QualType destPointee
04230         = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04231       QualType destType = Context.getPointerType(destPointee);
04232       // Add qualifiers if necessary.
04233       ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
04234       // Promote to void*.
04235       ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04236       return destType;
04237     }
04238     if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
04239       QualType destPointee
04240         = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04241       QualType destType = Context.getPointerType(destPointee);
04242       // Add qualifiers if necessary.
04243       ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
04244       // Promote to void*.
04245       ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04246       return destType;
04247     }
04248 
04249     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04250       // Two identical pointer types are always compatible.
04251       return LHSTy;
04252     }
04253     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
04254                                     rhptee.getUnqualifiedType())) {
04255       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
04256         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04257       // In this situation, we assume void* type. No especially good
04258       // reason, but this is what gcc does, and we do have to pick
04259       // to get a consistent AST.
04260       QualType incompatTy = Context.getPointerType(Context.VoidTy);
04261       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04262       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04263       return incompatTy;
04264     }
04265     // The pointer types are compatible.
04266     // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
04267     // differently qualified versions of compatible types, the result type is
04268     // a pointer to an appropriately qualified version of the *composite*
04269     // type.
04270     // FIXME: Need to calculate the composite type.
04271     // FIXME: Need to add qualifiers
04272     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
04273     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04274     return LHSTy;
04275   }
04276 
04277   // GCC compatibility: soften pointer/integer mismatch.
04278   if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
04279     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
04280       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04281     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
04282     return RHSTy;
04283   }
04284   if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
04285     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
04286       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04287     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
04288     return LHSTy;
04289   }
04290 
04291   // Otherwise, the operands are not compatible.
04292   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04293     << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
04294   return QualType();
04295 }
04296 
04297 /// FindCompositeObjCPointerType - Helper method to find composite type of
04298 /// two objective-c pointer types of the two input expressions.
04299 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
04300                                         SourceLocation QuestionLoc) {
04301   QualType LHSTy = LHS->getType();
04302   QualType RHSTy = RHS->getType();
04303 
04304   // Handle things like Class and struct objc_class*.  Here we case the result
04305   // to the pseudo-builtin, because that will be implicitly cast back to the
04306   // redefinition type if an attempt is made to access its fields.
04307   if (LHSTy->isObjCClassType() &&
04308       (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
04309     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04310     return LHSTy;
04311   }
04312   if (RHSTy->isObjCClassType() &&
04313       (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
04314     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04315     return RHSTy;
04316   }
04317   // And the same for struct objc_object* / id
04318   if (LHSTy->isObjCIdType() &&
04319       (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
04320     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04321     return LHSTy;
04322   }
04323   if (RHSTy->isObjCIdType() &&
04324       (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
04325     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04326     return RHSTy;
04327   }
04328   // And the same for struct objc_selector* / SEL
04329   if (Context.isObjCSelType(LHSTy) &&
04330       (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
04331     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
04332     return LHSTy;
04333   }
04334   if (Context.isObjCSelType(RHSTy) &&
04335       (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
04336     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
04337     return RHSTy;
04338   }
04339   // Check constraints for Objective-C object pointers types.
04340   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
04341 
04342     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
04343       // Two identical object pointer types are always compatible.
04344       return LHSTy;
04345     }
04346     const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
04347     const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
04348     QualType compositeType = LHSTy;
04349 
04350     // If both operands are interfaces and either operand can be
04351     // assigned to the other, use that type as the composite
04352     // type. This allows
04353     //   xxx ? (A*) a : (B*) b
04354     // where B is a subclass of A.
04355     //
04356     // Additionally, as for assignment, if either type is 'id'
04357     // allow silent coercion. Finally, if the types are
04358     // incompatible then make sure to use 'id' as the composite
04359     // type so the result is acceptable for sending messages to.
04360 
04361     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
04362     // It could return the composite type.
04363     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
04364       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
04365     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
04366       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
04367     } else if ((LHSTy->isObjCQualifiedIdType() ||
04368                 RHSTy->isObjCQualifiedIdType()) &&
04369                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
04370       // Need to handle "id<xx>" explicitly.
04371       // GCC allows qualified id and any Objective-C type to devolve to
04372       // id. Currently localizing to here until clear this should be
04373       // part of ObjCQualifiedIdTypesAreCompatible.
04374       compositeType = Context.getObjCIdType();
04375     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
04376       compositeType = Context.getObjCIdType();
04377     } else if (!(compositeType =
04378                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
04379       ;
04380     else {
04381       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
04382       << LHSTy << RHSTy
04383       << LHS->getSourceRange() << RHS->getSourceRange();
04384       QualType incompatTy = Context.getObjCIdType();
04385       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
04386       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
04387       return incompatTy;
04388     }
04389     // The object pointer types are compatible.
04390     ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
04391     ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
04392     return compositeType;
04393   }
04394   // Check Objective-C object pointer types and 'void *'
04395   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
04396     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
04397     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04398     QualType destPointee
04399     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
04400     QualType destType = Context.getPointerType(destPointee);
04401     // Add qualifiers if necessary.
04402     ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
04403     // Promote to void*.
04404     ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
04405     return destType;
04406   }
04407   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
04408     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
04409     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
04410     QualType destPointee
04411     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
04412     QualType destType = Context.getPointerType(destPointee);
04413     // Add qualifiers if necessary.
04414     ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
04415     // Promote to void*.
04416     ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
04417     return destType;
04418   }
04419   return QualType();
04420 }
04421 
04422 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
04423 /// in the case of a the GNU conditional expr extension.
04424 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
04425                                                   SourceLocation ColonLoc,
04426                                                   ExprArg Cond, ExprArg LHS,
04427                                                   ExprArg RHS) {
04428   Expr *CondExpr = (Expr *) Cond.get();
04429   Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
04430 
04431   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
04432   // was the condition.
04433   bool isLHSNull = LHSExpr == 0;
04434   if (isLHSNull)
04435     LHSExpr = CondExpr;
04436 
04437   QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
04438                                              RHSExpr, QuestionLoc);
04439   if (result.isNull())
04440     return ExprError();
04441 
04442   Cond.release();
04443   LHS.release();
04444   RHS.release();
04445   return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
04446                                                  isLHSNull ? 0 : LHSExpr,
04447                                                  ColonLoc, RHSExpr, result));
04448 }
04449 
04450 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
04451 // being closely modeled after the C99 spec:-). The odd characteristic of this
04452 // routine is it effectively iqnores the qualifiers on the top level pointee.
04453 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
04454 // FIXME: add a couple examples in this comment.
04455 Sema::AssignConvertType
04456 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
04457   QualType lhptee, rhptee;
04458 
04459   if ((lhsType->isObjCClassType() &&
04460        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
04461      (rhsType->isObjCClassType() &&
04462        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
04463       return Compatible;
04464   }
04465 
04466   // get the "pointed to" type (ignoring qualifiers at the top level)
04467   lhptee = lhsType->getAs<PointerType>()->getPointeeType();
04468   rhptee = rhsType->getAs<PointerType>()->getPointeeType();
04469 
04470   // make sure we operate on the canonical type
04471   lhptee = Context.getCanonicalType(lhptee);
04472   rhptee = Context.getCanonicalType(rhptee);
04473 
04474   AssignConvertType ConvTy = Compatible;
04475 
04476   // C99 6.5.16.1p1: This following citation is common to constraints
04477   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
04478   // qualifiers of the type *pointed to* by the right;
04479   // FIXME: Handle ExtQualType
04480   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
04481     ConvTy = CompatiblePointerDiscardsQualifiers;
04482 
04483   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
04484   // incomplete type and the other is a pointer to a qualified or unqualified
04485   // version of void...
04486   if (lhptee->isVoidType()) {
04487     if (rhptee->isIncompleteOrObjectType())
04488       return ConvTy;
04489 
04490     // As an extension, we allow cast to/from void* to function pointer.
04491     assert(rhptee->isFunctionType());
04492     return FunctionVoidPointer;
04493   }
04494 
04495   if (rhptee->isVoidType()) {
04496     if (lhptee->isIncompleteOrObjectType())
04497       return ConvTy;
04498 
04499     // As an extension, we allow cast to/from void* to function pointer.
04500     assert(lhptee->isFunctionType());
04501     return FunctionVoidPointer;
04502   }
04503   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
04504   // unqualified versions of compatible types, ...
04505   lhptee = lhptee.getUnqualifiedType();
04506   rhptee = rhptee.getUnqualifiedType();
04507   if (!Context.typesAreCompatible(lhptee, rhptee)) {
04508     // Check if the pointee types are compatible ignoring the sign.
04509     // We explicitly check for char so that we catch "char" vs
04510     // "unsigned char" on systems where "char" is unsigned.
04511     if (lhptee->isCharType())
04512       lhptee = Context.UnsignedCharTy;
04513     else if (lhptee->isSignedIntegerType())
04514       lhptee = Context.getCorrespondingUnsignedType(lhptee);
04515 
04516     if (rhptee->isCharType())
04517       rhptee = Context.UnsignedCharTy;
04518     else if (rhptee->isSignedIntegerType())
04519       rhptee = Context.getCorrespondingUnsignedType(rhptee);
04520 
04521     if (lhptee == rhptee) {
04522       // Types are compatible ignoring the sign. Qualifier incompatibility
04523       // takes priority over sign incompatibility because the sign
04524       // warning can be disabled.
04525       if (ConvTy != Compatible)
04526         return ConvTy;
04527       return IncompatiblePointerSign;
04528     }
04529 
04530     // If we are a multi-level pointer, it's possible that our issue is simply
04531     // one of qualification - e.g. char ** -> const char ** is not allowed. If
04532     // the eventual target type is the same and the pointers have the same
04533     // level of indirection, this must be the issue.
04534     if (lhptee->isPointerType() && rhptee->isPointerType()) {
04535       do {
04536         lhptee = lhptee->getAs<PointerType>()->getPointeeType();
04537         rhptee = rhptee->getAs<PointerType>()->getPointeeType();
04538 
04539         lhptee = Context.getCanonicalType(lhptee);
04540         rhptee = Context.getCanonicalType(rhptee);
04541       } while (lhptee->isPointerType() && rhptee->isPointerType());
04542 
04543       if (Context.hasSameUnqualifiedType(lhptee, rhptee))
04544         return IncompatibleNestedPointerQualifiers;
04545     }
04546 
04547     // General pointer incompatibility takes priority over qualifiers.
04548     return IncompatiblePointer;
04549   }
04550   return ConvTy;
04551 }
04552 
04553 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
04554 /// block pointer types are compatible or whether a block and normal pointer
04555 /// are compatible. It is more restrict than comparing two function pointer
04556 // types.
04557 Sema::AssignConvertType
04558 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
04559                                           QualType rhsType) {
04560   QualType lhptee, rhptee;
04561 
04562   // get the "pointed to" type (ignoring qualifiers at the top level)
04563   lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
04564   rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
04565 
04566   // make sure we operate on the canonical type
04567   lhptee = Context.getCanonicalType(lhptee);
04568   rhptee = Context.getCanonicalType(rhptee);
04569 
04570   AssignConvertType ConvTy = Compatible;
04571 
04572   // For blocks we enforce that qualifiers are identical.
04573   if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
04574     ConvTy = CompatiblePointerDiscardsQualifiers;
04575 
04576   if (!Context.typesAreCompatible(lhptee, rhptee))
04577     return IncompatibleBlockPointer;
04578   return ConvTy;
04579 }
04580 
04581 /// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
04582 /// for assignment compatibility.
04583 Sema::AssignConvertType
04584 Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
04585   if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
04586     return Compatible;
04587   QualType lhptee =
04588   lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
04589   QualType rhptee =
04590   rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
04591   // make sure we operate on the canonical type
04592   lhptee = Context.getCanonicalType(lhptee);
04593   rhptee = Context.getCanonicalType(rhptee);
04594   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
04595     return CompatiblePointerDiscardsQualifiers;
04596 
04597   if (Context.typesAreCompatible(lhsType, rhsType))
04598     return Compatible;
04599   if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
04600     return IncompatibleObjCQualifiedId;
04601   return IncompatiblePointer;
04602 }
04603 
04604 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
04605 /// has code to accommodate several GCC extensions when type checking
04606 /// pointers. Here are some objectionable examples that GCC considers warnings:
04607 ///
04608 ///  int a, *pint;
04609 ///  short *pshort;
04610 ///  struct foo *pfoo;
04611 ///
04612 ///  pint = pshort; // warning: assignment from incompatible pointer type
04613 ///  a = pint; // warning: assignment makes integer from pointer without a cast
04614 ///  pint = a; // warning: assignment makes pointer from integer without a cast
04615 ///  pint = pfoo; // warning: assignment from incompatible pointer type
04616 ///
04617 /// As a result, the code for dealing with pointers is more complex than the
04618 /// C99 spec dictates.
04619 ///
04620 Sema::AssignConvertType
04621 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
04622   // Get canonical types.  We're not formatting these types, just comparing
04623   // them.
04624   lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
04625   rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
04626 
04627   if (lhsType == rhsType)
04628     return Compatible; // Common case: fast path an exact match.
04629 
04630   if ((lhsType->isObjCClassType() &&
04631        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
04632      (rhsType->isObjCClassType() &&
04633        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
04634       return Compatible;
04635   }
04636 
04637   // If the left-hand side is a reference type, then we are in a
04638   // (rare!) case where we've allowed the use of references in C,
04639   // e.g., as a parameter type in a built-in function. In this case,
04640   // just make sure that the type referenced is compatible with the
04641   // right-hand side type. The caller is responsible for adjusting
04642   // lhsType so that the resulting expression does not have reference
04643   // type.
04644   if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
04645     if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
04646       return Compatible;
04647     return Incompatible;
04648   }
04649   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
04650   // to the same ExtVector type.
04651   if (lhsType->isExtVectorType()) {
04652     if (rhsType->isExtVectorType())
04653       return lhsType == rhsType ? Compatible : Incompatible;
04654     if (!rhsType->isVectorType() && rhsType->isArithmeticType())
04655       return Compatible;
04656   }
04657 
04658   if (lhsType->isVectorType() || rhsType->isVectorType()) {
04659     // If we are allowing lax vector conversions, and LHS and RHS are both
04660     // vectors, the total size only needs to be the same. This is a bitcast;
04661     // no bits are changed but the result type is different.
04662     if (getLangOptions().LaxVectorConversions &&
04663         lhsType->isVectorType() && rhsType->isVectorType()) {
04664       if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
04665         return IncompatibleVectors;
04666     }
04667     return Incompatible;
04668   }
04669 
04670   if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
04671     return Compatible;
04672 
04673   if (isa<PointerType>(lhsType)) {
04674     if (rhsType->isIntegerType())
04675       return IntToPointer;
04676 
04677     if (isa<PointerType>(rhsType))
04678       return CheckPointerTypesForAssignment(lhsType, rhsType);
04679 
04680     // In general, C pointers are not compatible with ObjC object pointers.
04681     if (isa<ObjCObjectPointerType>(rhsType)) {
04682       if (lhsType->isVoidPointerType()) // an exception to the rule.
04683         return Compatible;
04684       return IncompatiblePointer;
04685     }
04686     if (rhsType->getAs<BlockPointerType>()) {
04687       if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04688         return Compatible;
04689 
04690       // Treat block pointers as objects.
04691       if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
04692         return Compatible;
04693     }
04694     return Incompatible;
04695   }
04696 
04697   if (isa<BlockPointerType>(lhsType)) {
04698     if (rhsType->isIntegerType())
04699       return IntToBlockPointer;
04700 
04701     // Treat block pointers as objects.
04702     if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
04703       return Compatible;
04704 
04705     if (rhsType->isBlockPointerType())
04706       return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
04707 
04708     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
04709       if (RHSPT->getPointeeType()->isVoidType())
04710         return Compatible;
04711     }
04712     return Incompatible;
04713   }
04714 
04715   if (isa<ObjCObjectPointerType>(lhsType)) {
04716     if (rhsType->isIntegerType())
04717       return IntToPointer;
04718 
04719     // In general, C pointers are not compatible with ObjC object pointers.
04720     if (isa<PointerType>(rhsType)) {
04721       if (rhsType->isVoidPointerType()) // an exception to the rule.
04722         return Compatible;
04723       return IncompatiblePointer;
04724     }
04725     if (rhsType->isObjCObjectPointerType()) {
04726       return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
04727     }
04728     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
04729       if (RHSPT->getPointeeType()->isVoidType())
04730         return Compatible;
04731     }
04732     // Treat block pointers as objects.
04733     if (rhsType->isBlockPointerType())
04734       return Compatible;
04735     return Incompatible;
04736   }
04737   if (isa<PointerType>(rhsType)) {
04738     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
04739     if (lhsType == Context.BoolTy)
04740       return Compatible;
04741 
04742     if (lhsType->isIntegerType())
04743       return PointerToInt;
04744 
04745     if (isa<PointerType>(lhsType))
04746       return CheckPointerTypesForAssignment(lhsType, rhsType);
04747 
04748     if (isa<BlockPointerType>(lhsType) &&
04749         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04750       return Compatible;
04751     return Incompatible;
04752   }
04753   if (isa<ObjCObjectPointerType>(rhsType)) {
04754     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
04755     if (lhsType == Context.BoolTy)
04756       return Compatible;
04757 
04758     if (lhsType->isIntegerType())
04759       return PointerToInt;
04760 
04761     // In general, C pointers are not compatible with ObjC object pointers.
04762     if (isa<PointerType>(lhsType)) {
04763       if (lhsType->isVoidPointerType()) // an exception to the rule.
04764         return Compatible;
04765       return IncompatiblePointer;
04766     }
04767     if (isa<BlockPointerType>(lhsType) &&
04768         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
04769       return Compatible;
04770     return Incompatible;
04771   }
04772 
04773   if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
04774     if (Context.typesAreCompatible(lhsType, rhsType))
04775       return Compatible;
04776   }
04777   return Incompatible;
04778 }
04779 
04780 /// \brief Constructs a transparent union from an expression that is
04781 /// used to initialize the transparent union.
04782 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
04783                                       QualType UnionType, FieldDecl *Field) {
04784   // Build an initializer list that designates the appropriate member
04785   // of the transparent union.
04786   InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
04787                                                    &E, 1,
04788                                                    SourceLocation());
04789   Initializer->setType(UnionType);
04790   Initializer->setInitializedFieldInUnion(Field);
04791 
04792   // Build a compound literal constructing a value of the transparent
04793   // union type from this initializer list.
04794   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
04795   E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
04796                                   Initializer, false);
04797 }
04798 
04799 Sema::AssignConvertType
04800 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
04801   QualType FromType = rExpr->getType();
04802 
04803   // If the ArgType is a Union type, we want to handle a potential
04804   // transparent_union GCC extension.
04805   const RecordType *UT = ArgType->getAsUnionType();
04806   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
04807     return Incompatible;
04808 
04809   // The field to initialize within the transparent union.
04810   RecordDecl *UD = UT->getDecl();
04811   FieldDecl *InitField = 0;
04812   // It's compatible if the expression matches any of the fields.
04813   for (RecordDecl::field_iterator it = UD->field_begin(),
04814          itend = UD->field_end();
04815        it != itend; ++it) {
04816     if (it->getType()->isPointerType()) {
04817       // If the transparent union contains a pointer type, we allow:
04818       // 1) void pointer
04819       // 2) null pointer constant
04820       if (FromType->isPointerType())
04821         if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
04822           ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
04823           InitField = *it;
04824           break;
04825         }
04826 
04827       if (rExpr->isNullPointerConstant(Context,
04828                                        Expr::NPC_ValueDependentIsNull)) {
04829         ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
04830         InitField = *it;
04831         break;
04832       }
04833     }
04834 
04835     if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
04836           == Compatible) {
04837       InitField = *it;
04838       break;
04839     }
04840   }
04841 
04842   if (!InitField)
04843     return Incompatible;
04844 
04845   ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
04846   return Compatible;
04847 }
04848 
04849 Sema::AssignConvertType
04850 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
04851   if (getLangOptions().CPlusPlus) {
04852     if (!lhsType->isRecordType()) {
04853       // C++ 5.17p3: If the left operand is not of class type, the
04854       // expression is implicitly converted (C++ 4) to the
04855       // cv-unqualified type of the left operand.
04856       if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
04857                                     AA_Assigning))
04858         return Incompatible;
04859       return Compatible;
04860     }
04861 
04862     // FIXME: Currently, we fall through and treat C++ classes like C
04863     // structures.
04864   }
04865 
04866   // C99 6.5.16.1p1: the left operand is a pointer and the right is
04867   // a null pointer constant.
04868   if ((lhsType->isPointerType() ||
04869        lhsType->isObjCObjectPointerType() ||
04870        lhsType->isBlockPointerType())
04871       && rExpr->isNullPointerConstant(Context,
04872                                       Expr::NPC_ValueDependentIsNull)) {
04873     ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
04874     return Compatible;
04875   }
04876 
04877   // This check seems unnatural, however it is necessary to ensure the proper
04878   // conversion of functions/arrays. If the conversion were done for all
04879   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
04880   // expressions that surpress this implicit conversion (&, sizeof).
04881   //
04882   // Suppress this for references: C++ 8.5.3p5.
04883   if (!lhsType->isReferenceType())
04884     DefaultFunctionArrayLvalueConversion(rExpr);
04885 
04886   Sema::AssignConvertType result =
04887     CheckAssignmentConstraints(lhsType, rExpr->getType());
04888 
04889   // C99 6.5.16.1p2: The value of the right operand is converted to the
04890   // type of the assignment expression.
04891   // CheckAssignmentConstraints allows the left-hand side to be a reference,
04892   // so that we can use references in built-in functions even in C.
04893   // The getNonReferenceType() call makes sure that the resulting expression
04894   // does not have reference type.
04895   if (result != Incompatible && rExpr->getType() != lhsType)
04896     ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
04897                       CastExpr::CK_Unknown);
04898   return result;
04899 }
04900 
04901 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
04902   Diag(Loc, diag::err_typecheck_invalid_operands)
04903     << lex->getType() << rex->getType()
04904     << lex->getSourceRange() << rex->getSourceRange();
04905   return QualType();
04906 }
04907 
04908 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
04909   // For conversion purposes, we ignore any qualifiers.
04910   // For example, "const float" and "float" are equivalent.
04911   QualType lhsType =
04912     Context.getCanonicalType(lex->getType()).getUnqualifiedType();
04913   QualType rhsType =
04914     Context.getCanonicalType(rex->getType()).getUnqualifiedType();
04915 
04916   // If the vector types are identical, return.
04917   if (lhsType == rhsType)
04918     return lhsType;
04919 
04920   // Handle the case of a vector & extvector type of the same size and element
04921   // type.  It would be nice if we only had one vector type someday.
04922   if (getLangOptions().LaxVectorConversions) {
04923     // FIXME: Should we warn here?
04924     if (const VectorType *LV = lhsType->getAs<VectorType>()) {
04925       if (const VectorType *RV = rhsType->getAs<VectorType>())
04926         if (LV->getElementType() == RV->getElementType() &&
04927             LV->getNumElements() == RV->getNumElements()) {
04928           return lhsType->isExtVectorType() ? lhsType : rhsType;
04929         }
04930     }
04931   }
04932 
04933   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
04934   // swap back (so that we don't reverse the inputs to a subtract, for instance.
04935   bool swapped = false;
04936   if (rhsType->isExtVectorType()) {
04937     swapped = true;
04938     std::swap(rex, lex);
04939     std::swap(rhsType, lhsType);
04940   }
04941 
04942   // Handle the case of an ext vector and scalar.
04943   if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
04944     QualType EltTy = LV->getElementType();
04945     if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
04946       if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
04947         ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
04948         if (swapped) std::swap(rex, lex);
04949         return lhsType;
04950       }
04951     }
04952     if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
04953         rhsType->isRealFloatingType()) {
04954       if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
04955         ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
04956         if (swapped) std::swap(rex, lex);
04957         return lhsType;
04958       }
04959     }
04960   }
04961 
04962   // Vectors of different size or scalar and non-ext-vector are errors.
04963   Diag(Loc, diag::err_typecheck_vector_not_convertable)
04964     << lex->getType() << rex->getType()
04965     << lex->getSourceRange() << rex->getSourceRange();
04966   return QualType();
04967 }
04968 
04969 QualType Sema::CheckMultiplyDivideOperands(
04970   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
04971   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
04972     return CheckVectorOperands(Loc, lex, rex);
04973 
04974   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
04975 
04976   if (!lex->getType()->isArithmeticType() ||
04977       !rex->getType()->isArithmeticType())
04978     return InvalidOperands(Loc, lex, rex);
04979 
04980   // Check for division by zero.
04981   if (isDiv &&
04982       rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
04983     DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
04984                                      << rex->getSourceRange());
04985 
04986   return compType;
04987 }
04988 
04989 QualType Sema::CheckRemainderOperands(
04990   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
04991   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
04992     if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
04993       return CheckVectorOperands(Loc, lex, rex);
04994     return InvalidOperands(Loc, lex, rex);
04995   }
04996 
04997   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
04998 
04999   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
05000     return InvalidOperands(Loc, lex, rex);
05001 
05002   // Check for remainder by zero.
05003   if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
05004     DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
05005                                  << rex->getSourceRange());
05006 
05007   return compType;
05008 }
05009 
05010 QualType Sema::CheckAdditionOperands( // C99 6.5.6
05011   Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
05012   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
05013     QualType compType = CheckVectorOperands(Loc, lex, rex);
05014     if (CompLHSTy) *CompLHSTy = compType;
05015     return compType;
05016   }
05017 
05018   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
05019 
05020   // handle the common case first (both operands are arithmetic).
05021   if (lex->getType()->isArithmeticType() &&
05022       rex->getType()->isArithmeticType()) {
05023     if (CompLHSTy) *CompLHSTy = compType;
05024     return compType;
05025   }
05026 
05027   // Put any potential pointer into PExp
05028   Expr* PExp = lex, *IExp = rex;
05029   if (IExp->getType()->isAnyPointerType())
05030     std::swap(PExp, IExp);
05031 
05032   if (PExp->getType()->isAnyPointerType()) {
05033 
05034     if (IExp->getType()->isIntegerType()) {
05035       QualType PointeeTy = PExp->getType()->getPointeeType();
05036 
05037       // Check for arithmetic on pointers to incomplete types.
05038       if (PointeeTy->isVoidType()) {
05039         if (getLangOptions().CPlusPlus) {
05040           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05041             << lex->getSourceRange() << rex->getSourceRange();
05042           return QualType();
05043         }
05044 
05045         // GNU extension: arithmetic on pointer to void
05046         Diag(Loc, diag::ext_gnu_void_ptr)
05047           << lex->getSourceRange() << rex->getSourceRange();
05048       } else if (PointeeTy->isFunctionType()) {
05049         if (getLangOptions().CPlusPlus) {
05050           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05051             << lex->getType() << lex->getSourceRange();
05052           return QualType();
05053         }
05054 
05055         // GNU extension: arithmetic on pointer to function
05056         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05057           << lex->getType() << lex->getSourceRange();
05058       } else {
05059         // Check if we require a complete type.
05060         if (((PExp->getType()->isPointerType() &&
05061               !PExp->getType()->isDependentType()) ||
05062               PExp->getType()->isObjCObjectPointerType()) &&
05063              RequireCompleteType(Loc, PointeeTy,
05064                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
05065                              << PExp->getSourceRange()
05066                              << PExp->getType()))
05067           return QualType();
05068       }
05069       // Diagnose bad cases where we step over interface counts.
05070       if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05071         Diag(Loc, diag::err_arithmetic_nonfragile_interface)
05072           << PointeeTy << PExp->getSourceRange();
05073         return QualType();
05074       }
05075 
05076       if (CompLHSTy) {
05077         QualType LHSTy = Context.isPromotableBitField(lex);
05078         if (LHSTy.isNull()) {
05079           LHSTy = lex->getType();
05080           if (LHSTy->isPromotableIntegerType())
05081             LHSTy = Context.getPromotedIntegerType(LHSTy);
05082         }
05083         *CompLHSTy = LHSTy;
05084       }
05085       return PExp->getType();
05086     }
05087   }
05088 
05089   return InvalidOperands(Loc, lex, rex);
05090 }
05091 
05092 // C99 6.5.6
05093 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
05094                                         SourceLocation Loc, QualType* CompLHSTy) {
05095   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
05096     QualType compType = CheckVectorOperands(Loc, lex, rex);
05097     if (CompLHSTy) *CompLHSTy = compType;
05098     return compType;
05099   }
05100 
05101   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
05102 
05103   // Enforce type constraints: C99 6.5.6p3.
05104 
05105   // Handle the common case first (both operands are arithmetic).
05106   if (lex->getType()->isArithmeticType()
05107       && rex->getType()->isArithmeticType()) {
05108     if (CompLHSTy) *CompLHSTy = compType;
05109     return compType;
05110   }
05111 
05112   // Either ptr - int   or   ptr - ptr.
05113   if (lex->getType()->isAnyPointerType()) {
05114     QualType lpointee = lex->getType()->getPointeeType();
05115 
05116     // The LHS must be an completely-defined object type.
05117 
05118     bool ComplainAboutVoid = false;
05119     Expr *ComplainAboutFunc = 0;
05120     if (lpointee->isVoidType()) {
05121       if (getLangOptions().CPlusPlus) {
05122         Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05123           << lex->getSourceRange() << rex->getSourceRange();
05124         return QualType();
05125       }
05126 
05127       // GNU C extension: arithmetic on pointer to void
05128       ComplainAboutVoid = true;
05129     } else if (lpointee->isFunctionType()) {
05130       if (getLangOptions().CPlusPlus) {
05131         Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05132           << lex->getType() << lex->getSourceRange();
05133         return QualType();
05134       }
05135 
05136       // GNU C extension: arithmetic on pointer to function
05137       ComplainAboutFunc = lex;
05138     } else if (!lpointee->isDependentType() &&
05139                RequireCompleteType(Loc, lpointee,
05140                                    PDiag(diag::err_typecheck_sub_ptr_object)
05141                                      << lex->getSourceRange()
05142                                      << lex->getType()))
05143       return QualType();
05144 
05145     // Diagnose bad cases where we step over interface counts.
05146     if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05147       Diag(Loc, diag::err_arithmetic_nonfragile_interface)
05148         << lpointee << lex->getSourceRange();
05149       return QualType();
05150     }
05151 
05152     // The result type of a pointer-int computation is the pointer type.
05153     if (rex->getType()->isIntegerType()) {
05154       if (ComplainAboutVoid)
05155         Diag(Loc, diag::ext_gnu_void_ptr)
05156           << lex->getSourceRange() << rex->getSourceRange();
05157       if (ComplainAboutFunc)
05158         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05159           << ComplainAboutFunc->getType()
05160           << ComplainAboutFunc->getSourceRange();
05161 
05162       if (CompLHSTy) *CompLHSTy = lex->getType();
05163       return lex->getType();
05164     }
05165 
05166     // Handle pointer-pointer subtractions.
05167     if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
05168       QualType rpointee = RHSPTy->getPointeeType();
05169 
05170       // RHS must be a completely-type object type.
05171       // Handle the GNU void* extension.
05172       if (rpointee->isVoidType()) {
05173         if (getLangOptions().CPlusPlus) {
05174           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
05175             << lex->getSourceRange() << rex->getSourceRange();
05176           return QualType();
05177         }
05178 
05179         ComplainAboutVoid = true;
05180       } else if (rpointee->isFunctionType()) {
05181         if (getLangOptions().CPlusPlus) {
05182           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
05183             << rex->getType() << rex->getSourceRange();
05184           return QualType();
05185         }
05186 
05187         // GNU extension: arithmetic on pointer to function
05188         if (!ComplainAboutFunc)
05189           ComplainAboutFunc = rex;
05190       } else if (!rpointee->isDependentType() &&
05191                  RequireCompleteType(Loc, rpointee,
05192                                      PDiag(diag::err_typecheck_sub_ptr_object)
05193                                        << rex->getSourceRange()
05194                                        << rex->getType()))
05195         return QualType();
05196 
05197       if (getLangOptions().CPlusPlus) {
05198         // Pointee types must be the same: C++ [expr.add]
05199         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
05200           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
05201             << lex->getType() << rex->getType()
05202             << lex->getSourceRange() << rex->getSourceRange();
05203           return QualType();
05204         }
05205       } else {
05206         // Pointee types must be compatible C99 6.5.6p3
05207         if (!Context.typesAreCompatible(
05208                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
05209                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
05210           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
05211             << lex->getType() << rex->getType()
05212             << lex->getSourceRange() << rex->getSourceRange();
05213           return QualType();
05214         }
05215       }
05216 
05217       if (ComplainAboutVoid)
05218         Diag(Loc, diag::ext_gnu_void_ptr)
05219           << lex->getSourceRange() << rex->getSourceRange();
05220       if (ComplainAboutFunc)
05221         Diag(Loc, diag::ext_gnu_ptr_func_arith)
05222           << ComplainAboutFunc->getType()
05223           << ComplainAboutFunc->getSourceRange();
05224 
05225       if (CompLHSTy) *CompLHSTy = lex->getType();
05226       return Context.getPointerDiffType();
05227     }
05228   }
05229 
05230   return InvalidOperands(Loc, lex, rex);
05231 }
05232 
05233 // C99 6.5.7
05234 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
05235                                   bool isCompAssign) {
05236   // C99 6.5.7p2: Each of the operands shall have integer type.
05237   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
05238     return InvalidOperands(Loc, lex, rex);
05239 
05240   // Vector shifts promote their scalar inputs to vector type.
05241   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05242     return CheckVectorOperands(Loc, lex, rex);
05243 
05244   // Shifts don't perform usual arithmetic conversions, they just do integer
05245   // promotions on each operand. C99 6.5.7p3
05246   QualType LHSTy = Context.isPromotableBitField(lex);
05247   if (LHSTy.isNull()) {
05248     LHSTy = lex->getType();
05249     if (LHSTy->isPromotableIntegerType())
05250       LHSTy = Context.getPromotedIntegerType(LHSTy);
05251   }
05252   if (!isCompAssign)
05253     ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
05254 
05255   UsualUnaryConversions(rex);
05256 
05257   // Sanity-check shift operands
05258   llvm::APSInt Right;
05259   // Check right/shifter operand
05260   if (!rex->isValueDependent() &&
05261       rex->isIntegerConstantExpr(Right, Context)) {
05262     if (Right.isNegative())
05263       Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
05264     else {
05265       llvm::APInt LeftBits(Right.getBitWidth(),
05266                           Context.getTypeSize(lex->getType()));
05267       if (Right.uge(LeftBits))
05268         Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
05269     }
05270   }
05271 
05272   // "The type of the result is that of the promoted left operand."
05273   return LHSTy;
05274 }
05275 
05276 // C99 6.5.8, C++ [expr.rel]
05277 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
05278                                     unsigned OpaqueOpc, bool isRelational) {
05279   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
05280 
05281   // Handle vector comparisons separately.
05282   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05283     return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
05284 
05285   CheckSignCompare(lex, rex, Loc, &Opc);
05286 
05287   // C99 6.5.8p3 / C99 6.5.9p4
05288   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
05289     UsualArithmeticConversions(lex, rex);
05290   else {
05291     UsualUnaryConversions(lex);
05292     UsualUnaryConversions(rex);
05293   }
05294   QualType lType = lex->getType();
05295   QualType rType = rex->getType();
05296 
05297   if (!lType->isFloatingType()
05298       && !(lType->isBlockPointerType() && isRelational)) {
05299     // For non-floating point types, check for self-comparisons of the form
05300     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
05301     // often indicate logic errors in the program.
05302     // NOTE: Don't warn about comparisons of enum constants. These can arise
05303     //  from macro expansions, and are usually quite deliberate.
05304     Expr *LHSStripped = lex->IgnoreParens();
05305     Expr *RHSStripped = rex->IgnoreParens();
05306     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
05307       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
05308         if (DRL->getDecl() == DRR->getDecl() &&
05309             !isa<EnumConstantDecl>(DRL->getDecl()))
05310           DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
05311 
05312     if (isa<CastExpr>(LHSStripped))
05313       LHSStripped = LHSStripped->IgnoreParenCasts();
05314     if (isa<CastExpr>(RHSStripped))
05315       RHSStripped = RHSStripped->IgnoreParenCasts();
05316 
05317     // Warn about comparisons against a string constant (unless the other
05318     // operand is null), the user probably wants strcmp.
05319     Expr *literalString = 0;
05320     Expr *literalStringStripped = 0;
05321     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
05322         !RHSStripped->isNullPointerConstant(Context,
05323                                             Expr::NPC_ValueDependentIsNull)) {
05324       literalString = lex;
05325       literalStringStripped = LHSStripped;
05326     } else if ((isa<StringLiteral>(RHSStripped) ||
05327                 isa<ObjCEncodeExpr>(RHSStripped)) &&
05328                !LHSStripped->isNullPointerConstant(Context,
05329                                             Expr::NPC_ValueDependentIsNull)) {
05330       literalString = rex;
05331       literalStringStripped = RHSStripped;
05332     }
05333 
05334     if (literalString) {
05335       std::string resultComparison;
05336       switch (Opc) {
05337       case BinaryOperator::LT: resultComparison = ") < 0"; break;
05338       case BinaryOperator::GT: resultComparison = ") > 0"; break;
05339       case BinaryOperator::LE: resultComparison = ") <= 0"; break;
05340       case BinaryOperator::GE: resultComparison = ") >= 0"; break;
05341       case BinaryOperator::EQ: resultComparison = ") == 0"; break;
05342       case BinaryOperator::NE: resultComparison = ") != 0"; break;
05343       default: assert(false && "Invalid comparison operator");
05344       }
05345 
05346       DiagRuntimeBehavior(Loc,
05347         PDiag(diag::warn_stringcompare)
05348           << isa<ObjCEncodeExpr>(literalStringStripped)
05349           << literalString->getSourceRange()
05350           << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
05351           << CodeModificationHint::CreateInsertion(lex->getLocStart(),
05352                                                    "strcmp(")
05353           << CodeModificationHint::CreateInsertion(
05354                                          PP.getLocForEndOfToken(rex->getLocEnd()),
05355                                          resultComparison));
05356     }
05357   }
05358 
05359   // The result of comparisons is 'bool' in C++, 'int' in C.
05360   QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
05361 
05362   if (isRelational) {
05363     if (lType->isRealType() && rType->isRealType())
05364       return ResultTy;
05365   } else {
05366     // Check for comparisons of floating point operands using != and ==.
05367     if (lType->isFloatingType() && rType->isFloatingType())
05368       CheckFloatComparison(Loc,lex,rex);
05369 
05370     if (lType->isArithmeticType() && rType->isArithmeticType())
05371       return ResultTy;
05372   }
05373 
05374   bool LHSIsNull = lex->isNullPointerConstant(Context,
05375                                               Expr::NPC_ValueDependentIsNull);
05376   bool RHSIsNull = rex->isNullPointerConstant(Context,
05377                                               Expr::NPC_ValueDependentIsNull);
05378 
05379   // All of the following pointer related warnings are GCC extensions, except
05380   // when handling null pointer constants. One day, we can consider making them
05381   // errors (when -pedantic-errors is enabled).
05382   if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
05383     QualType LCanPointeeTy =
05384       Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
05385     QualType RCanPointeeTy =
05386       Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
05387 
05388     if (getLangOptions().CPlusPlus) {
05389       if (LCanPointeeTy == RCanPointeeTy)
05390         return ResultTy;
05391       if (!isRelational &&
05392           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
05393         // Valid unless comparison between non-null pointer and function pointer
05394         // This is a gcc extension compatibility comparison.
05395         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
05396             && !LHSIsNull && !RHSIsNull) {
05397           Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
05398             << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05399           ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05400           return ResultTy;
05401         }
05402       }
05403       // C++ [expr.rel]p2:
05404       //   [...] Pointer conversions (4.10) and qualification
05405       //   conversions (4.4) are performed on pointer operands (or on
05406       //   a pointer operand and a null pointer constant) to bring
05407       //   them to their composite pointer type. [...]
05408       //
05409       // C++ [expr.eq]p1 uses the same notion for (in)equality
05410       // comparisons of pointers.
05411       bool NonStandardCompositeType = false;
05412       QualType T = FindCompositePointerType(lex, rex,
05413                               isSFINAEContext()? 0 : &NonStandardCompositeType);
05414       if (T.isNull()) {
05415         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
05416           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05417         return QualType();
05418       } else if (NonStandardCompositeType) {
05419         Diag(Loc,
05420              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
05421           << lType << rType << T
05422           << lex->getSourceRange() << rex->getSourceRange();
05423       }
05424 
05425       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
05426       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
05427       return ResultTy;
05428     }
05429     // C99 6.5.9p2 and C99 6.5.8p2
05430     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
05431                                    RCanPointeeTy.getUnqualifiedType())) {
05432       // Valid unless a relational comparison of function pointers
05433       if (isRelational && LCanPointeeTy->isFunctionType()) {
05434         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
05435           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05436       }
05437     } else if (!isRelational &&
05438                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
05439       // Valid unless comparison between non-null pointer and function pointer
05440       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
05441           && !LHSIsNull && !RHSIsNull) {
05442         Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
05443           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05444       }
05445     } else {
05446       // Invalid
05447       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05448         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05449     }
05450     if (LCanPointeeTy != RCanPointeeTy)
05451       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05452     return ResultTy;
05453   }
05454 
05455   if (getLangOptions().CPlusPlus) {
05456     // Comparison of pointers with null pointer constants and equality
05457     // comparisons of member pointers to null pointer constants.
05458     if (RHSIsNull &&
05459         (lType->isPointerType() ||
05460          (!isRelational && lType->isMemberPointerType()))) {
05461       ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
05462       return ResultTy;
05463     }
05464     if (LHSIsNull &&
05465         (rType->isPointerType() ||
05466          (!isRelational && rType->isMemberPointerType()))) {
05467       ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
05468       return ResultTy;
05469     }
05470 
05471     // Comparison of member pointers.
05472     if (!isRelational &&
05473         lType->isMemberPointerType() && rType->isMemberPointerType()) {
05474       // C++ [expr.eq]p2:
05475       //   In addition, pointers to members can be compared, or a pointer to
05476       //   member and a null pointer constant. Pointer to member conversions
05477       //   (4.11) and qualification conversions (4.4) are performed to bring
05478       //   them to a common type. If one operand is a null pointer constant,
05479       //   the common type is the type of the other operand. Otherwise, the
05480       //   common type is a pointer to member type similar (4.4) to the type
05481       //   of one of the operands, with a cv-qualification signature (4.4)
05482       //   that is the union of the cv-qualification signatures of the operand
05483       //   types.
05484       bool NonStandardCompositeType = false;
05485       QualType T = FindCompositePointerType(lex, rex,
05486                               isSFINAEContext()? 0 : &NonStandardCompositeType);
05487       if (T.isNull()) {
05488         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
05489           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05490         return QualType();
05491       } else if (NonStandardCompositeType) {
05492         Diag(Loc,
05493              diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
05494           << lType << rType << T
05495           << lex->getSourceRange() << rex->getSourceRange();
05496       }
05497 
05498       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
05499       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
05500       return ResultTy;
05501     }
05502 
05503     // Comparison of nullptr_t with itself.
05504     if (lType->isNullPtrType() && rType->isNullPtrType())
05505       return ResultTy;
05506   }
05507 
05508   // Handle block pointer types.
05509   if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
05510     QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
05511     QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
05512 
05513     if (!LHSIsNull && !RHSIsNull &&
05514         !Context.typesAreCompatible(lpointee, rpointee)) {
05515       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
05516         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05517     }
05518     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05519     return ResultTy;
05520   }
05521   // Allow block pointers to be compared with null pointer constants.
05522   if (!isRelational
05523       && ((lType->isBlockPointerType() && rType->isPointerType())
05524           || (lType->isPointerType() && rType->isBlockPointerType()))) {
05525     if (!LHSIsNull && !RHSIsNull) {
05526       if (!((rType->isPointerType() && rType->getAs<PointerType>()
05527              ->getPointeeType()->isVoidType())
05528             || (lType->isPointerType() && lType->getAs<PointerType>()
05529                 ->getPointeeType()->isVoidType())))
05530         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
05531           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05532     }
05533     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05534     return ResultTy;
05535   }
05536 
05537   if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
05538     if (lType->isPointerType() || rType->isPointerType()) {
05539       const PointerType *LPT = lType->getAs<PointerType>();
05540       const PointerType *RPT = rType->getAs<PointerType>();
05541       bool LPtrToVoid = LPT ?
05542         Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
05543       bool RPtrToVoid = RPT ?
05544         Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
05545 
05546       if (!LPtrToVoid && !RPtrToVoid &&
05547           !Context.typesAreCompatible(lType, rType)) {
05548         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05549           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05550       }
05551       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05552       return ResultTy;
05553     }
05554     if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
05555       if (!Context.areComparableObjCPointerTypes(lType, rType))
05556         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
05557           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05558       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
05559       return ResultTy;
05560     }
05561   }
05562   if (lType->isAnyPointerType() && rType->isIntegerType()) {
05563     unsigned DiagID = 0;
05564     if (RHSIsNull) {
05565       if (isRelational)
05566         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
05567     } else if (isRelational)
05568       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
05569     else
05570       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
05571 
05572     if (DiagID) {
05573       Diag(Loc, DiagID)
05574         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05575     }
05576     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
05577     return ResultTy;
05578   }
05579   if (lType->isIntegerType() && rType->isAnyPointerType()) {
05580     unsigned DiagID = 0;
05581     if (LHSIsNull) {
05582       if (isRelational)
05583         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
05584     } else if (isRelational)
05585       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
05586     else
05587       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
05588 
05589     if (DiagID) {
05590       Diag(Loc, DiagID)
05591         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
05592     }
05593     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
05594     return ResultTy;
05595   }
05596   // Handle block pointers.
05597   if (!isRelational && RHSIsNull
05598       && lType->isBlockPointerType() && rType->isIntegerType()) {
05599     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
05600     return ResultTy;
05601   }
05602   if (!isRelational && LHSIsNull
05603       && lType->isIntegerType() && rType->isBlockPointerType()) {
05604     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
05605     return ResultTy;
05606   }
05607   return InvalidOperands(Loc, lex, rex);
05608 }
05609 
05610 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
05611 /// operates on extended vector types.  Instead of producing an IntTy result,
05612 /// like a scalar comparison, a vector comparison produces a vector of integer
05613 /// types.
05614 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
05615                                           SourceLocation Loc,
05616                                           bool isRelational) {
05617   // Check to make sure we're operating on vectors of the same type and width,
05618   // Allowing one side to be a scalar of element type.
05619   QualType vType = CheckVectorOperands(Loc, lex, rex);
05620   if (vType.isNull())
05621     return vType;
05622 
05623   QualType lType = lex->getType();
05624   QualType rType = rex->getType();
05625 
05626   // For non-floating point types, check for self-comparisons of the form
05627   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
05628   // often indicate logic errors in the program.
05629   if (!lType->isFloatingType()) {
05630     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
05631       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
05632         if (DRL->getDecl() == DRR->getDecl())
05633           DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
05634   }
05635 
05636   // Check for comparisons of floating point operands using != and ==.
05637   if (!isRelational && lType->isFloatingType()) {
05638     assert (rType->isFloatingType());
05639     CheckFloatComparison(Loc,lex,rex);
05640   }
05641 
05642   // Return the type for the comparison, which is the same as vector type for
05643   // integer vectors, or an integer type of identical size and number of
05644   // elements for floating point vectors.
05645   if (lType->isIntegerType())
05646     return lType;
05647 
05648   const VectorType *VTy = lType->getAs<VectorType>();
05649   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
05650   if (TypeSize == Context.getTypeSize(Context.IntTy))
05651     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
05652   if (TypeSize == Context.getTypeSize(Context.LongTy))
05653     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
05654 
05655   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
05656          "Unhandled vector element size in vector compare");
05657   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
05658 }
05659 
05660 inline QualType Sema::CheckBitwiseOperands(
05661   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
05662   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
05663     return CheckVectorOperands(Loc, lex, rex);
05664 
05665   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
05666 
05667   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
05668     return compType;
05669   return InvalidOperands(Loc, lex, rex);
05670 }
05671 
05672 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
05673   Expr *&lex, Expr *&rex, SourceLocation Loc) {
05674   if (!Context.getLangOptions().CPlusPlus) {
05675     UsualUnaryConversions(lex);
05676     UsualUnaryConversions(rex);
05677 
05678     if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
05679       return InvalidOperands(Loc, lex, rex);
05680 
05681     return Context.IntTy;
05682   }
05683 
05684   // C++ [expr.log.and]p1
05685   // C++ [expr.log.or]p1
05686   // The operands are both implicitly converted to type bool (clause 4).
05687   StandardConversionSequence LHS;
05688   if (!IsStandardConversion(lex, Context.BoolTy,
05689                             /*InOverloadResolution=*/false, LHS))
05690     return InvalidOperands(Loc, lex, rex);
05691 
05692   if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
05693                                 AA_Passing, /*IgnoreBaseAccess=*/false))
05694     return InvalidOperands(Loc, lex, rex);
05695 
05696   StandardConversionSequence RHS;
05697   if (!IsStandardConversion(rex, Context.BoolTy,
05698                             /*InOverloadResolution=*/false, RHS))
05699     return InvalidOperands(Loc, lex, rex);
05700 
05701   if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
05702                                 AA_Passing, /*IgnoreBaseAccess=*/false))
05703     return InvalidOperands(Loc, lex, rex);
05704 
05705   // C++ [expr.log.and]p2
05706   // C++ [expr.log.or]p2
05707   // The result is a bool.
05708   return Context.BoolTy;
05709 }
05710 
05711 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
05712 /// is a read-only property; return true if so. A readonly property expression
05713 /// depends on various declarations and thus must be treated specially.
05714 ///
05715 static bool IsReadonlyProperty(Expr *E, Sema &S) {
05716   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
05717     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
05718     if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
05719       QualType BaseType = PropExpr->getBase()->getType();
05720       if (const ObjCObjectPointerType *OPT =
05721             BaseType->getAsObjCInterfacePointerType())
05722         if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
05723           if (S.isPropertyReadonly(PDecl, IFace))
05724             return true;
05725     }
05726   }
05727   return false;
05728 }
05729 
05730 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
05731 /// emit an error and return true.  If so, return false.
05732 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
05733   SourceLocation OrigLoc = Loc;
05734   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
05735                                                               &Loc);
05736   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
05737     IsLV = Expr::MLV_ReadonlyProperty;
05738   if (IsLV == Expr::MLV_Valid)
05739     return false;
05740 
05741   unsigned Diag = 0;
05742   bool NeedType = false;
05743   switch (IsLV) { // C99 6.5.16p2
05744   case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
05745   case Expr::MLV_ArrayType:
05746     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
05747     NeedType = true;
05748     break;
05749   case Expr::MLV_NotObjectType:
05750     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
05751     NeedType = true;
05752     break;
05753   case Expr::MLV_LValueCast:
05754     Diag = diag::err_typecheck_lvalue_casts_not_supported;
05755     break;
05756   case Expr::MLV_Valid:
05757     llvm_unreachable("did not take early return for MLV_Valid");
05758   case Expr::MLV_InvalidExpression:
05759   case Expr::MLV_MemberFunction:
05760   case Expr::MLV_ClassTemporary:
05761     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
05762     break;
05763   case Expr::MLV_IncompleteType:
05764   case Expr::MLV_IncompleteVoidType:
05765     return S.RequireCompleteType(Loc, E->getType(),
05766                 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
05767                   << E->getSourceRange());
05768   case Expr::MLV_DuplicateVectorComponents:
05769     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
05770     break;
05771   case Expr::MLV_NotBlockQualified:
05772     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
05773     break;
05774   case Expr::MLV_ReadonlyProperty:
05775     Diag = diag::error_readonly_property_assignment;
05776     break;
05777   case Expr::MLV_NoSetterProperty:
05778     Diag = diag::error_nosetter_property_assignment;
05779     break;
05780   case Expr::MLV_SubObjCPropertySetting:
05781     Diag = diag::error_no_subobject_property_setting;
05782     break;
05783   case Expr::MLV_SubObjCPropertyGetterSetting:
05784     Diag = diag::error_no_subobject_property_getter_setting;
05785     break;
05786   }
05787 
05788   SourceRange Assign;
05789   if (Loc != OrigLoc)
05790     Assign = SourceRange(OrigLoc, OrigLoc);
05791   if (NeedType)
05792     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
05793   else
05794     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
05795   return true;
05796 }
05797 
05798 
05799 
05800 // C99 6.5.16.1
05801 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
05802                                        SourceLocation Loc,
05803                                        QualType CompoundType) {
05804   // Verify that LHS is a modifiable lvalue, and emit error if not.
05805   if (CheckForModifiableLvalue(LHS, Loc, *this))
05806     return QualType();
05807 
05808   QualType LHSType = LHS->getType();
05809   QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
05810 
05811   AssignConvertType ConvTy;
05812   if (CompoundType.isNull()) {
05813     // Simple assignment "x = y".
05814     ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
05815     // Special case of NSObject attributes on c-style pointer types.
05816     if (ConvTy == IncompatiblePointer &&
05817         ((Context.isObjCNSObjectType(LHSType) &&
05818           RHSType->isObjCObjectPointerType()) ||
05819          (Context.isObjCNSObjectType(RHSType) &&
05820           LHSType->isObjCObjectPointerType())))
05821       ConvTy = Compatible;
05822 
05823     // If the RHS is a unary plus or minus, check to see if they = and + are
05824     // right next to each other.  If so, the user may have typo'd "x =+ 4"
05825     // instead of "x += 4".
05826     Expr *RHSCheck = RHS;
05827     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
05828       RHSCheck = ICE->getSubExpr();
05829     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
05830       if ((UO->getOpcode() == UnaryOperator::Plus ||
05831            UO->getOpcode() == UnaryOperator::Minus) &&
05832           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
05833           // Only if the two operators are exactly adjacent.
05834           Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
05835           // And there is a space or other character before the subexpr of the
05836           // unary +/-.  We don't want to warn on "x=-1".
05837           Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
05838           UO->getSubExpr()->getLocStart().isFileID()) {
05839         Diag(Loc, diag::warn_not_compound_assign)
05840           << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
05841           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
05842       }
05843     }
05844   } else {
05845     // Compound assignment "x += y"
05846     ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
05847   }
05848 
05849   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
05850                                RHS, AA_Assigning))
05851     return QualType();
05852 
05853   // C99 6.5.16p3: The type of an assignment expression is the type of the
05854   // left operand unless the left operand has qualified type, in which case
05855   // it is the unqualified version of the type of the left operand.
05856   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
05857   // is converted to the type of the assignment expression (above).
05858   // C++ 5.17p1: the type of the assignment expression is that of its left
05859   // operand.
05860   return LHSType.getUnqualifiedType();
05861 }
05862 
05863 // C99 6.5.17
05864 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
05865   // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
05866   // C++ does not perform this conversion (C++ [expr.comma]p1).
05867   if (!getLangOptions().CPlusPlus)
05868     DefaultFunctionArrayLvalueConversion(RHS);
05869 
05870   // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
05871   // incomplete in C++).
05872 
05873   return RHS->getType();
05874 }
05875 
05876 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
05877 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
05878 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
05879                                               bool isInc) {
05880   if (Op->isTypeDependent())
05881     return Context.DependentTy;
05882 
05883   QualType ResType = Op->getType();
05884   assert(!ResType.isNull() && "no type for increment/decrement expression");
05885 
05886   if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
05887     // Decrement of bool is not allowed.
05888     if (!isInc) {
05889       Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
05890       return QualType();
05891     }
05892     // Increment of bool sets it to true, but is deprecated.
05893     Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
05894   } else if (ResType->isRealType()) {
05895     // OK!
05896   } else if (ResType->isAnyPointerType()) {
05897     QualType PointeeTy = ResType->getPointeeType();
05898 
05899     // C99 6.5.2.4p2, 6.5.6p2
05900     if (PointeeTy->isVoidType()) {
05901       if (getLangOptions().CPlusPlus) {
05902         Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
05903           << Op->getSourceRange();
05904         return QualType();
05905       }
05906 
05907       // Pointer to void is a GNU extension in C.
05908       Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
05909     } else if (PointeeTy->isFunctionType()) {
05910       if (getLangOptions().CPlusPlus) {
05911         Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
05912           << Op->getType() << Op->getSourceRange();
05913         return QualType();
05914       }
05915 
05916       Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
05917         << ResType << Op->getSourceRange();
05918     } else if (RequireCompleteType(OpLoc, PointeeTy,
05919                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
05920                              << Op->getSourceRange()
05921                              << ResType))
05922       return QualType();
05923     // Diagnose bad cases where we step over interface counts.
05924     else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
05925       Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
05926         << PointeeTy << Op->getSourceRange();
05927       return QualType();
05928     }
05929   } else if (ResType->isAnyComplexType()) {
05930     // C99 does not support ++/-- on complex types, we allow as an extension.
05931     Diag(OpLoc, diag::ext_integer_increment_complex)
05932       << ResType << Op->getSourceRange();
05933   } else {
05934     Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
05935       << ResType << int(isInc) << Op->getSourceRange();
05936     return QualType();
05937   }
05938   // At this point, we know we have a real, complex or pointer type.
05939   // Now make sure the operand is a modifiable lvalue.
05940   if (CheckForModifiableLvalue(Op, OpLoc, *this))
05941     return QualType();
05942   return ResType;
05943 }
05944 
05945 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
05946 /// This routine allows us to typecheck complex/recursive expressions
05947 /// where the declaration is needed for type checking. We only need to
05948 /// handle cases when the expression references a function designator
05949 /// or is an lvalue. Here are some examples:
05950 ///  - &(x) => x
05951 ///  - &*****f => f for f a function designator.
05952 ///  - &s.xx => s
05953 ///  - &s.zz[1].yy -> s, if zz is an array
05954 ///  - *(x + 1) -> x, if x is an array
05955 ///  - &"123"[2] -> 0
05956 ///  - & __real__ x -> x
05957 static NamedDecl *getPrimaryDecl(Expr *E) {
05958   switch (E->getStmtClass()) {
05959   case Stmt::DeclRefExprClass:
05960     return cast<DeclRefExpr>(E)->getDecl();
05961   case Stmt::MemberExprClass:
05962     // If this is an arrow operator, the address is an offset from
05963     // the base's value, so the object the base refers to is
05964     // irrelevant.
05965     if (cast<MemberExpr>(E)->isArrow())
05966       return 0;
05967     // Otherwise, the expression refers to a part of the base
05968     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
05969   case Stmt::ArraySubscriptExprClass: {
05970     // FIXME: This code shouldn't be necessary!  We should catch the implicit
05971     // promotion of register arrays earlier.
05972     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
05973     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
05974       if (ICE->getSubExpr()->getType()->isArrayType())
05975         return getPrimaryDecl(ICE->getSubExpr());
05976     }
05977     return 0;
05978   }
05979   case Stmt::UnaryOperatorClass: {
05980     UnaryOperator *UO = cast<UnaryOperator>(E);
05981 
05982     switch(UO->getOpcode()) {
05983     case UnaryOperator::Real:
05984     case UnaryOperator::Imag:
05985     case UnaryOperator::Extension:
05986       return getPrimaryDecl(UO->getSubExpr());
05987     default:
05988       return 0;
05989     }
05990   }
05991   case Stmt::ParenExprClass:
05992     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
05993   case Stmt::ImplicitCastExprClass:
05994     // If the result of an implicit cast is an l-value, we care about
05995     // the sub-expression; otherwise, the result here doesn't matter.
05996     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
05997   default:
05998     return 0;
05999   }
06000 }
06001 
06002 /// CheckAddressOfOperand - The operand of & must be either a function
06003 /// designator or an lvalue designating an object. If it is an lvalue, the
06004 /// object cannot be declared with storage class register or be a bit field.
06005 /// Note: The usual conversions are *not* applied to the operand of the &
06006 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
06007 /// In C++, the operand might be an overloaded function name, in which case
06008 /// we allow the '&' but retain the overloaded-function type.
06009 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
06010   // Make sure to ignore parentheses in subsequent checks
06011   op = op->IgnoreParens();
06012 
06013   if (op->isTypeDependent())
06014     return Context.DependentTy;
06015 
06016   if (getLangOptions().C99) {
06017     // Implement C99-only parts of addressof rules.
06018     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
06019       if (uOp->getOpcode() == UnaryOperator::Deref)
06020         // Per C99 6.5.3.2, the address of a deref always returns a valid result
06021         // (assuming the deref expression is valid).
06022         return uOp->getSubExpr()->getType();
06023     }
06024     // Technically, there should be a check for array subscript
06025     // expressions here, but the result of one is always an lvalue anyway.
06026   }
06027   NamedDecl *dcl = getPrimaryDecl(op);
06028   Expr::isLvalueResult lval = op->isLvalue(Context);
06029 
06030   MemberExpr *ME = dyn_cast<MemberExpr>(op);
06031   if (lval == Expr::LV_MemberFunction && ME &&
06032       isa<CXXMethodDecl>(ME->getMemberDecl())) {
06033     ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
06034     // &f where f is a member of the current object, or &o.f, or &p->f
06035     // All these are not allowed, and we need to catch them before the dcl
06036     // branch of the if, below.
06037     Diag(OpLoc, diag::err_unqualified_pointer_member_function)
06038         << dcl;
06039     // FIXME: Improve this diagnostic and provide a fixit.
06040 
06041     // Now recover by acting as if the function had been accessed qualified.
06042     return Context.getMemberPointerType(op->getType(),
06043                 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
06044                        .getTypePtr());
06045   } else if (lval == Expr::LV_ClassTemporary) {
06046     Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
06047                                  : diag::ext_typecheck_addrof_class_temporary)
06048       << op->getType() << op->getSourceRange();
06049     if (isSFINAEContext())
06050       return QualType();
06051   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
06052     // C99 6.5.3.2p1
06053     // The operand must be either an l-value or a function designator
06054     if (!op->getType()->isFunctionType()) {
06055       // FIXME: emit more specific diag...
06056       Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
06057         << op->getSourceRange();
06058       return QualType();
06059     }
06060   } else if (op->getBitField()) { // C99 6.5.3.2p1
06061     // The operand cannot be a bit-field
06062     Diag(OpLoc, diag::err_typecheck_address_of)
06063       << "bit-field" << op->getSourceRange();
06064         return QualType();
06065   } else if (op->refersToVectorElement()) {
06066     // The operand cannot be an element of a vector
06067     Diag(OpLoc, diag::err_typecheck_address_of)
06068       << "vector element" << op->getSourceRange();
06069     return QualType();
06070   } else if (isa<ObjCPropertyRefExpr>(op)) {
06071     // cannot take address of a property expression.
06072     Diag(OpLoc, diag::err_typecheck_address_of)
06073       << "property expression" << op->getSourceRange();
06074     return QualType();
06075   } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
06076     // FIXME: Can LHS ever be null here?
06077     if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
06078       return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
06079   } else if (isa<UnresolvedLookupExpr>(op)) {
06080     return Context.OverloadTy;
06081   } else if (dcl) { // C99 6.5.3.2p1
06082     // We have an lvalue with a decl. Make sure the decl is not declared
06083     // with the register storage-class specifier.
06084     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
06085       if (vd->getStorageClass() == VarDecl::Register) {
06086         Diag(OpLoc, diag::err_typecheck_address_of)
06087           << "register variable" << op->getSourceRange();
06088         return QualType();
06089       }
06090     } else if (isa<FunctionTemplateDecl>(dcl)) {
06091       return Context.OverloadTy;
06092     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
06093       // Okay: we can take the address of a field.
06094       // Could be a pointer to member, though, if there is an explicit
06095       // scope qualifier for the class.
06096       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
06097         DeclContext *Ctx = dcl->getDeclContext();
06098         if (Ctx && Ctx->isRecord()) {
06099           if (FD->getType()->isReferenceType()) {
06100             Diag(OpLoc,
06101                  diag::err_cannot_form_pointer_to_member_of_reference_type)
06102               << FD->getDeclName() << FD->getType();
06103             return QualType();
06104           }
06105 
06106           return Context.getMemberPointerType(op->getType(),
06107                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
06108         }
06109       }
06110     } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
06111       // Okay: we can take the address of a function.
06112       // As above.
06113       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
06114           MD->isInstance())
06115         return Context.getMemberPointerType(op->getType(),
06116               Context.getTypeDeclType(MD->getParent()).getTypePtr());
06117     } else if (!isa<FunctionDecl>(dcl))
06118       assert(0 && "Unknown/unexpected decl type");
06119   }
06120 
06121   if (lval == Expr::LV_IncompleteVoidType) {
06122     // Taking the address of a void variable is technically illegal, but we
06123     // allow it in cases which are otherwise valid.
06124     // Example: "extern void x; void* y = &x;".
06125     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
06126   }
06127 
06128   // If the operand has type "type", the result has type "pointer to type".
06129   return Context.getPointerType(op->getType());
06130 }
06131 
06132 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
06133   if (Op->isTypeDependent())
06134     return Context.DependentTy;
06135 
06136   UsualUnaryConversions(Op);
06137   QualType Ty = Op->getType();
06138 
06139   // Note that per both C89 and C99, this is always legal, even if ptype is an
06140   // incomplete type or void.  It would be possible to warn about dereferencing
06141   // a void pointer, but it's completely well-defined, and such a warning is
06142   // unlikely to catch any mistakes.
06143   if (const PointerType *PT = Ty->getAs<PointerType>())
06144     return PT->getPointeeType();
06145 
06146   if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
06147     return OPT->getPointeeType();
06148 
06149   Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
06150     << Ty << Op->getSourceRange();
06151   return QualType();
06152 }
06153 
06154 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
06155   tok::TokenKind Kind) {
06156   BinaryOperator::Opcode Opc;
06157   switch (Kind) {
06158   default: assert(0 && "Unknown binop!");
06159   case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
06160   case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
06161   case tok::star:                 Opc = BinaryOperator::Mul; break;
06162   case tok::slash:                Opc = BinaryOperator::Div; break;
06163   case tok::percent:              Opc = BinaryOperator::Rem; break;
06164   case tok::plus:                 Opc = BinaryOperator::Add; break;
06165   case tok::minus:                Opc = BinaryOperator::Sub; break;
06166   case tok::lessless:             Opc = BinaryOperator::Shl; break;
06167   case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
06168   case tok::lessequal:            Opc = BinaryOperator::LE; break;
06169   case tok::less:                 Opc = BinaryOperator::LT; break;
06170   case tok::greaterequal:         Opc = BinaryOperator::GE; break;
06171   case tok::greater:              Opc = BinaryOperator::GT; break;
06172   case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
06173   case tok::equalequal:           Opc = BinaryOperator::EQ; break;
06174   case tok::amp:                  Opc = BinaryOperator::And; break;
06175   case tok::caret:                Opc = BinaryOperator::Xor; break;
06176   case tok::pipe:                 Opc = BinaryOperator::Or; break;
06177   case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
06178   case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
06179   case tok::equal:                Opc = BinaryOperator::Assign; break;
06180   case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
06181   case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
06182   case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
06183   case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
06184   case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
06185   case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
06186   case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
06187   case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
06188   case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
06189   case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
06190   case tok::comma:                Opc = BinaryOperator::Comma; break;
06191   }
06192   return Opc;
06193 }
06194 
06195 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
06196   tok::TokenKind Kind) {
06197   UnaryOperator::Opcode Opc;
06198   switch (Kind) {
06199   default: assert(0 && "Unknown unary op!");
06200   case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
06201   case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
06202   case tok::amp:          Opc = UnaryOperator::AddrOf; break;
06203   case tok::star:         Opc = UnaryOperator::Deref; break;
06204   case tok::plus:         Opc = UnaryOperator::Plus; break;
06205   case tok::minus:        Opc = UnaryOperator::Minus; break;
06206   case tok::tilde:        Opc = UnaryOperator::Not; break;
06207   case tok::exclaim:      Opc = UnaryOperator::LNot; break;
06208   case tok::kw___real:    Opc = UnaryOperator::Real; break;
06209   case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
06210   case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
06211   }
06212   return Opc;
06213 }
06214 
06215 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
06216 /// operator @p Opc at location @c TokLoc. This routine only supports
06217 /// built-in operations; ActOnBinOp handles overloaded operators.
06218 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
06219                                                   unsigned Op,
06220                                                   Expr *lhs, Expr *rhs) {
06221   QualType ResultTy;     // Result type of the binary operator.
06222   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
06223   // The following two variables are used for compound assignment operators
06224   QualType CompLHSTy;    // Type of LHS after promotions for computation
06225   QualType CompResultTy; // Type of computation result
06226 
06227   switch (Opc) {
06228   case BinaryOperator::Assign:
06229     ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
06230     break;
06231   case BinaryOperator::PtrMemD:
06232   case BinaryOperator::PtrMemI:
06233     ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
06234                                             Opc == BinaryOperator::PtrMemI);
06235     break;
06236   case BinaryOperator::Mul:
06237   case BinaryOperator::Div:
06238     ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
06239                                            Opc == BinaryOperator::Div);
06240     break;
06241   case BinaryOperator::Rem:
06242     ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
06243     break;
06244   case BinaryOperator::Add:
06245     ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
06246     break;
06247   case BinaryOperator::Sub:
06248     ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
06249     break;
06250   case BinaryOperator::Shl:
06251   case BinaryOperator::Shr:
06252     ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
06253     break;
06254   case BinaryOperator::LE:
06255   case BinaryOperator::LT:
06256   case BinaryOperator::GE:
06257   case BinaryOperator::GT:
06258     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
06259     break;
06260   case BinaryOperator::EQ:
06261   case BinaryOperator::NE:
06262     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
06263     break;
06264   case BinaryOperator::And:
06265   case BinaryOperator::Xor:
06266   case BinaryOperator::Or:
06267     ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
06268     break;
06269   case BinaryOperator::LAnd:
06270   case BinaryOperator::LOr:
06271     ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
06272     break;
06273   case BinaryOperator::MulAssign:
06274   case BinaryOperator::DivAssign:
06275     CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
06276                                               Opc == BinaryOperator::DivAssign);
06277     CompLHSTy = CompResultTy;
06278     if (!CompResultTy.isNull())
06279       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06280     break;
06281   case BinaryOperator::RemAssign:
06282     CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
06283     CompLHSTy = CompResultTy;
06284     if (!CompResultTy.isNull())
06285       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06286     break;
06287   case BinaryOperator::AddAssign:
06288     CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
06289     if (!CompResultTy.isNull())
06290       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06291     break;
06292   case BinaryOperator::SubAssign:
06293     CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
06294     if (!CompResultTy.isNull())
06295       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06296     break;
06297   case BinaryOperator::ShlAssign:
06298   case BinaryOperator::ShrAssign:
06299     CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
06300     CompLHSTy = CompResultTy;
06301     if (!CompResultTy.isNull())
06302       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06303     break;
06304   case BinaryOperator::AndAssign:
06305   case BinaryOperator::XorAssign:
06306   case BinaryOperator::OrAssign:
06307     CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
06308     CompLHSTy = CompResultTy;
06309     if (!CompResultTy.isNull())
06310       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
06311     break;
06312   case BinaryOperator::Comma:
06313     ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
06314     break;
06315   }
06316   if (ResultTy.isNull())
06317     return ExprError();
06318   if (CompResultTy.isNull())
06319     return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
06320   else
06321     return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
06322                                                       CompLHSTy, CompResultTy,
06323                                                       OpLoc));
06324 }
06325 
06326 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
06327 /// ParenRange in parentheses.
06328 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
06329                                const PartialDiagnostic &PD,
06330                                SourceRange ParenRange,
06331                       const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
06332                                SourceRange SecondParenRange = SourceRange()) {
06333   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
06334   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
06335     // We can't display the parentheses, so just dig the
06336     // warning/error and return.
06337     Self.Diag(Loc, PD);
06338     return;
06339   }
06340 
06341   Self.Diag(Loc, PD)
06342     << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
06343     << CodeModificationHint::CreateInsertion(EndLoc, ")");
06344 
06345   if (!SecondPD.getDiagID())
06346     return;
06347 
06348   EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
06349   if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
06350     // We can't display the parentheses, so just dig the
06351     // warning/error and return.
06352     Self.Diag(Loc, SecondPD);
06353     return;
06354   }
06355 
06356   Self.Diag(Loc, SecondPD)
06357     << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
06358     << CodeModificationHint::CreateInsertion(EndLoc, ")");
06359 }
06360 
06361 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
06362 /// operators are mixed in a way that suggests that the programmer forgot that
06363 /// comparison operators have higher precedence. The most typical example of
06364 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
06365 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
06366                                       SourceLocation OpLoc,Expr *lhs,Expr *rhs){
06367   typedef BinaryOperator BinOp;
06368   BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
06369                 rhsopc = static_cast<BinOp::Opcode>(-1);
06370   if (BinOp *BO = dyn_cast<BinOp>(lhs))
06371     lhsopc = BO->getOpcode();
06372   if (BinOp *BO = dyn_cast<BinOp>(rhs))
06373     rhsopc = BO->getOpcode();
06374 
06375   // Subs are not binary operators.
06376   if (lhsopc == -1 && rhsopc == -1)
06377     return;
06378 
06379   // Bitwise operations are sometimes used as eager logical ops.
06380   // Don't diagnose this.
06381   if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
06382       (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
06383     return;
06384 
06385   if (BinOp::isComparisonOp(lhsopc))
06386     SuggestParentheses(Self, OpLoc,
06387       PDiag(diag::warn_precedence_bitwise_rel)
06388           << SourceRange(lhs->getLocStart(), OpLoc)
06389           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
06390       lhs->getSourceRange(),
06391       PDiag(diag::note_precedence_bitwise_first)
06392           << BinOp::getOpcodeStr(Opc),
06393       SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
06394   else if (BinOp::isComparisonOp(rhsopc))
06395     SuggestParentheses(Self, OpLoc,
06396       PDiag(diag::warn_precedence_bitwise_rel)
06397           << SourceRange(OpLoc, rhs->getLocEnd())
06398           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
06399       rhs->getSourceRange(),
06400       PDiag(diag::note_precedence_bitwise_first)
06401         << BinOp::getOpcodeStr(Opc),
06402       SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
06403 }
06404 
06405 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
06406 /// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
06407 /// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
06408 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
06409                                     SourceLocation OpLoc, Expr *lhs, Expr *rhs){
06410   if (BinaryOperator::isBitwiseOp(Opc))
06411     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
06412 }
06413 
06414 // Binary Operators.  'Tok' is the token for the operator.
06415 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
06416                                           tok::TokenKind Kind,
06417                                           ExprArg LHS, ExprArg RHS) {
06418   BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
06419   Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
06420 
06421   assert((lhs != 0) && "ActOnBinOp(): missing left expression");
06422   assert((rhs != 0) && "ActOnBinOp(): missing right expression");
06423 
06424   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
06425   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
06426 
06427   return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
06428 }
06429 
06430 Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
06431                                           BinaryOperator::Opcode Opc,
06432                                           Expr *lhs, Expr *rhs) {
06433   if (getLangOptions().CPlusPlus &&
06434       (lhs->getType()->isOverloadableType() ||
06435        rhs->getType()->isOverloadableType())) {
06436     // Find all of the overloaded operators visible from this
06437     // point. We perform both an operator-name lookup from the local
06438     // scope and an argument-dependent lookup based on the types of
06439     // the arguments.
06440     UnresolvedSet<16> Functions;
06441     OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
06442     if (S && OverOp != OO_None)
06443       LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
06444                                    Functions);
06445 
06446     // Build the (potentially-overloaded, potentially-dependent)
06447     // binary operation.
06448     return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
06449   }
06450 
06451   // Build a built-in binary operation.
06452   return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
06453 }
06454 
06455 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
06456                                                     unsigned OpcIn,
06457                                                     ExprArg InputArg) {
06458   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
06459 
06460   // FIXME: Input is modified below, but InputArg is not updated appropriately.
06461   Expr *Input = (Expr *)InputArg.get();
06462   QualType resultType;
06463   switch (Opc) {
06464   case UnaryOperator::OffsetOf:
06465     assert(false && "Invalid unary operator");
06466     break;
06467 
06468   case UnaryOperator::PreInc:
06469   case UnaryOperator::PreDec:
06470   case UnaryOperator::PostInc:
06471   case UnaryOperator::PostDec:
06472     resultType = CheckIncrementDecrementOperand(Input, OpLoc,
06473                                                 Opc == UnaryOperator::PreInc ||
06474                                                 Opc == UnaryOperator::PostInc);
06475     break;
06476   case UnaryOperator::AddrOf:
06477     resultType = CheckAddressOfOperand(Input, OpLoc);
06478     break;
06479   case UnaryOperator::Deref:
06480     DefaultFunctionArrayLvalueConversion(Input);
06481     resultType = CheckIndirectionOperand(Input, OpLoc);
06482     break;
06483   case UnaryOperator::Plus:
06484   case UnaryOperator::Minus:
06485     UsualUnaryConversions(Input);
06486     resultType = Input->getType();
06487     if (resultType->isDependentType())
06488       break;
06489     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
06490       break;
06491     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
06492              resultType->isEnumeralType())
06493       break;
06494     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
06495              Opc == UnaryOperator::Plus &&
06496              resultType->isPointerType())
06497       break;
06498 
06499     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06500       << resultType << Input->getSourceRange());
06501   case UnaryOperator::Not: // bitwise complement
06502     UsualUnaryConversions(Input);
06503     resultType = Input->getType();
06504     if (resultType->isDependentType())
06505       break;
06506     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
06507     if (resultType->isComplexType() || resultType->isComplexIntegerType())
06508       // C99 does not support '~' for complex conjugation.
06509       Diag(OpLoc, diag::ext_integer_complement_complex)
06510         << resultType << Input->getSourceRange();
06511     else if (!resultType->isIntegerType())
06512       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06513         << resultType << Input->getSourceRange());
06514     break;
06515   case UnaryOperator::LNot: // logical negation
06516     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
06517     DefaultFunctionArrayLvalueConversion(Input);
06518     resultType = Input->getType();
06519     if (resultType->isDependentType())
06520       break;
06521     if (!resultType->isScalarType()) // C99 6.5.3.3p1
06522       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
06523         << resultType << Input->getSourceRange());
06524     // LNot always has type int. C99 6.5.3.3p5.
06525     // In C++, it's bool. C++ 5.3.1p8
06526     resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
06527     break;
06528   case UnaryOperator::Real:
06529   case UnaryOperator::Imag:
06530     resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
06531     break;
06532   case UnaryOperator::Extension:
06533     resultType = Input->getType();
06534     break;
06535   }
06536   if (resultType.isNull())
06537     return ExprError();
06538 
06539   InputArg.release();
06540   return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
06541 }
06542 
06543 Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
06544                                             UnaryOperator::Opcode Opc,
06545                                             ExprArg input) {
06546   Expr *Input = (Expr*)input.get();
06547   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
06548       Opc != UnaryOperator::Extension) {
06549     // Find all of the overloaded operators visible from this
06550     // point. We perform both an operator-name lookup from the local
06551     // scope and an argument-dependent lookup based on the types of
06552     // the arguments.
06553     UnresolvedSet<16> Functions;
06554     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
06555     if (S && OverOp != OO_None)
06556       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
06557                                    Functions);
06558 
06559     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
06560   }
06561 
06562   return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
06563 }
06564 
06565 // Unary Operators.  'Tok' is the token for the operator.
06566 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
06567                                             tok::TokenKind Op, ExprArg input) {
06568   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
06569 }
06570 
06571 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
06572 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
06573                                             SourceLocation LabLoc,
06574                                             IdentifierInfo *LabelII) {
06575   // Look up the record for this label identifier.
06576   LabelStmt *&LabelDecl = getLabelMap()[LabelII];
06577 
06578   // If we haven't seen this label yet, create a forward reference. It
06579   // will be validated and/or cleaned up in ActOnFinishFunctionBody.
06580   if (LabelDecl == 0)
06581     LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
06582 
06583   // Create the AST node.  The address of a label always has type 'void*'.
06584   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
06585                                        Context.getPointerType(Context.VoidTy)));
06586 }
06587 
06588 Sema::OwningExprResult
06589 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
06590                     SourceLocation RPLoc) { // "({..})"
06591   Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
06592   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
06593   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
06594 
06595   bool isFileScope
06596     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
06597   if (isFileScope)
06598     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
06599 
06600   // FIXME: there are a variety of strange constraints to enforce here, for
06601   // example, it is not possible to goto into a stmt expression apparently.
06602   // More semantic analysis is needed.
06603 
06604   // If there are sub stmts in the compound stmt, take the type of the last one
06605   // as the type of the stmtexpr.
06606   QualType Ty = Context.VoidTy;
06607 
06608   if (!Compound->body_empty()) {
06609     Stmt *LastStmt = Compound->body_back();
06610     // If LastStmt is a label, skip down through into the body.
06611     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
06612       LastStmt = Label->getSubStmt();
06613 
06614     if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
06615       Ty = LastExpr->getType();
06616   }
06617 
06618   // FIXME: Check that expression type is complete/non-abstract; statement
06619   // expressions are not lvalues.
06620 
06621   substmt.release();
06622   return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
06623 }
06624 
06625 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
06626                                                   SourceLocation BuiltinLoc,
06627                                                   SourceLocation TypeLoc,
06628                                                   TypeTy *argty,
06629                                                   OffsetOfComponent *CompPtr,
06630                                                   unsigned NumComponents,
06631                                                   SourceLocation RPLoc) {
06632   // FIXME: This function leaks all expressions in the offset components on
06633   // error.
06634   // FIXME: Preserve type source info.
06635   QualType ArgTy = GetTypeFromParser(argty);
06636   assert(!ArgTy.isNull() && "Missing type argument!");
06637 
06638   bool Dependent = ArgTy->isDependentType();
06639 
06640   // We must have at least one component that refers to the type, and the first
06641   // one is known to be a field designator.  Verify that the ArgTy represents
06642   // a struct/union/class.
06643   if (!Dependent && !ArgTy->isRecordType())
06644     return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
06645 
06646   // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
06647   // with an incomplete type would be illegal.
06648 
06649   // Otherwise, create a null pointer as the base, and iteratively process
06650   // the offsetof designators.
06651   QualType ArgTyPtr = Context.getPointerType(ArgTy);
06652   Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
06653   Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
06654                                     ArgTy, SourceLocation());
06655 
06656   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
06657   // GCC extension, diagnose them.
06658   // FIXME: This diagnostic isn't actually visible because the location is in
06659   // a system header!
06660   if (NumComponents != 1)
06661     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
06662       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
06663 
06664   if (!Dependent) {
06665     bool DidWarnAboutNonPOD = false;
06666 
06667     if (RequireCompleteType(TypeLoc, Res->getType(),
06668                             diag::err_offsetof_incomplete_type))
06669       return ExprError();
06670 
06671     // FIXME: Dependent case loses a lot of information here. And probably
06672     // leaks like a sieve.
06673     for (unsigned i = 0; i != NumComponents; ++i) {
06674       const OffsetOfComponent &OC = CompPtr[i];
06675       if (OC.isBrackets) {
06676         // Offset of an array sub-field.  TODO: Should we allow vector elements?
06677         const ArrayType *AT = Context.getAsArrayType(Res->getType());
06678         if (!AT) {
06679           Res->Destroy(Context);
06680           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
06681             << Res->getType());
06682         }
06683 
06684         // FIXME: C++: Verify that operator[] isn't overloaded.
06685 
06686         // Promote the array so it looks more like a normal array subscript
06687         // expression.
06688         DefaultFunctionArrayLvalueConversion(Res);
06689 
06690         // C99 6.5.2.1p1
06691         Expr *Idx = static_cast<Expr*>(OC.U.E);
06692         // FIXME: Leaks Res
06693         if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
06694           return ExprError(Diag(Idx->getLocStart(),
06695                                 diag::err_typecheck_subscript_not_integer)
06696             << Idx->getSourceRange());
06697 
06698         Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
06699                                                OC.LocEnd);
06700         continue;
06701       }
06702 
06703       const RecordType *RC = Res->getType()->getAs<RecordType>();
06704       if (!RC) {
06705         Res->Destroy(Context);
06706         return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
06707           << Res->getType());
06708       }
06709 
06710       // Get the decl corresponding to this.
06711       RecordDecl *RD = RC->getDecl();
06712       if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
06713         if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
06714             DiagRuntimeBehavior(BuiltinLoc,
06715                                 PDiag(diag::warn_offsetof_non_pod_type)
06716                                   << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
06717                                   << Res->getType()))
06718           DidWarnAboutNonPOD = true;
06719       }
06720 
06721       LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
06722       LookupQualifiedName(R, RD);
06723 
06724       FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
06725       // FIXME: Leaks Res
06726       if (!MemberDecl)
06727         return ExprError(Diag(BuiltinLoc, diag::err_no_member)
06728          << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
06729 
06730       // FIXME: C++: Verify that MemberDecl isn't a static field.
06731       // FIXME: Verify that MemberDecl isn't a bitfield.
06732       if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
06733         Res = BuildAnonymousStructUnionMemberReference(
06734             OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
06735       } else {
06736         PerformObjectMemberConversion(Res, /*Qualifier=*/0, MemberDecl);
06737         // MemberDecl->getType() doesn't get the right qualifiers, but it
06738         // doesn't matter here.
06739         Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
06740                 MemberDecl->getType().getNonReferenceType());
06741       }
06742     }
06743   }
06744 
06745   return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
06746                                            Context.getSizeType(), BuiltinLoc));
06747 }
06748 
06749 
06750 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
06751                                                       TypeTy *arg1,TypeTy *arg2,
06752                                                       SourceLocation RPLoc) {
06753   // FIXME: Preserve type source info.
06754   QualType argT1 = GetTypeFromParser(arg1);
06755   QualType argT2 = GetTypeFromParser(arg2);
06756 
06757   assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
06758 
06759   if (getLangOptions().CPlusPlus) {
06760     Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
06761       << SourceRange(BuiltinLoc, RPLoc);
06762     return ExprError();
06763   }
06764 
06765   return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
06766                                                  argT1, argT2, RPLoc));
06767 }
06768 
06769 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
06770                                              ExprArg cond,
06771                                              ExprArg expr1, ExprArg expr2,
06772                                              SourceLocation RPLoc) {
06773   Expr *CondExpr = static_cast<Expr*>(cond.get());
06774   Expr *LHSExpr = static_cast<Expr*>(expr1.get());
06775   Expr *RHSExpr = static_cast<Expr*>(expr2.get());
06776 
06777   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
06778 
06779   QualType resType;
06780   bool ValueDependent = false;
06781   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
06782     resType = Context.DependentTy;
06783     ValueDependent = true;
06784   } else {
06785     // The conditional expression is required to be a constant expression.
06786     llvm::APSInt condEval(32);
06787     SourceLocation ExpLoc;
06788     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
06789       return ExprError(Diag(ExpLoc,
06790                        diag::err_typecheck_choose_expr_requires_constant)
06791         << CondExpr->getSourceRange());
06792 
06793     // If the condition is > zero, then the AST type is the same as the LSHExpr.
06794     resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
06795     ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
06796                                              : RHSExpr->isValueDependent();
06797   }
06798 
06799   cond.release(); expr1.release(); expr2.release();
06800   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
06801                                         resType, RPLoc,
06802                                         resType->isDependentType(),
06803                                         ValueDependent));
06804 }
06805 
06806 //===----------------------------------------------------------------------===//
06807 // Clang Extensions.
06808 //===----------------------------------------------------------------------===//
06809 
06810 /// ActOnBlockStart - This callback is invoked when a block literal is started.
06811 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
06812   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
06813   PushBlockScope(BlockScope, Block);
06814   CurContext->addDecl(Block);
06815   PushDeclContext(BlockScope, Block);
06816 }
06817 
06818 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
06819   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
06820   BlockScopeInfo *CurBlock = getCurBlock();
06821 
06822   if (ParamInfo.getNumTypeObjects() == 0
06823       || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
06824     ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
06825     QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
06826 
06827     if (T->isArrayType()) {
06828       Diag(ParamInfo.getSourceRange().getBegin(),
06829            diag::err_block_returns_array);
06830       return;
06831     }
06832 
06833     // The parameter list is optional, if there was none, assume ().
06834     if (!T->isFunctionType())
<